This guide walks you through creating and using Managed Agents on the Gemini API, using the Antigravity agent. You'll make your first agent call, continue a multi-turn conversation, stream the response, download files from the sandbox, and work with the Antigravity managed agent.
Run your first agent interaction
A single call to the Interactions API provisions a Linux sandbox, runs the agent loop, and returns the result. You'll define three parameters:
- Pass in the
agentas"antigravity-preview-05-2026", which is the current version of our predefined and general purpose managed agent. - Define
environment="remote", to provision a new, fresh sandbox environment. Create an input, defining what you want the agent to do.
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"}
}'
The response returns an Interaction object. Store interaction.id and interaction.environment_id to continue the conversation in the same sandbox. Use interaction.output_text to access the agent's final response. interaction.steps lists each step the agent took (reasoning, tool calls, code execution).
Continue the conversation (multi-turn)
The API tracks two independent state dimensions:
- Conversation context: chat history, reasoning trace, tool use, using
previous_interaction_id. - Environment state: files, installed packages and sandbox state, using
environment.
Pass both in their respective place to resume the conversation:
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."}]
}'
Files from turn 1 (fibonacci.txt) persist in turn 2. The agent also retains conversation context.
You can mix and match these states independently:
- Clear conversation, keep files: Omit
previous_interaction_id, only pass the environment ID usingenvironmentfor a fresh conversation in the same workspace. - Keep conversation, new workspace: Pass
previous_interaction_id, setenvironment="remote"for a fresh sandbox.
Automatic context compaction
In long-running, multi-turn conversations, the raw history of reasoning steps, tool calls, and large file contents can quickly grow and consume significant context space. To prevent token limit errors and maintain the agent's focus (preventing "context rot"), the managed agent features a native context compaction step at around 135k tokens. You don't need to do anything for this to happen.
Stream the response
For long-running tasks, you can stream the response by setting stream: true, to see the agent work in real time:
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
}'
Streaming returns an iterable of step deltas, which are incremental text, reasoning tokens, and tool call updates. Learn more about how to stream responses in the Streaming guide.
Download files from the environment
The agent can create files inside the sandbox. To download them, you can use the Files API with a direct HTTP request:
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
Build a custom agent
In previous steps, we used the default agent: Antigravity Agent. You can instead create a custom agent by bundling instructions, tools, and environment sources into a named agent. Invoke it by ID instead of repeating configuration.
Once you define the base environment, either from source or from an existing environment, the agent will use it for every new interaction instead of the default fresh sandbox. For more information on environments, see Environments.
From sources: You can define sources inline, or from other sources such as GitHub or Cloud Storage. This example defines an AGENTS.md file and a Skills directory from GitHub:
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"Created 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(`Created 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"
}
]
}
}'
From an existing environment: Iterate on an environment through interactions, and then set it as the base for your agent referencing its id:
Python
agent = client.agents.create(
id="fibonacci-analyst",
base_agent="antigravity-preview-05-2026",
system_instruction="You are a math analysis agent.",
base_environment=interaction.environment_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.",
base_environment: interaction.environment_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.",
"base_environment": "environment_id_from_previous_interaction"
}'
The agent automatically loads .agents/AGENTS.md as system instructions and any SKILL.md files under .agents/skills/ as capabilities. See Building Custom Agents for the full agent definition format, skills, and advanced configuration.
Invoke the custom agent
Once you've created a custom agent, you can invoke it by name instead of repeating configuration. Each invocation forks the base environment, so every run starts clean:
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."
}'
It uses the previously defined system_instruction, tools, and environment forks from base_environment. Everything can also be overridden per interaction.
What's next
- Agents Overview: Learn about the core concepts of managed agents.
- Antigravity Agent: Explore capabilities, tools, and pricing for the default agent.
- Agent Environments: Configure sandboxes, sources, and networking.
- Building Custom Agents: Define your own agents using
AGENTS.mdandSKILL.md.