Code Execution Tool with Agent Engine¶
使用智能体引擎的代码执行工具¶
The Agent Engine Code Execution ADK Tool provides a low-latency, highly efficient method for running AI-generated code using the Google Cloud Agent Engine service. This tool is designed for fast execution, tailored for agentic workflows, and uses sandboxed environments for improved security. The Code Execution tool allows code and data to persist over multiple requests, enabling complex, multi-step coding tasks, including:
智能体引擎代码执行 ADK 工具提供了一种低延迟、高效率的方法来运行 AI 生成的代码,它使用 Google Cloud 智能体引擎服务。此工具专为快速执行而设计,针对智能体工作流进行了优化,并使用沙箱环境以提高安全性。代码执行工具允许代码和数据在多个请求之间持久化,从而实现复杂的多步骤编码任务,包括:
- Code development and debugging: Create agent tasks that test and iterate on versions of code over multiple requests. 代码开发和调试: 创建智能体任务,在多个请求中测试和迭代代码版本。
- Code with data analysis: Upload data files up to 100MB, and run multiple code-based analyses without the need to reload data for each code run. 带数据分析的代码: 上传高达 100MB 的数据文件,并运行多个基于代码的分析,而无需在每次代码运行时重新加载数据。
This code execution tool is part of the Agent Engine suite, however you do not have to deploy your agent to Agent Engine to use it. You can run your agent locally or with other services and use this tool. For more information about the Code Execution feature in Agent Engine, see the Agent Engine Code Execution documentation.
此代码执行工具是智能体引擎套件的一部分,但你不必将智能体部署到智能体引擎即可使用它。你可以本地运行智能体或与其他服务一起使用此工具。有关智能体引擎中代码执行功能的更多信息,请参阅智能体引擎代码执行文档。
Preview release
The Agent Engine Code Execution feature is a Preview release. For more information, see the launch stage descriptions.
智能体引擎代码执行功能是预览版。有关更多信息,请参阅发布阶段说明。
Use the Tool¶
使用工具¶
Using the Agent Engine Code Execution tool requires that you create a sandbox environment with Google Cloud Agent Engine before using the tool with an ADK agent.
使用智能体引擎代码执行工具要求你在将工具与 ADK 智能体一起使用之前,使用 Google Cloud 智能体引擎创建沙箱环境。
To use the Code Execution tool with your ADK agent: 要将代码执行工具与 ADK 智能体一起使用:
- Follow the instructions in the Agent Engine Code Execution quickstart to create a code execution sandbox environment. 按照智能体引擎代码执行快速入门中的说明创建代码执行沙箱环境。
- Create an ADK agent with settings to access the Google Cloud project where you created the sandbox environment. 创建具有访问你创建沙箱环境的 Google Cloud 项目设置的 ADK 智能体。
- The following code example shows an agent configured to use the Code
Executor tool. Replace
SANDBOX_RESOURCE_NAMEwith the sandbox environment resource name you created. 以下代码示例显示了一个配置为使用代码执行器工具的智能体。将SANDBOX_RESOURCE_NAME替换为你创建的沙箱环境资源名称。
from google.adk.agents.llm_agent import Agent
from google.adk.code_executors.agent_engine_sandbox_code_executor import AgentEngineSandboxCodeExecutor
root_agent = Agent(
model="gemini-2.5-flash",
name="agent_engine_code_execution_agent",
instruction="You are a helpful agent that can write and execute code to answer questions and solve problems.",
code_executor=AgentEngineSandboxCodeExecutor(
sandbox_resource_name="SANDBOX_RESOURCE_NAME",
),
)
For details on the expected format of the sandbox_resource_name value, and the
alternative agent_engine_resource_name parameter, see Configuration
parameters. For a more advanced example, including
recommended system instructions for the tool, see the Advanced
example or the full
agent code example.
有关 sandbox_resource_name 值的预期格式和替代的 agent_engine_resource_name 参数的详细信息,请参阅配置参数。有关更高级的示例,包括为工具推荐的系统说明,请参阅高级示例或完整的智能体代码示例。
How it works¶
工作原理¶
The AgentEngineCodeExecutor Tool maintains a single sandbox throughout an
agent's task, meaning the sandbox's state persists across all operations within
an ADK workflow session.
AgentEngineCodeExecutor 工具在智能体任务期间维护单个沙箱,这意味着沙箱的状态在 ADK 工作流会话中的所有操作之间持久存在。
- Sandbox creation: For multi-step tasks requiring code execution, the Agent Engine creates a sandbox with specified language and machine configurations, isolating the code execution environment. If no sandbox is pre-created, the code execution tool will automatically create one using default settings. 沙箱创建: 对于需要代码执行的多步骤任务,智能体引擎使用指定的语言和机器配置创建沙箱,隔离代码执行环境。如果没有预先创建沙箱,代码执行工具将使用默认设置自动创建一个。
- Code execution with persistence: AI-generated code for a tool call is streamed to the sandbox and then executed within the isolated environment. After execution, the sandbox remains active for subsequent tool calls within the same session, preserving variables, imported modules, and file state for the next tool call from the same agent. 带持久性的代码执行: 工具调用的 AI 生成的代码被流式传输到沙箱,然后在隔离环境中执行。执行后,沙箱保持活动状态以进行同一会话中的后续工具调用,为来自同一智能体的下一次工具调用保留变量、导入的模块和文件状态。
- Result retrieval: The standard output, and any captured error streams are collected and passed back to the calling agent. 结果检索: 标准输出和任何捕获的错误流被收集并传递回调用智能体。
- Sandbox clean up: Once the agent task or conversation concludes, the agent can explicitly delete the sandbox, or rely on the TTL feature of the sandbox specified when creating the sandbox. 沙箱清理: 智能体任务或对话结束后,智能体可以显式删除沙箱,或依赖创建沙箱时指定的沙箱 TTL 功能。
Key benefits¶
主要优势¶
- Persistent state: Solve complex tasks where data manipulation or variable context must carry over between multiple tool calls. 持久状态: 解决数据操作或变量上下文必须在多个工具调用之间传递的复杂任务。
- Targeted Isolation: Provides robust process-level isolation, ensuring that tool code execution is safe while remaining lightweight. 针对性隔离: 提供强大的进程级隔离,确保工具代码执行安全同时保持轻量级。
- Agent Engine integration: Tightly integrated into the Agent Engine tool-use and orchestration layer. 智能体引擎集成: 紧密集成到智能体引擎工具使用和编排层。
- Low-latency performance: Designed for speed, allowing agents to execute complex tool-use workflows efficiently without significant overhead. 低延迟性能: 为速度而设计,允许智能体高效执行复杂的工具使用工作流而不会产生显著的开销。
- Flexible compute configurations: Create sandboxes with specific programming language, processing power, and memory configurations. 灵活的配置: 创建具有特定编程语言、处理能力和内存配置的沙箱。
System requirements¶¶
系统要求¶¶
The following requirements must be met to successfully use the Agent Engine Code Execution tool with your ADK agents: 要成功将智能体引擎代码执行工具与 ADK 智能体一起使用,必须满足以下要求:
- Google Cloud project with Vertex API enabled 启用了 Vertex API 的 Google Cloud 项目
- Agent's service account requires roles/aiplatform.user role, which
allow it to:
智能体的服务账户需要 roles/aiplatform.user 角色,允许它:
- Create, get, list and delete code execution sandboxes 创建、获取、列出和删除代码执行沙箱
- Execute code execution sandbox 执行代码执行沙箱
Configuration parameters¶
配置参数¶
The Agent Engine Code Execution tool has the following parameters. You must set one of the following resource parameters: 智能体引擎代码执行工具具有以下参数。你必须设置以下资源参数之一:
sandbox_resource_name: A sandbox resource path to an existing sandbox environment it uses for each tool call. The expected string format is as follows:sandbox_resource_name: 用于每次工具调用的现有沙箱环境的沙箱资源路径。预期的字符串格式如下:agent_engine_resource_name: Agent Engine resource name where the tool creates a sandbox environment. The expected string format is as follows:agent_engine_resource_name: 工具在其中创建沙箱环境的智能体引擎资源名称。预期的字符串格式如下:
You can use Google Cloud Agent Engine's API to configure Agent Engine sandbox environments separately using a Google Cloud client connection, including the following settings: 你可以使用 Google Cloud 智能体引擎的 API 通过 Google Cloud 客户端连接单独配置智能体引擎沙箱环境,包括以下设置:
- Programming languages, including Python and JavaScript 编程语言,包括 Python 和 JavaScript
- Compute environment, including CPU and memory sizes 计算环境,包括 CPU 和内存大小
For more information on connecting to Google Cloud Agent Engine and configuring sandbox environments, see the Agent Engine Code Execution quickstart.
有关连接到 Google Cloud 智能体引擎和配置沙箱环境的更多信息,请参阅智能体引擎代码执行快速入门。
Advanced example¶
高级示例¶
The following example code shows how to implement use of the Code Executor tool
in an ADK agent. This example includes a base_system_instruction clause to set
the operating guidelines for code execution. This instruction clause is
optional, but strongly recommended for getting the best results from this tool.
以下示例代码显示如何在 ADK 智能体中实现代码执行器工具的使用。此示例包括 base_system_instruction 子句,用于设置代码执行的操作指南。此指令子句是可选的,但强烈建议使用以从此工具获得最佳结果。
from google.adk.agents.llm_agent import Agent
from google.adk.code_executors.agent_engine_sandbox_code_executor import AgentEngineSandboxCodeExecutor
def base_system_instruction():
"""Returns: data science agent system instruction."""
return """
# Guidelines
# 指南
**Objective:** Assist the user in achieving their data analysis goals, **with emphasis on avoiding assumptions and ensuring accuracy.** Reaching that goal can involve multiple steps. When you need to generate code, you **don't** need to solve the goal in one go. Only generate the next step at a time.
**目标:** 帮助用户实现他们的数据分析目标,**强调避免假设并确保准确性。** 实现该目标可能涉及多个步骤。当你需要生成代码时,你**不需要**一次性解决问题。只需一次生成下一步。
**Code Execution:** All code snippets provided will be executed within the sandbox environment.
**代码执行:** 提供的所有代码片段都将在沙箱环境中执行。
**Statefulness:** All code snippets are executed and the variables stays in the environment. You NEVER need to re-initialize variables. You NEVER need to reload files. You NEVER need to re-import libraries.
**有状态性:** 所有代码片段都被执行,变量保持在环境中。你永远不需要重新初始化变量。你永远不需要重新加载文件。你永远不需要重新导入库。
**Output Visibility:** Always print the output of code execution to visualize results, especially for data exploration and analysis. For example:
**输出可见性:** 始终打印代码执行的输出以可视化结果,特别是对于数据探索和分析。例如:
- To look a the shape of a pandas.DataFrame do:
要查看 pandas.DataFrame 的形状,请执行:
```tool_code
print(df.shape)
```
The output will be presented to you as:
输出将呈现为:
```tool_outputs
(49, 7)
```
- To display the result of a numerical computation:
要显示数值计算的结果:
```tool_code
x = 10 ** 9 - 12 ** 5
print(f'{{x=}}')
```
The output will be presented to you as:
输出将呈现为:
```tool_outputs
x=999751168
```
- You **never** generate ```tool_outputs yourself.
你**永远不**自己生成 ```tool_outputs。
- You can then use this output to decide on next steps.
然后你可以使用此输出来决定下一步。
- Print just variables (e.g., `print(f'{{variable=}}')`.
只打印变量(例如,`print(f'{{variable=}}')`)。
**No Assumptions:** **Crucially, avoid making assumptions about the nature of the data or column names.** Base findings solely on the data itself. Always use the information obtained from `explore_df` to guide your analysis.
**不做假设:** **关键是要避免对数据性质或列名做出假设。** 研究结果仅基于数据本身。始终使用从 `explore_df` 获得的信息来指导你的分析。
**Available files:** Only use the files that are available as specified in the list of available files.
**可用文件:** 仅使用可用文件列表中指定的文件。
**Data in prompt:** Some queries contain the input data directly in the prompt. You have to parse that data into a pandas DataFrame. ALWAYS parse all the data. NEVER edit the data that are given to you.
**提示中的数据:** 某些查询直接在提示中包含输入数据。你必须将该数据解析为 pandas DataFrame。始终解析所有数据。永远不要编辑给你的数据。
**Answerability:** Some queries may not be answerable with the available data. In those cases, inform the user why you cannot process their query and suggest what type of data would be needed to fulfill their request.
**可回答性:** 某些查询可能无法用可用数据回答。在这些情况下,告知用户为什么你无法处理他们的查询,并建议完成他们的请求需要什么类型的数据。
"""
root_agent = Agent(
model="gemini-2.5-flash",
name="agent_engine_code_execution_agent",
instruction=base_system_instruction() + """
你需要通过查看对话中的数据和上下文来帮助用户解答他们的查询。
你的最终答案应该总结与用户查询相关的代码和代码执行。
你应该包括回答用户查询的所有数据片段,例如代码执行结果中的表格。
如果你不能直接回答问题,你应该按照上述指南生成下一步。
如果问题可以通过编写任何代码直接回答,你应该这样做。
如果你没有足够的数据来回答问题,你应该向用户寻求澄清。
你应该永远不要自行安装任何包,如 `pip install ...`。
在绘制趋势时,你应该确保按 x 轴对数据进行排序和排序。
""",
code_executor=AgentEngineSandboxCodeExecutor(
# Replace with your sandbox resource name if you already have one.
# 如果你已经有沙箱资源名称,请替换为你的。
sandbox_resource_name="SANDBOX_RESOURCE_NAME",
# Replace with agent engine resource name used for creating sandbox if
# sandbox_resource_name is not set:
# 如果未设置 sandbox_resource_name,请替换为用于创建沙箱的智能体引擎资源名称:
# agent_engine_resource_name="AGENT_ENGINE_RESOURCE_NAME",
),
)
For a complete version of an ADK agent using this example code, see the agent_engine_code_execution sample.
有关使用此示例代码的 ADK 智能体的完整版本,请参阅agent_engine_code_execution 示例。