In dieser Anleitung wird beschrieben, wie Sie verwaltete Agents in der Gemini API mit dem Antigravity-Agent erstellen und verwenden. Sie führen Ihren ersten Agent-Aufruf aus, setzen eine Unterhaltung mit mehreren Schritten fort, streamen die Antwort, laden Dateien aus der Sandbox herunter und arbeiten mit dem verwalteten Antigravity-Agent.
Erste Agent-Interaktion ausführen
Ein einzelner Aufruf der Interactions API stellt eine Linux-Sandbox bereit, führt die Agent-Schleife aus und gibt das Ergebnis zurück. Sie definieren drei Parameter:
- Übergeben Sie den
agentals"antigravity-preview-05-2026",. Das ist die aktuelle Version unseres vordefinierten und universellen verwalteten Agents. - Definieren Sie
environment="remote", um eine neue Sandbox-Umgebung bereitzustellen. Erstellen Sie eine Eingabe, in der Sie definieren, was der Agent tun soll.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
environment="remote",
)
# Print the agent's final output
print(f"Interaction ID: {interaction.id}")
print(f"Environment ID: {interaction.environment_id}")
print(f"Output: {interaction.output_text}")
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents.",
environment: "remote",
});
console.log(`Interaction ID: ${interaction.id}`);
console.log(`Environment ID: ${interaction.environment_id}`);
console.log(`Output: ${interaction.output_text}`);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": [{"type": "text", "text": "Write a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt. Then read the file and print its contents."}],
"environment": {"type": "remote"}
}'
Die Antwort gibt ein Interaction-Objekt zurück. Speichern Sie interaction.id und interaction.environment_id, um die Unterhaltung in derselben Sandbox fortzusetzen. Verwenden Sie interaction.output_text, um auf die endgültige Antwort des Agents zuzugreifen. Unter interaction.steps sind alle Schritte aufgeführt, die der Agent ausgeführt hat (Begründung, Tool-Aufrufe, Codeausführung).
Unterhaltung fortsetzen (mehrere Schritte)
Die API verfolgt zwei unabhängige Zustandsdimensionen:
- Unterhaltungskontext:Chatverlauf, Begründungsablauf, Tool-Verwendung mit
previous_interaction_id. - **Umgebungsstatus**:Dateien, installierte Pakete und Sandbox-Status mit
environment.
Übergeben Sie beide an der entsprechenden Stelle, um fortzufahren:
Python
interaction_2 = client.interactions.create(
agent="antigravity-preview-05-2026",
previous_interaction_id=interaction.id,
environment=interaction.environment_id,
input="Now plot the Fibonacci sequence as a line chart and save it as chart.png.",
)
print(interaction_2.output_text)
JavaScript
const interaction2 = await client.interactions.create({
agent: "antigravity-preview-05-2026",
previous_interaction_id: interaction.id,
environment: interaction.environment_id,
input: "Now plot the Fibonacci sequence as a line chart and save it as chart.png.",
}, { timeout: 300_000 });
console.log(interaction2.output_text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
"agent": "antigravity-preview-05-2026",
"previous_interaction_id": "interaction_id_from_step_1",
"environment": "environment_id_from_step_1",
"input": [{"type": "text", "text": "Now plot the Fibonacci sequence as a line chart and save it as chart.png."}]
}'
Dateien aus Schritt 1 (fibonacci.txt) bleiben in Schritt 2 erhalten. Der Agent behält auch den Unterhaltungskontext bei.
Sie können diese unabhängig voneinander kombinieren:
- Unterhaltung löschen, Dateien behalten:Lassen Sie
previous_interaction_idweg und übergeben Sie nur die Umgebungs-ID mitenvironment, um eine neue Unterhaltung im selben Arbeitsbereich zu starten. - Unterhaltung behalten, neuer Arbeitsbereich: Übergeben Sie
previous_interaction_idund legen Sieenvironment="remote"für eine neue Sandbox fest.
Automatische Kontextkomprimierung
Bei langen Unterhaltungen mit mehreren Schritten kann der Rohverlauf von Begründungsschritten, Tool-Aufrufen und großen Dateiinhalten schnell anwachsen und viel Kontextraum verbrauchen. Um Fehler aufgrund von Tokenlimits zu vermeiden und den Fokus des Agents beizubehalten (und damit „Kontextverfall“ zu verhindern), bietet die Managed Agents API bei etwa 135.000 Tokens einen nativen Schritt zur Kontextkomprimierung. Dies geschieht automatisch.
Antwort streamen
Bei zeitaufwendigen Aufgaben können Sie die Antwort streamen, um die Arbeit des Agents in Echtzeit zu verfolgen:
Python
from google import genai
client = genai.Client()
stream = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",
environment="remote",
stream=True,
)
for event in stream:
print(event)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const stream = await client.interactions.create({
agent: "antigravity-preview-05-2026",
input: "Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",
environment: "remote",
stream: true,
});
for await (const event of stream) {
console.log(event);
}
REST
curl -N -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
"agent": "antigravity-preview-05-2026",
"input": "Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",
"environment": "remote",
"stream": true
}'
Beim Streaming wird eine iterierbare Liste von Schrittdeltas zurückgegeben. Das sind inkrementelle Text-, Begründungs-Tokens und Tool-Aufruf-Updates. Weitere Informationen zum Streamen von Antworten finden Sie im Leitfaden zum Streaming.
Dateien aus der Umgebung herunterladen
Wenn der Agent Dateien in der Sandbox erstellt. Laden Sie sie mit der Files API über eine direkte HTTP-Anfrage herunter (noch keine SDK-Methode):
Python
import os
import requests
import tarfile
env_id = interaction.environment_id
api_key = os.environ["GEMINI_API_KEY"]
response = requests.get(
f"https://generativelanguage.googleapis.com/v1beta/files/environment-{env_id}:download",
params={"alt": "media"},
headers={"x-goog-api-key": api_key},
allow_redirects=True,
)
with open("snapshot.tar", "wb") as f:
f.write(response.content)
with tarfile.open("snapshot.tar") as tar:
tar.extractall(path="extracted_snapshot")
JavaScript
import fs from "fs";
import { execSync } from "child_process";
const envId = interaction.environment_id;
const apiKey = process.env.GEMINI_API_KEY || "";
const url = `https://generativelanguage.googleapis.com/v1beta/files/environment-${envId}:download?alt=media`;
const response = await fetch(url, {
headers: {
"x-goog-api-key": apiKey,
},
});
if (!response.ok) {
throw new Error(`Failed to download file: ${response.statusText}`);
}
const buffer = Buffer.from(await response.arrayBuffer());
fs.writeFileSync("snapshot.tar", buffer);
if (!fs.existsSync("extracted_snapshot")) {
fs.mkdirSync("extracted_snapshot");
}
execSync("tar -xf snapshot.tar -C extracted_snapshot");
console.log(fs.readdirSync("extracted_snapshot"));
REST
curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/files/environment-$ENV_ID:download?alt=media" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-o snapshot.tar
tar -xf snapshot.tar -C extracted_snapshot
Verwalteten Agent speichern
In den vorherigen Schritten haben wir den Standard-Antigravity-Agent verwendet und ihn inline angepasst. Sobald Sie Ihre Konfiguration (Anweisungen, Fähigkeiten und Umgebung) durchlaufen haben, können Sie sie als verwalteten Agent speichern. So können Sie ihn per ID aufrufen, ohne die Konfiguration zu wiederholen.
Wenn Sie einen Agent speichern, definieren Sie eine base_environment (entweder aus Quellen oder durch Forking einer vorhandenen Umgebung). Der Agent verwendet diese Umgebung für jede neue Interaktion.
Aus Quellen:Definieren Sie Quellen inline oder aus anderen Quellen wie GitHub oder Cloud Storage.
Python
agent = client.agents.create(
id="fibonacci-analyst",
base_agent="antigravity-preview-05-2026",
system_instruction="You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
base_environment={
"type": "remote",
"sources": [
{
"type": "inline",
"target": ".agents/AGENTS.md",
"content": "Always include a chart and a summary table in your reports.",
},
{
"type": "repository",
"source": "https://github.com/your-org/skills",
"target": ".agents/skills"
}
],
},
)
print(f"Saved agent: {agent.id}")
JavaScript
const agent = await client.agents.create({
id: "fibonacci-analyst",
base_agent: "antigravity-preview-05-2026",
system_instruction: "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
base_environment: {
type: "remote",
sources: [
{
type: "inline",
target: ".agents/AGENTS.md",
content: "Always include a chart and a summary table in your reports.",
},
{
type: "repository",
source: "https://github.com/your-org/skills",
target: ".agents/skills"
}
],
},
});
console.log(`Saved agent: ${agent.id}`);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/agents" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
"id": "fibonacci-analyst",
"base_agent": "antigravity-preview-05-2026",
"system_instruction": "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",
"base_environment": {
"type": "remote",
"sources": [
{
"type": "inline",
"target": ".agents/AGENTS.md",
"content": "Always include a chart and a summary table in your reports."
},
{
"type": "repository",
"source": "https://github.com/your-org/skills",
"target": ".agents/skills"
}
]
}
}'
Verwalteten Agent aufrufen
Sobald Sie einen verwalteten Agent gespeichert haben, können Sie ihn per ID aufrufen. Bei jedem Aufruf wird die Basisumgebung geforkt, sodass jede Ausführung sauber beginnt:
Python
result = client.interactions.create(
agent="fibonacci-analyst",
input="Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",
environment="remote",
)
print(result.output_text)
JavaScript
const result = await client.interactions.create({
agent: "fibonacci-analyst",
input: "Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",
environment: "remote",
}, {
timeout: 300_000,
});
console.log(result.output_text);
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
"agent": "fibonacci-analyst",
"environment": "remote",
"input": "Generate the first 50 prime numbers, plot their distribution, and save a PDF report."
}'
Nächste Schritte
- Antigravity-Agent: Funktionen, unterstützte Tools, multimodale Eingabe, Preise und Einschränkungen.
- Verwaltete Agents erstellen: Antigravity mit eigenen Anweisungen, Fähigkeiten und Daten erweitern.
- Umgebungen: Quellen, Netzwerke, Lebenszyklus, Ressourcenlimits.
- Interactions API: die zugrunde liegende API für Modelle und Agents.