开始使用托管代理:Google Colab 教程

本教程面向有编程基础的开发者,深入讲解如何使用 Gemini Agents API 的 Interactions API 构建托管代理。通过对比 agent= 与 model= 模式,阐明托管代理在自主任务中的优势。教程涵盖简单问答、多轮对话、内置工具(代码执行、网络搜索、文件操作)、数据加载、自定义代理创建、流式输出及高级功能(网络配置、环境快照)。提供完整代码示例、环境准备步骤、常见错误排查与生产优化建议,帮助开发者快速掌握构建有状态、自主 AI 代理的工程实践。

技术背景

传统 LLM API 提供无状态推理,开发者需自行编排工具调用、管理上下文,难以构建复杂自主任务。托管代理(如 antigravity-preview-05-2026)在沙盒 Linux 环境中运行,具备推理、规划、代码执行、网络搜索和文件管理能力,无需开发者编写编排逻辑。适用于需要多步骤操作、外部数据获取或持久化状态的场景,如数据分析、自动化报告、代码生成等。主要限制包括沙盒资源限制、网络访问控制、代理行为不确定性,以及 API 配额和成本。

核心原理

Interactions API 提供统一接口,通过 agent= 参数启动托管代理。代理在远程沙盒中运行,拥有持久化文件系统,可自主调用内置工具(bash、google_search、url_context、write_file 等)。每次交互返回 interaction 对象,包含输出文本、状态、环境 ID 和步骤详情。多轮对话通过复用 environment_id 保持状态,previous_interaction_id 可链接历史。自定义代理通过 /agents 端点创建,绑定系统指令、环境和技能(SKILL.md),实现可复用配置。

架构分析

系统由客户端 SDK、Interactions API、代理运行时和沙盒环境组成。客户端初始化 genai.Client,调用 interactions.create 或 agents.create。代理运行时解析输入,规划步骤,调用工具,返回结果。沙盒环境提供隔离的 Linux 容器,支持文件持久化、网络访问控制。自定义代理基于文件结构(agent.yaml、AGENTS.md、skills/、workspace/)定义,便于版本控制。数据加载通过 sources 注入(inline、gcs、repository),网络配置通过 allowlist 控制。流式输出通过 SSE 事件实现实时更新。

完整实战教程

##### 版权所有 2026 Google LLC.

# @title Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Gemini Agents API:使用 Interactions API 构建托管代理

<a class="tfo-notebook-buttons" target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_managed_agents.ipynb">

</a>

Interactions API 为使用 Gemini 模型和代理提供了一个统一接口。入门笔记本 涵盖了如何将其与标准 Gemini 模型 结合用于文本生成、多轮对话和工具使用。

本笔记本重点介绍不同的内容:使用 antigravity-preview-05-2026 代理的托管代理。

agent= 与 model= 对比

调用 Interactions API 时,您可以在两种模式之间进行选择:

| 参数 | 运行内容 | 最适合 |

|-----------|-----------|----------|

| model="gemini-..." | 标准 Gemini 模型 | 文本生成、结构化输出、函数调用 |

| agent="antigravity-preview-05-2026" | 在沙盒 Linux 环境中的托管代理 | 自主任务:代码执行、网络研究、文件管理 |

使用 model= 时,您获得的是无状态 LLM 调用(参见入门笔记本)。使用 agent= 时,您启动一个自主代理,它可以推理、规划、编写和执行代码、浏览网页以及管理文件——所有这些都在安全沙盒内完成,无需您编写任何编排逻辑。

本笔记本将逐步引导您了解代理模式:

  1. 简单问题 — 像使用 LLM 一样使用代理(可行,但有点大材小用!)
  2. 多轮对话 — 持久化沙盒 = 内置记忆
  3. 使用工具 — 代码执行、网络搜索、文件操作
  4. 将数据加载到沙盒中 — 在代理启动前注入文件
  5. 创建可复用的自定义代理 — 捆绑指令、技能和环境

<a name="setup"></a>

设置

安装 SDK

从 PyPI 安装 SDK。建议始终使用最新版本。

%pip install -U -q "google-genai>=2.9.0"

设置你的 API 密钥

要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab 密钥中。如果你还没有 API 密钥,或者不确定如何创建 Colab 密钥,请参阅 [身份验证](

image(有关示例,请参阅](../quickstarts/Authentication.ipynb)。

from google.colab import userdata

GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')

初始化 SDK 客户端

使用新版 SDK,现在你只需使用你的 API 密钥初始化一个客户端即可。

import uuid
from google import genai
from google.genai import types
from IPython.display import Markdown

client = genai.Client(api_key=GEMINI_API_KEY)

# The default managed agent.
AGENT = "antigravity-preview-05-2026"

# Generate a unique suffix for this notebook session to prevent agent ID conflicts
UNIQUE_SUFFIX = uuid.uuid4().hex[:8]

print("Client ready!")

1. 简单问题——将智能体视为 LLM

使用托管智能体的最简单方式是向它提问,就像调用标准的 Gemini 模型一样。传入 agent="antigravity-preview-05-2026" 和 environment="remote" 来为智能体创建一个全新的 Linux 沙箱。

这种方法可行,但有点像开着一级方程式赛车去杂货店——智能体具备代码执行、网络搜索和文件管理能力,而这些能力在处理简单事实性问题时都处于闲置状态。

interaction = client.interactions.create(
    agent=AGENT,
    input="What is the capital of France?",
    environment="remote",
)

Markdown(interaction.output_text)
# The response also includes metadata about the agent's sandbox.
print(f"Status:         {interaction.status}")
print(f"Interaction ID: {interaction.id}")
print(f"Environment ID: {interaction.environment_id}")

注意响应中的 environment_id。那是智能体的持久化 Linux 沙箱。即使对于这个简单的问题,也配置了一个完整的容器。接下来让我们利用这种持久性。

2. 多轮对话

由于每个代理都在持久化沙箱中运行,你可以通过复用 environment_id 并将轮次与 previous_interaction_id 链接来从上次中断的地方继续。

这与无状态的 model= 调用有根本不同。代理拥有真正的*持久化环境*——它创建的文件会保留,安装的包仍然可用,对话上下文也会被保留。

# Turn 1: Introduce yourself.
turn1 = client.interactions.create(
    agent=AGENT,
    input="Hi! My name is Alice and I'm a software engineer. Remember that in a knowledge.md doc.",
    environment= "remote",
)

Markdown(f"**Turn 1:** {turn1.output_text}")
# Turn 2: Ask whether the agent remembers.
# Pass environment_id and previous_interaction_id to continue the conversation.
turn2 = client.interactions.create(
    agent=AGENT,
    input="what's my name and what do I do?",
    environment= turn1.environment_id,
)

Markdown(f"**Turn 2:** {turn2.output_text}")

代理之所以能跨轮次记住,是因为你传入了带有先前环境 ID 的 environment —— 同一个沙箱,意味着相同的文件。

你也可以使用 previous_interaction_id 来保留先前对话的历史,达到同样的效果,但这无法展示环境的特性。

这就是构建有状态、多轮工作流的方式。参见 入门笔记本 了解仅使用 previous_interaction_id(不涉及环境)的基于 model= 的多轮对话。

3. 使用工具——智能体的亮点所在

这正是托管智能体超越标准聊天模型之处。antigravity-preview-05-2026 智能体拥有内置工具,可自主使用——你无需声明它们,只需描述目标,智能体便会自行决定使用哪些工具。

| 工具 | 描述 |

|------|-------------|

| bash | 在沙盒中执行 shell 命令 |

| google_search | 搜索网络以获取最新信息 |

| url_context | 从 URL 获取并提取文本 |

| write_file | 在沙盒中创建或覆盖文件 |

| read_file | 从沙盒中读取文件内容 |

| list_files | 列出目录内容 |

| delete_file | 从沙盒中删除文件 |

对于基于标准 model= 的工具(Google 搜索接地、代码执行、函数调用),请参阅 入门笔记本 和专门的工具笔记本:

代码执行

提出一个计算性问题,代理将编写代码,在其沙箱中运行,并返回验证后的结果。

interaction = client.interactions.create(
    agent=AGENT,
    input=(
        "Write a Python script that computes the first 20 Fibonacci numbers. "
        "Run it and show the output."
    ),
    environment="remote",
)

Markdown(interaction.output_text)

检查步骤——智能体实际做了什么

响应中的 steps 字段展示了智能体的推理链:它的思考、工具调用、工具结果以及最终输出。这对于调试和理解智能体的行为非常有用。

# Inspect the steps from the Fibonacci interaction above.
for i, step in enumerate(interaction.steps):
    step_type = step.type
    print(f"--- Step {i} [{step_type}] ---")

    # Tool call steps show which tool was invoked and with what arguments.
    if hasattr(step, "name") and step.name:
        print(f"  Tool: {step.name}")
        if hasattr(step, "arguments"):
            args_str = str(step.arguments)[:300]
            print(f"  Args: {args_str}")

    # Content steps contain the agent's text output.
    if hasattr(step, "content") and step.content:
        for c in step.content:
            if hasattr(c, "text"):
                print(f"  Text: {c.text[:300]}")
    print()

网络搜索

当代理需要最新信息时,它可以自主搜索网络。

interaction = client.interactions.create(
    agent=AGENT,
    input="What were the top 3 news stories about Google this week? Summarize them briefly.",
    environment="remote",
)

Markdown(interaction.output_text)

文件操作

智能体可以在其沙箱中创建、读取和管理文件。文件在环境中跨轮次持久保存。

# Ask the agent to create a file, run it, and show results.
interaction = client.interactions.create(
    agent=AGENT,
    input=(
        "Create a Python file called 'analysis.py' that generates 50 random numbers, "
        "computes mean, median, and standard deviation, then prints the results. "
        "Run it and show the output."
    ),
    environment="remote",
)

Markdown(interaction.output_text)

4. 将数据加载到代理的沙箱中

您可以在代理启动之前使用 sources 将文件注入其环境。这是您提供数据、配置或代码供代理使用的方式。

| 源类型 | 描述 | 最适合 |

|------------|-------------|----------|

| inline | 直接嵌入内容(最大 75 KB) | 配置文件、小脚本 |

| gcs | 从 Google Cloud Storage 加载 | 大型数据集 |

| repository | 从 GitHub 加载 | 代码仓库 |

# Inject a CSV file inline and ask the agent to analyze it.
csv_data = """name,age,city,score
              Alice,28,Paris,92
              Bob,35,London,87
              Charlie,42,Berlin,95
              Diana,31,Tokyo,88
              Eve,26,Sydney,91"""

interaction = client.interactions.create(
    agent=AGENT,
    input="Read the file data.csv, analyze it, and tell me who scored the highest.",
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "content": csv_data,
                "target": "/workspace/data.csv",
            }
        ],
    },
)

Markdown(interaction.output_text)

你还可以从其他来源加载:

# From Google Cloud Storage
{"type": "gcs", "source": "gs://my-bucket/data/", "target": "/workspace/data/"}

# From a GitHub repository
{"type": "repository", "source": "https://github.com/user/repo", "target": "/workspace/repo/"}

你可以在单个请求中组合多个来源——代理在启动时将能够访问所有这些来源。

专业提示: 你可以利用这一点为你的智能体添加技能,稍后你将看到。

5. 创建可复用的自定义代理

到目前为止,每次交互都使用了带有内联指令的基础 antigravity-preview-05-2026 代理。一旦你找到了一个有效的设置,你可以将其持久化为一个命名的自定义代理,该代理捆绑了:

这是推荐的工作流程:

  1. 原型设计 使用 agent="antigravity-preview-05-2026" — 迭代指令、源和提示
  2. 创建 通过 /agents 端点创建一个命名代理
  3. 调用 从任何客户端按名称调用你的代理

创建自定义代理

# Create a custom data analysis agent using the SDK.
my_agent = client.agents.create(
    id=f"my-data-analyst-{UNIQUE_SUFFIX}",
    base_agent=AGENT,
    system_instruction=(
        "You are a data analysis assistant. "
        "Always write Python code using pandas to answer questions. "
        "Show your code and output clearly. "
        "When creating visualizations, save them as PNG files."
    ),
    base_environment={
        "type": "remote",
    },
)

print(f"✓ Agent created: {my_agent.id}")

使用自定义智能体

创建后,通过名称调用你的智能体。它会自动遵循其指令。

# Invoke the custom agent.
interaction = client.interactions.create(
    agent=f"my-data-analyst-{UNIQUE_SUFFIX}",
    input=(
        "Generate a sample dataset of 100 sales records with columns: "
        "product, region, revenue, quantity. "
        "Find the top 5 products by total revenue and show the analysis."
    ),
    environment="remote",
)

Markdown(interaction.output_text)

创建预加载数据的代理

您可以通过源定义代理的环境,以便在代理启动前数据就已准备就绪:

# Create an agent with GCS sources pre-loaded using the SDK.
my_slides_agent = client.agents.create(
    id=f"my-gemini-api-agent-{UNIQUE_SUFFIX}",
    base_agent=AGENT,
    system_instruction=(
        "You are a software engineer speciliazed in the Gemini API. "
        "Use the skills available in /.agents/skills/ to create amazing apps."
    ),
    base_environment={
        "type": "remote",
        "sources": [
            {
                "type": "repository",
                "source": "https://github.com/google-gemini/gemini-skills",
                "target": "/.agents/skills",
            }
        ],
    },
)

print(f"✓ Agent created: {my_slides_agent.id}")
# Invoke the custom agent.
interaction = client.interactions.create(
    agent=f"my-gemini-api-agent-{UNIQUE_SUFFIX}",
    input="Tell me what you can do with your skills?",
    environment="remote",
)

Markdown(interaction.output_text)

从现有环境分叉

如果你已经设置了一个喜欢的沙箱(安装了包、创建了文件等),你可以使用之前交互中的 environment_id 将其分叉到新的代理中:

my_forked_agent = client.agents.create(
    id="my-forked-agent",
    base_agent=AGENT,
    system_instruction="Your custom instructions here.",
    base_environment={"env_id": "YOUR_ENVIRONMENT_ID"},
)

这捕获了该沙箱的确切状态——所有已安装的包、文件和配置。

my_forked_agent = client.agents.create(
    id="my-forked-agent",
    base_agent="my-gemini-api-agent",
    system_instruction="I want all your apps to use the Live API",
    base_environment={"env_id": interaction.environment_id},
)
print(f"✓ Agent forked: {my_forked_agent.id}")

管理代理(CRUD)

/agents 端点支持完整的生命周期管理:

# List all your agents.
print("Your agents:")
for agent in client.agents.list().agents:
    print(f"- {agent.id}")

# Get a specific agent's details.
agent = client.agents.get(id="my-data-analyst")
print(f"\nAgent details for {agent.id}:")
print(f"Base agent: {agent.base_agent}")
print(f"System instruction: {agent.system_instruction}")
# Clean up: delete the agents you created.
for agent_name in ["my-data-analyst", "my-forked-agent", "my-gemini-api-agent"]:
    try:
        client.agents.delete(id=agent_name)
        print(f"✓ Deleted {agent_name}")
    except Exception as e:
        print(f"  Failed to delete {agent_name}: {e}")

Agent 目录结构

在 API 背后,一个 agent 由一组简单的文件定义。当你创建一个 agent 时,部署的就是这些文件:

my-agent/
├── agent.yaml       # Configuration: base agent, tools, environment
├── AGENTS.md        # System instructions (loaded automatically)
├── skills/          # Custom SKILL.md files that extend capabilities
└── workspace/       # Files seeded into the remote sandbox at startup

这种基于文件的结构使代理易于版本控制、共享和迭代。查看文档了解更多详情。

6. 流式输出

对于较长的任务,通过设置 stream=True 启用流式输出,以便在代理工作时获得实时更新。您无需等待完整响应,而是接收一系列服务器发送事件(SSE),从而可以向用户展示进度。

事件类型

流会传递事件,告知您代理正在做什么:

| 事件类型 | 含义 | 操作 |

|------------|---------|------------|

| interaction.created | 交互已创建 | 存储 id 以供后续引用 |

| interaction.status_update | 状态已更改(例如,in_progress) | 更新 UI 状态指示器 |

| step.start | 新步骤开始(思考、工具调用、输出) | 显示加载指示器 |

| step.delta | 增量内容——文本、思考或工具输出的片段 | 追加到显示——这是主要内容 |

| step.stop | 步骤完成 | 隐藏加载指示器 |

| interaction.completed | 代理完成所有工作 | 完成 UI 更新 |

step.delta 事件是内容所在之处。每个增量都有一个 type(例如,text、thought、function_call、function_result)以及可以增量渲染的内容。

# Stream a response and collect the text as it arrives.
stream = client.interactions.create(
    agent=AGENT,
    input="Write a short poem about the ocean.",
    stream=True,
    environment="remote",
)

collected_text = []

for event in stream:
    # Show the event type so you can see the lifecycle.
    if event.event_type in ("interaction.created", "step.start", "step.stop", "interaction.completed"):
        print(f"[{event.event_type}]")

    # step.delta events carry the actual content.
    elif event.event_type == "step.delta":
        delta = event.delta
        if hasattr(delta, "text") and delta.text:
            print(delta.text, end="", flush=True)
            collected_text.append(delta.text)

print(f"\n\n--- Collected {len(collected_text)} text chunks ---")

7. 高级功能

网络配置

默认情况下,代理的沙箱具有不受限制的出站网络访问权限。您可以通过 network 字段对此进行控制:

# Allow the agent to call only the Gemini API, with an auto-injected API key.
interaction = client.interactions.create(
    agent=AGENT,
    input="Use curl to call the Gemini API and list available models. Show the first 3.",
    environment={
        "type": "remote",
        "network": {
            "allowlist": [
                {
                    "domain": "generativelanguage.googleapis.com",
                    "transform": [{"x-goog-api-key": GEMINI_API_KEY}],
                },
            ]
        },
    },
)

Markdown(interaction.output_text)

下载环境快照

你可以将代理创建或修改的所有文件以 tar 归档形式下载。这样,你就可以从沙盒中获取代理的工作成果——代码、数据、报告等。

import subprocess
import tarfile
import os

# Create an interaction where the agent produces files.
interaction = client.interactions.create(
    agent=AGENT,
    input=(
        "Create a directory called 'project' with a README.md and a hello.py script. "
        "List the files you created."
    ),
    environment="remote",
)

env_id = interaction.environment_id
print(f"Environment ID: {env_id}")

Markdown(interaction.output_text)
# Download the environment snapshot.
download_url = (
    f"https://generativelanguage.googleapis.com/v1beta/"
    f"files/environment-{env_id}:download?alt=media"
)

result = subprocess.run(
    ["curl", "-L", "-s", "-o", "snapshot.tar",
     "-H", f"x-goog-api-key: {GEMINI_API_KEY}",
     download_url],
    capture_output=True, text=True,
)

if os.path.exists("snapshot.tar") and os.path.getsize("snapshot.tar") > 0:
    with tarfile.open("snapshot.tar") as tar:
        print("Files in snapshot:")
        for member in tar.getmembers():
            print(f"  {member.name} ({member.size} bytes)")
else:
    print("Snapshot not available (environment may have expired).")

后续步骤

你已经了解了托管代理的核心功能:

  1. ✅ 简单问答 — 代理可以像大语言模型一样回答问题
  2. ✅ 多轮对话 — 持久化沙箱支持有状态的对话
  3. ✅ 内置工具 — 代码执行、网络搜索、文件管理
  4. ✅ 数据加载 — 通过内联、GCS 或 GitHub 源注入文件
  5. ✅ 自定义代理 — 可复用的配置,包含指令、技能和环境
  6. ✅ 流式传输 — 代理工作时实时更新
  7. ✅ 高级功能 — 网络控制和环境快照

了解更多

常见问题

常见错误:1) API 密钥未设置或无效,导致 401 错误,检查 GEMINI_API_KEY 是否正确配置。2) 环境 ID 无效或过期,多轮对话时确保复用正确的 environment_id。3) 代理 ID 冲突,使用唯一后缀(如 uuid)避免。4) 网络请求被阻止,检查网络配置 allowlist。5) 文件路径错误,确保 target 路径正确。排查方法:查看 interaction.steps 了解代理行为,检查状态字段,使用流式输出观察实时进度。生产优化:使用自定义代理减少重复配置,合理设置网络白名单,定期清理环境快照,监控 API 配额。

企业应用扩展

可扩展方向:1) 集成更多数据源(如 BigQuery、S3)丰富数据加载。2) 开发自定义技能(SKILL.md)增强代理专业能力。3) 结合函数调用实现与外部系统集成。4) 利用环境快照进行结果归档和审计。5) 实现代理编排,多个代理协同完成复杂任务。6) 优化提示词设计,提高代理效率和准确性。7) 探索流式输出的 UI 集成,提升用户体验。

总结

本教程面向有编程基础的开发者,深入讲解如何使用 Gemini Agents API 的 Interactions API 构建托管代理。通过对比 agent= 与 model= 模式,阐明托管代理在自主任务中的优势。教程涵盖简单问答、多轮对话、内置工具(代码执行、网络搜索、文件操作)、数据加载、自定义代理创建、流式输出及高级功能(网络配置、环境快照)。提供完整代码示例、环境准备步骤、常见错误排查与生产优化建议,帮助开发者快速掌握构建有状态、自主 AI 代理的工程实践。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部AI 智能体教程