Repository Public
1This guide walks you through creating and using Managed Agents on the Gemini API, using the [Antigravity agent](https://ai.google.dev/gemini-api/docs/agents/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.23## Run your first agent interaction45A single call to the [Interactions API](https://ai.google.dev/gemini-api/docs) provisions a Linux sandbox, runs the agent loop, and returns the result. You'll define three parameters:67- Pass in the `agent` as `"antigravity-preview-09-2026",` which is the current version of our predefined and general purpose managed agent.8- Define `environment="remote"`, to provision a new, fresh sandbox environment.9- Create an input, defining what you want the agent to do.1011### Python1213 from google import genai1415 client = genai.Client()1617 interaction = client.interactions.create(18 agent="antigravity-preview-09-2026",19 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.",20 environment="remote",21 )2223 # Print the agent's final output24 print(f"Interaction ID: {interaction.id}")25 print(f"Environment ID: {interaction.environment_id}")26 print(f"Output: {interaction.output_text}")2728### JavaScript2930 import { GoogleGenAI } from "@google/genai";3132 const client = new GoogleGenAI({});3334 const interaction = await client.interactions.create({35 agent: "antigravity-preview-09-2026",36 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.",37 environment: "remote",38 });3940 console.log(`Interaction ID: ${interaction.id}`);41 console.log(`Environment ID: ${interaction.environment_id}`);4243 console.log(`Output: ${interaction.output_text}`);4445### Java4647 import com.google.genai.Client;48 import com.google.genai.gaos.models.interactions.AgentOption;49 import com.google.genai.gaos.models.interactions.CreateAgentInteraction;50 import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;51 import com.google.genai.gaos.models.interactions.Interaction;52 import com.google.genai.gaos.models.interactions.InteractionsInput;53 import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;5455 Client client = new Client();5657 CreateAgentInteraction params = CreateAgentInteraction.builder()58 .agent(AgentOption.of("antigravity-preview-09-2026"))59 .input(InteractionsInput.of("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."))60 .environment(CreateAgentInteractionEnvironment.of("remote"))61 .build();6263 Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();6465 // Print the agent's final output66 System.out.println("Interaction ID: " + interaction.id().orElse(""));67 System.out.println("Environment ID: " + interaction.environmentId().orElse(""));68 System.out.println("Output: " + interaction.outputText().orElse(""));6970### REST7172 curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \73 -H "Content-Type: application/json" \74 -H "x-goog-api-key: $GEMINI_API_KEY" \75 -d '{76 "agent": "antigravity-preview-09-2026",77 "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."}],78 "environment": {"type": "remote"}79 }'8081The 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).8283## Continue the conversation (multi-turn)8485The API tracks two independent state dimensions:8687- **Conversation context:** chat history, reasoning trace, tool use, using `previous_interaction_id`.88- [**Environment state:**](https://ai.google.dev/gemini-api/docs/agent-environment) files, installed packages and sandbox state, using `environment`.8990Pass both in their respective place to resume:9192### Python9394 interaction_2 = client.interactions.create(95 agent="antigravity-preview-09-2026",96 previous_interaction_id=interaction.id,97 environment=interaction.environment_id,98 input="Now plot the Fibonacci sequence as a line chart and save it as chart.png.",99 )100101 print(interaction_2.output_text)102103### JavaScript104105 const interaction2 = await client.interactions.create({106 agent: "antigravity-preview-09-2026",107 previous_interaction_id: interaction.id,108 environment: interaction.environment_id,109 input: "Now plot the Fibonacci sequence as a line chart and save it as chart.png.",110 }, { timeout: 300_000 });111112 console.log(interaction2.output_text);113114### Java115116 import com.google.genai.Client;117 import com.google.genai.gaos.models.interactions.AgentOption;118 import com.google.genai.gaos.models.interactions.CreateAgentInteraction;119 import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;120 import com.google.genai.gaos.models.interactions.Interaction;121 import com.google.genai.gaos.models.interactions.InteractionsInput;122 import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;123124 Client client = new Client();125 String interactionId = "INTERACTION_ID";126 String environmentId = "ENVIRONMENT_ID";127128 CreateAgentInteraction params = CreateAgentInteraction.builder()129 .agent(AgentOption.of("antigravity-preview-09-2026"))130 .previousInteractionId(interactionId)131 .environment(CreateAgentInteractionEnvironment.of(environmentId))132 .input(InteractionsInput.of("Now plot the Fibonacci sequence as a line chart and save it as chart.png."))133 .build();134135 Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();136 System.out.println(interaction2.outputText().orElse(""));137138### REST139140 curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \141 -H "Content-Type: application/json" \142 -H "x-goog-api-key: $GEMINI_API_KEY" \143 -d '{144 "agent": "antigravity-preview-09-2026",145 "previous_interaction_id": "interaction_id_from_step_1",146 "environment": "environment_id_from_step_1",147 "input": [{"type": "text", "text": "Now plot the Fibonacci sequence as a line chart and save it as chart.png."}]148 }'149150Files from turn 1 (`fibonacci.txt`) persist in turn 2. The agent also retains conversation context.151152You can mix and match these independently:153154- **Clear conversation, keep files:** Omit `previous_interaction_id`, only pass the environment ID using `environment` for a fresh conversation in the same workspace.155- **Keep conversation, new workspace:** Pass `previous_interaction_id`, set `environment="remote"` for a fresh sandbox.156157### Automatic context compaction158159In 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 Agents API features a native context compaction step at around 135k tokens. This happens automatically.160161## Stream the response162163For long-running tasks, you can stream the response to see the agent work in real time:164165### Python166167 from google import genai168169 client = genai.Client()170171 stream = client.interactions.create(172 agent="antigravity-preview-09-2026",173 input="Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",174 environment="remote",175 stream=True,176 )177178 for event in stream:179 print(event)180 if event.event_type == "step.stop" and event.usage:181 print(event.usage)182183### JavaScript184185 import { GoogleGenAI } from "@google/genai";186187 const client = new GoogleGenAI({});188189 const stream = await client.interactions.create({190 agent: "antigravity-preview-09-2026",191 input: "Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",192 environment: "remote",193 stream: true,194 });195196 for await (const event of stream) {197 console.log(event);198 if (event.event_type === "step.stop" && event.usage) {199 console.log(event.usage);200 }201 }202203### Java204205 import com.google.genai.Client;206 import com.google.genai.gaos.models.interactions.AgentOption;207 import com.google.genai.gaos.models.interactions.CreateAgentInteraction;208 import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;209 import com.google.genai.gaos.models.interactions.InteractionSSEStreamEvent;210 import com.google.genai.gaos.models.interactions.InteractionsInput;211 import com.google.genai.gaos.models.interactions.StepStop;212 import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;213 import com.google.genai.gaos.utils.EventStream;214215 Client client = new Client();216217 CreateAgentInteraction params = CreateAgentInteraction.builder()218 .agent(AgentOption.of("antigravity-preview-09-2026"))219 .input(InteractionsInput.of("Read Hacker News, summarize the top 5 stories, and save the results as a PDF."))220 .environment(CreateAgentInteractionEnvironment.of("remote"))221 .stream(true)222 .build();223224 try (EventStream<InteractionSSEStreamEvent> stream =225 client.interactions.create(CreateInteractionRequestBody.of(params)).events()) {226 for (InteractionSSEStreamEvent event : stream) {227 System.out.println(event);228 if (event.data().isPresent() && event.data().get() instanceof StepStop stepStop) {229 stepStop.usage().ifPresent(System.out::println);230 }231 }232 }233234### REST235236 curl -N -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \237 -H "Content-Type: application/json" \238 -H "x-goog-api-key: $GEMINI_API_KEY" \239 -d '{240 "agent": "antigravity-preview-09-2026",241 "input": "Read Hacker News, summarize the top 5 stories, and save the results as a PDF.",242 "environment": "remote",243 "stream": true244 }'245246Streaming returns step deltas with incremental updates. When a step completes,247the `step.stop` event includes accumulated usage stats. Learn more in the248[Streaming guide](https://ai.google.dev/gemini-api/docs/streaming).249250## Download files from the environment251252When the agent creates files inside the sandbox. Download them using the Files API with a direct HTTP request (no SDK method yet):253254### Python255256 import os257 import requests258 import tarfile259260 env_id = interaction.environment_id261 api_key = os.environ["GEMINI_API_KEY"]262263 response = requests.get(264 f"https://generativelanguage.googleapis.com/v1beta/files/environment-{env_id}:download",265 params={"alt": "media"},266 headers={"x-goog-api-key": api_key},267 allow_redirects=True,268 )269270 with open("snapshot.tar", "wb") as f:271 f.write(response.content)272273 with tarfile.open("snapshot.tar") as tar:274 tar.extractall(path="extracted_snapshot")275276### JavaScript277278 import fs from "fs";279 import { execSync } from "child_process";280281 const envId = interaction.environment_id;282 const apiKey = process.env.GEMINI_API_KEY || "";283284 const url = `https://generativelanguage.googleapis.com/v1beta/files/environment-${envId}:download?alt=media`;285 const response = await fetch(url, {286 headers: {287 "x-goog-api-key": apiKey,288 },289 });290291 if (!response.ok) {292 throw new Error(`Failed to download file: ${response.statusText}`);293 }294295 const buffer = Buffer.from(await response.arrayBuffer());296 fs.writeFileSync("snapshot.tar", buffer);297298 if (!fs.existsSync("extracted_snapshot")) {299 fs.mkdirSync("extracted_snapshot");300 }301 execSync("tar -xf snapshot.tar -C extracted_snapshot");302303 console.log(fs.readdirSync("extracted_snapshot"));304305### Java306307 import java.net.URI;308 import java.net.http.HttpClient;309 import java.net.http.HttpRequest;310 import java.net.http.HttpResponse;311 import java.nio.file.Files;312 import java.nio.file.Paths;313314 String envId = "ENVIRONMENT_ID";315 String apiKey = System.getenv("GEMINI_API_KEY");316317 HttpClient httpClient = HttpClient.newBuilder()318 .followRedirects(HttpClient.Redirect.NORMAL)319 .build();320321 HttpRequest request = HttpRequest.newBuilder()322 .uri(URI.create("https://generativelanguage.googleapis.com/v1beta/files/environment-" + envId + ":download?alt=media"))323 .header("x-goog-api-key", apiKey)324 .GET()325 .build();326327 HttpResponse<byte[]> response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());328 Files.write(Paths.get("snapshot.tar"), response.body());329 System.out.println("Saved snapshot to snapshot.tar");330331### REST332333 ENV_ID="your_environment_id_here"334335 curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/files/environment-$ENV_ID:download?alt=media" \336 -H "x-goog-api-key: $GEMINI_API_KEY" \337 -o snapshot.tar338339 mkdir -p extracted_snapshot340 tar -xf snapshot.tar -C extracted_snapshot341342## Save a managed agent343344In the previous steps, we used the default Antigravity agent and customized it inline. Once you have iterated on your configuration (instructions, skills, model selection, and environment), you can save it as a reusable managed agent. This allows you to invoke it by ID without repeating the configuration.345346When you save an agent, notice the architectural symmetry with inline interactions: you specify `base_agent: "antigravity-preview-09-2026"` and can pass an `agent_config` with your chosen `model` just as you would on `interactions.create`. You also define a `base_environment` (either from sources or by forking an existing environment). The agent will use this environment and model configuration for every new interaction.347348**From sources:** Define sources inline, or from other sources such as GitHub or Cloud Storage.349350### Python351352 agent = client.agents.create(353 id="fibonacci-analyst",354 base_agent="antigravity-preview-09-2026",355 agent_config={356 "type": "antigravity",357 "model": "gemini-3.8-flash",358 },359 system_instruction="You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",360 base_environment={361 "type": "remote",362 "sources": [363 {364 "type": "inline",365 "target": ".agents/AGENTS.md",366 "content": "Always include a chart and a summary table in your reports.",367 },368 {369 "type": "repository",370 "source": "https://github.com/your-org/skills",371 "target": ".agents/skills"372 }373 ],374 },375 )376377 print(f"Saved agent: {agent.id}")378379### JavaScript380381 const agent = await client.agents.create({382 id: "fibonacci-analyst",383 base_agent: "antigravity-preview-09-2026",384 agent_config: {385 type: "antigravity",386 model: "gemini-3.8-flash",387 },388 system_instruction: "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",389 base_environment: {390 type: "remote",391 sources: [392 {393 type: "inline",394 target: ".agents/AGENTS.md",395 content: "Always include a chart and a summary table in your reports.",396 },397 {398 type: "repository",399 source: "https://github.com/your-org/skills",400 target: ".agents/skills"401 }402 ],403 },404 });405406 console.log(`Saved agent: ${agent.id}`);407408### Java409410 import com.google.genai.Client;411 import com.google.genai.gaos.models.agents.Agent;412 import com.google.genai.gaos.models.agents.AgentConfig;413 import com.google.genai.gaos.models.agents.BaseEnvironment;414 import com.google.genai.gaos.models.interactions.AntigravityAgentConfig;415 import com.google.genai.gaos.models.interactions.Environment;416 import com.google.genai.gaos.models.interactions.Source;417 import com.google.genai.gaos.models.interactions.SourceType;418 import java.util.List;419420 Client client = new Client();421422 Environment env = Environment.builder()423 .sources(List.of(424 Source.builder()425 .type(SourceType.INLINE)426 .target(".agents/AGENTS.md")427 .content("Always include a chart and a summary table in your reports.")428 .build(),429 Source.builder()430 .type(SourceType.REPOSITORY)431 .source("https://github.com/your-org/skills")432 .target(".agents/skills")433 .build()434 ))435 .build();436437 Agent agentParams = Agent.builder()438 .id("fibonacci-analyst")439 .baseAgent("antigravity-preview-09-2026")440 .agentConfig(AgentConfig.of(441 AntigravityAgentConfig.builder()442 .model("gemini-3.8-flash")443 .build()444 ))445 .systemInstruction("You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.")446 .baseEnvironment(BaseEnvironment.of(env))447 .build();448449 Agent agent = client.agents.create(agentParams).agent().get();450 System.out.println("Saved agent: " + agent.id().orElse(""));451452### REST453454 curl -X POST "https://generativelanguage.googleapis.com/v1beta/agents" \455 -H "Content-Type: application/json" \456 -H "x-goog-api-key: $GEMINI_API_KEY" \457 -d '{458 "id": "fibonacci-analyst",459 "base_agent": "antigravity-preview-09-2026",460 "agent_config": {461 "type": "antigravity",462 "model": "gemini-3.8-flash"463 },464 "system_instruction": "You are a math analysis agent. Generate sequences, visualize them, and export results as PDF reports.",465 "base_environment": {466 "type": "remote",467 "sources": [468 {469 "type": "inline",470 "target": ".agents/AGENTS.md",471 "content": "Always include a chart and a summary table in your reports."472 },473 {474 "type": "repository",475 "source": "https://github.com/your-org/skills",476 "target": ".agents/skills"477 }478 ]479 }480 }'481482## Invoke the managed agent483484Once you've saved a managed agent, you can invoke it by ID. Each invocation forks the base environment, so every run starts clean:485486### Python487488 result = client.interactions.create(489 agent="fibonacci-analyst",490 input="Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",491 environment="remote",492 )493494 print(result.output_text)495496### JavaScript497498 const result = await client.interactions.create({499 agent: "fibonacci-analyst",500 input: "Generate the first 50 prime numbers, plot their distribution, and save a PDF report.",501 environment: "remote",502 }, {503 timeout: 300_000,504 });505506 console.log(result.output_text);507508### Java509510 import com.google.genai.Client;511 import com.google.genai.gaos.models.interactions.AgentOption;512 import com.google.genai.gaos.models.interactions.CreateAgentInteraction;513 import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;514 import com.google.genai.gaos.models.interactions.Interaction;515 import com.google.genai.gaos.models.interactions.InteractionsInput;516 import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;517518 Client client = new Client();519520 CreateAgentInteraction params = CreateAgentInteraction.builder()521 .agent(AgentOption.of("fibonacci-analyst"))522 .input(InteractionsInput.of("Generate the first 50 prime numbers, plot their distribution, and save a PDF report."))523 .environment(CreateAgentInteractionEnvironment.of("remote"))524 .build();525526 Interaction result = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();527 System.out.println(result.outputText().orElse(""));528529### REST530531 curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \532 -H "Content-Type: application/json" \533 -H "x-goog-api-key: $GEMINI_API_KEY" \534 -d '{535 "agent": "fibonacci-analyst",536 "environment": "remote",537 "input": "Generate the first 50 prime numbers, plot their distribution, and save a PDF report."538 }'539540## What's next541542- [Antigravity Agent](https://ai.google.dev/gemini-api/docs/antigravity-agent): capabilities, supported tools, multimodal input, pricing, and limitations.543- [Building Managed Agents](https://ai.google.dev/gemini-api/docs/custom-agents): extend Antigravity with your own instructions, skills, and data.544- [Environments](https://ai.google.dev/gemini-api/docs/agent-environment): sources, networking, lifecycle, resource limits.545- [Interactions API](https://ai.google.dev/gemini-api/docs/interactions-overview): the underlying API for models and agents.