How to Build Managed Agents in the Gemini API: Step by Step Guide
By Braincuber Team
Published on May 23, 2026
Imagine having an autonomous worker with access to its own isolated computer. When given a task, such as analyzing a dataset, the agent autonomously writes and executes the code required to complete the work. Once the process is finished, you can access the agent's workspace to retrieve your results. In this complete tutorial, you will learn how to build managed agents in the Gemini API, deploy autonomous data analyst agents with a single API call, and leverage sandboxed code execution, persistent file management, and web integration to build powerful AI-driven data workflows without managing infrastructure.
What You'll Learn in this Beginner Guide:
- What Gemini Managed Agents are and how they work under the hood.
- How to set up the API environment, create API keys, and configure billing.
- How to spin up agents, share files, and persist state across multiple interactions.
- How to build a complete data analyst agent that loads, analyzes, and visualizes a Netflix dataset.
- How to customize agent behavior with AGENTS.md and SKILL.md files for reusable, modular skills.
How Do Managed Agents Work?
Managed Agents allow you to deploy autonomous AI agents with a single API call. These agents can reason, plan, and execute code in an isolated, temporary Linux environment. They are powered by Google's Antigravity agent, a general-purpose agent harness for Gemini models. It provides a pre-configured suite of operational tools directly within the runtime environment, eliminating the need for manual setup.
Sandboxed Code Execution
Write, debug, and run code in Bash, Python, or Node.js within a fully isolated Linux sandbox with no manual environment setup.
Persistent File Management
Read, write, edit, and search for files across sequential turns with a persistent filesystem in the remote container.
Web Integration
Access Google Search for live information grounding, and fetch and parse unstructured online data on demand.
Isolated Linux Sandbox
Each agent runs in its own isolated environment with persistent state for up to 7 days, keeping your workspace secure and clean.
Understanding Managed Agent Costs
There are many components involved in the pricing of Gemini Managed Agents. The cost is driven by four main factors as outlined below:
| Component | Description |
|---|---|
| Model Usage (Tokens) | Charged based on the number of input and output tokens processed, including intermediate reasoning and script generation. |
| Infrastructure and Platform Fees | Service fees for using the platform tools to manage and deploy agents. |
| Context Caching | Agents can reuse the same data, providing significant cost reductions compared to standard token pricing. |
| Grounding Services | Google Search or Google Maps queries are billed separately, with a quota of free requests and per-query costs. |
The antigravity-preview-05-2026 agent is powered by Gemini 3.5 Flash. Token costs for this model are approximately $1.50 per million text input tokens, $9.00 per million text output tokens, and $0.15 per million context cache hit (input) tokens.
Billing Is Required Before Running Agents
Before creating or interacting with agents, you must set up billing on your Google AI Studio API key. Without billing, all requests will be denied because Google cannot charge for token usage.
Beginner Guide: Setting Up the API Environment
Before you can build managed agents, you need to configure your Google AI Studio API environment. This step by step guide covers creating an API key, setting up billing, and configuring your local Python environment with Anaconda.
Create a Google AI Studio API Key
Navigate to Google AI Studio and click the Create API Key button at the top right. You will be prompted to select or create a Google Cloud project to associate with the key. Once created, copy the key for the next step.
Store the API Key Securely
In your project folder, create a .env file and store the API key as follows. This keeps your sensitive credentials out of your source code.
GEMINI_API_KEY=<paste_your_api_key_here>
Set Up Billing
In Google AI Studio, locate the Set up billing button next to your newly created API key. Without billing enabled, all agent requests will be denied. Add a payment method or link your project to an existing billing account.
Create and Activate a Conda Environment
We use Anaconda to manage the Python environment for this project. Run the following commands in your terminal to create and activate the environment.
conda create --name gemini_agents python=3.12 -y
conda activate gemini_agents
pip install google-genai requests python-dotenv
How to Interact with a Managed Agent
With the environment ready, you can now create your first managed agent interaction. The following example demonstrates a simple agent interaction that installs matplotlib and reports its version. This step by step guide breaks down every line of code so you understand how the API works from the ground up.
from dotenv import load_dotenv
from google import genai
# Load secure environment variables
load_dotenv()
# Initialize the GenAI Client
client = genai.Client()
# Create a basic interaction with a managed agent
interaction = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Install the matplotlib package, verify its version, and report back.",
environment="remote"
)
# Output the status of the agent
print(f"Status: {interaction.status}")
print(f"Environment ID: {interaction.environment_id}")
print(f"Output:
{interaction.output_text}")
When you run this script, the agent installs matplotlib inside its sandbox and returns a confirmation message similar to this:
Status: completed
Environment ID: 104ad7f8-32e0-4b8d-b344-24d92eb74eb6
Output:
I have successfully installed the matplotlib package.
Installed Version: 3.10.9
Understanding the Sandbox Lifecycle
The environment_id returned in the interaction is the identifier of the sandbox where the agent executed. This environment is ephemeral and retained for up to 7 days after the last activity before being deleted. The lifecycle stages are: Created/Active, Idle, Offline, and Deleted. While the environment exists, you can access it and perform further interactions using its environment_id.
Performing Multiple Interactions with Persistence
To build meaningful workflows, you need to chain multiple interactions together while preserving the agent's workspace and conversation history. You do this by passing two key parameters in subsequent interaction calls:
# First interaction
inter1 = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Write a Python script sum.py that adds all integers from 1 to 100.",
environment="remote"
)
# Second interaction — preserves history and workspace
inter2 = client.interactions.create(
agent="antigravity-preview-05-2026",
previous_interaction_id=inter1.id, # Passes conversation history
environment=inter1.environment_id, # Keeps the same filesystem state
input="Execute 'sum.py' using Python and display the standard output."
)
print(f"Output:
{inter2.output_text}")
Sharing Files with Managed Agents
To build a data analyst agent, you need to share data with it. There are several methods, each suited to different file sizes and use cases. The table below summarizes all available methods and their ideal use cases.
| Method | Best For | Max Size |
|---|---|---|
| Inline Data | Small local files loaded as strings | 1 MB per file, 2 MB total |
| Hosted File | Files accessible via public URL | No strict limit |
| GitHub Repository | Larger datasets or project files | Repository size |
| Google Cloud Bucket | Enterprise-scale data sharing | Bucket quotas |
Sharing Inline Data
Inline data is ideal for small files. You load the file content as a string and pass it directly in the interaction payload. The target location in the agent environment should always be inside the /workspace folder.
inter = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Add all the numbers in the /workspace/numbers.txt file.",
environment={
"type": "remote",
"sources": [
{
"type": "inline",
"target": "/workspace/numbers.txt",
"content": utils.read_text_file("data/numbers.txt")
}
]
}
)
Sharing a GitHub Repository
For larger files or project-based datasets, providing a GitHub repository URL is the most practical approach. The agent clones the entire repository into its workspace.
inter = client.interactions.create(
agent="antigravity-preview-05-2026",
input="Add all the numbers in /workspace/repository/numbers.txt.",
environment={
"type": "remote",
"sources": [
{
"type": "repository",
"source": "https://github.com/fran-aubry/gemini-agents-tutorial",
"target": "/workspace/repository"
}
]
}
)
Downloading an Agent's Environment
After the agent generates files like charts or reports, you can download its entire workspace to retrieve the results. Each workspace can be downloaded at a specific URL using the environment ID.
def download_env(env_id, path="environments"):
download_url = f"https://generativelanguage.googleapis.com/v1beta/files/environment-{env_id}:download"
try:
request_params = {"alt": "media"}
request_headers = {"x-goog-api-key": os.environ.get("GEMINI_API_KEY")}
response = requests.get(
download_url,
params=request_params,
headers=request_headers,
allow_redirects=True
)
response.raise_for_status()
archive_name = f"{env_id}.tar"
output_path = os.path.join(path, archive_name)
with open(output_path, "wb") as archive_file:
archive_file.write(response.content)
print(f"Successfully downloaded workspace: {output_path}")
except requests.exceptions.RequestException as error:
print(f"Failed to download workspace: {error}")
How to Build a Data Analyst Agent
Now that you know how to create agents, share files, and download environments, it is time to build a complete data analyst agent. In this example, we will create an agent that analyzes a Netflix dataset to find the most-watched genres. The agent will be customized with behavior instructions and modular skills.
Step 1: Create the Agent
Instead of interacting directly with the base antigravity-preview-05-2026 agent, you can create your own agent using client.agents.create(). This lets you define custom behavior and attach specific skills.
agent = client.agents.create(
id="data-analyst",
base_agent="antigravity-preview-05-2026",
base_environment={
"type": "remote",
"sources": [
{
"type": "inline",
"target": ".agents/AGENTS.md",
"content": read_text_file(".agents/AGENTS.md")
},
{
"type": "inline",
"target": ".agents/skills/csv-aggregator/SKILL.md",
"content": read_text_file(".agents/skills/csv-aggregator/SKILL.md")
},
{
"type": "repository",
"source": "https://github.com/fran-aubry/gemini-agents-tutorial",
"target": "/workspace/repository"
}
]
}
)
Step 2: Understanding AGENTS.md
The AGENTS.md file acts as the system prompt for your agent. It is your primary instruction manual where you define the agent's specific role, main goals, and operational boundaries. You should also list any specific tools or data sources the agent is allowed to access and provide examples of how you want it to communicate or handle tasks. The location must be .agents/AGENTS.md.
Step 3: Understanding SKILL.md
Skill files are used to equip the agent with specific, repeatable capabilities. Each skill is described in a SKILL.md file located at .agents/skills/<skill_name>/SKILL.md. The structure is standardized:
---
name: <skill_name>
description: <description of when to use the skill>
---
<steps on how to perform the task>
Step 4: Putting It All Together
Below is the complete script for analyzing Netflix genres. It initializes the agent, installs matplotlib, triggers the csv-aggregator skill, executes the generated script, and downloads the environment to retrieve the chart.
from dotenv import load_dotenv
from google import genai
import utils
load_dotenv()
client = genai.Client()
# Create or load the data-analyst agent
data_analyst = utils.load_or_create_agent(client, "data-analyst")
print(f"Agent '{data_analyst.id}' initialized.")
# Step 1: Install matplotlib
inter1 = client.interactions.create(
agent=data_analyst.id,
input="Install the matplotlib package.",
environment="remote"
)
# Step 2: Analyze Netflix dataset by genre
inter2 = client.interactions.create(
agent=data_analyst.id,
input="Use the csv-aggregator to plot the top 10 genres from /workspace/repository/data/netflix.csv in terms of viewership.",
environment=inter1.environment_id
)
# Step 3: Execute the generated script
inter3 = client.interactions.create(
agent=data_analyst.id,
input="Execute the genres.py script using python.",
environment=inter2.environment_id
)
# Step 4: Download the environment with the chart
utils.download_env(inter3.environment_id)
The output after running this script is a bar chart showing the most viewed Netflix shows by genre, generated and saved inside the agent's sandbox, then downloaded to your local machine.
Summary and Next Steps
In this complete tutorial, you learned how to build and deploy managed agents using the Gemini API with a single API call. You set up the Python environment, authenticated with the Google AI Studio API, and built a data analyst agent capable of installing dependencies, analyzing datasets, and generating charts autonomously.
The subagent architecture isn't just a performance optimization; it is a design pattern that maps naturally to how complex analytical work gets done. Here are some ideas for next steps:
- Build multi-step pipelines: Chain multiple interactions to create complex, multi-stage data processing workflows with persistent state.
- Add custom skills: Create additional
SKILL.mdfiles for domain-specific tasks like sentiment analysis, financial modeling, or report generation. - Integrate with cloud storage: Use Google Cloud Buckets instead of GitHub repositories for enterprise-scale data sharing.
- Schedule recurring analysis: Use the
/schedulecommand or a cron job to rerun your analysis pipeline on fresh data automatically.
Frequently Asked Questions
What exactly are Managed Agents, and what are their core capabilities?
Managed Agents are autonomous AI workers powered by Google's Antigravity agent. They can reason, plan, and execute code in Bash, Python, or Node.js within an isolated Linux sandbox, with persistent file management and Google Search integration for live data grounding.
How does an agent's workspace and conversation history persist across multiple interactions?
Persistence is maintained using a unique Environment ID. By passing this ID in later interaction calls using the environment parameter, sequential interactions link to the same sandboxed filesystem and conversation history, preserving files and installed packages.
What are the primary methods for sharing datasets or files with an agent?
You can share data via inline data strings for small files under 1 MB, hosted files via public URLs, GitHub repositories for larger project-based datasets, or Google Cloud Buckets for enterprise-scale data sharing with full access control.
How do you customize an agent's behavior and define specific tools for it to use?
Use the .agents/AGENTS.md file as a system prompt to define general behavior, role, and boundaries. Define specialized, repeatable actions using .agents/skills/skill_name/SKILL.md files, then attach them when creating the agent via base_environment.
How are the costs for using Managed Agents calculated?
Costs are determined by four main factors: model usage (tokens for input and output), infrastructure and platform service fees, context caching (which reduces repetitive token costs), and separate charges for grounding services like Google Search and Google Maps.
Need Help Building AI Agents for Your Business?
Our experts can help you design, deploy, and scale AI agent architectures using Google Gemini, Antigravity, and the latest agentic AI frameworks for your specific use cases.
