代码执行快速入门

本页面演示了如何直接调用 Vertex AI Agent Engine Code Execution API,以便在隔离的沙盒环境中运行不受信任的代码。如果您不希望代理框架为您编排调用,或者您想将 Code Execution 与其他代理框架集成,则直接调用 API 会很有用。

在本快速入门中,您将执行以下任务:

  • 创建 Vertex AI Agent Engine 实例以访问 Code Execution
  • 创建 Code Execution 沙盒
  • (可选)列出和获取沙盒
  • 在沙盒中执行代码
  • 使用同一沙盒执行更多代码。请注意,沙盒会自动维护其状态。
  • 清理

如需详细了解如何将 Code Execution 与智能体开发套件 (ADK) 搭配使用,请参阅将 Code Execution 工具与 Vertex AI Agent Engine 搭配使用

准备工作

设置您的项目和环境。

设置项目

  1. 登录您的 Google Cloud 账号。如果您是新手 Google Cloud, 请创建一个账号来评估我们的产品在 实际场景中的表现。新客户还可获享 $300 赠金,用于 运行、测试和部署工作负载。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

获取所需的角色

如需获得使用 Vertex AI Agent Engine 所需的权限,请让您的管理员为您授予项目的 Vertex AI User (roles/aiplatform.user) IAM 角色。如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

设置环境

本部分假定您已设置 Python 开发环境, 或者正在使用具有 Python 开发环境的运行时(例如 Colab)。

安装库

安装 Vertex AI SDK:

  pip install google-cloud-aiplatform>=1.112.0

向 Vertex AI 进行身份验证

如需进行身份验证,请执行以下操作:

本地 shell

gcloud init
gcloud auth application-default login

Colab

from google.colab import auth

auth.authenticate_user()

创建 Vertex AI Agent Engine 实例

如需使用 Code Execution,请先创建 Vertex AI Agent Engine 实例。您无需部署代理即可使用 Code Execution。 无需部署,创建 Vertex AI Agent Engine 实例应该只需几秒钟。

import vertexai

client = vertexai.Client(project=PROJECT_ID, location=LOCATION)

agent_engine = client.agent_engines.create()
agent_engine_name = agent_engine.api_resource.name

替换以下内容:

创建沙盒

创建沙盒以执行代码。

operation = client.agent_engines.sandboxes.create(
    spec={"code_execution_environment": {}},
    name=agent_engine_name,
    config=types.CreateAgentEngineSandboxConfig(display_name=SANDBOX_DISPLAY_NAME)
)

sandbox_name = operation.response.name

替换以下内容:

  • SANDBOX_DISPLAY_NAME:代码执行沙盒环境的直观易懂的名称。

您还可以配置沙盒设置,例如编码语言和机器配置:

operation = client.agent_engines.sandboxes.create(
   spec={
       "code_execution_environment": {
            "code_language": "LANGUAGE_JAVASCRIPT",
            "machine_config": "MACHINE_CONFIG_VCPU4_RAM4GIB"
        }
   },
   name='projects/PROJECT_ID/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID',
   config=types.CreateAgentEngineSandboxConfig(
       display_name=sandbox_display_name, ttl="3600s"),
)

替换以下内容:

  • PROJECT_ID:您的 Google Cloud 项目 ID。

  • LOCATION:Vertex AI Agent Engine 实例的区域。 Google Cloud 请参阅 Vertex AI Agent Engine 支持的区域

  • AGENT_ENGINE_ID:Vertex AI Agent Engine 实例的 ID。

仅支持 LANGUAGE_PYTHONLANGUAGE_JAVASCRIPT。如果未指定 machine_config,则默认配置为 2 个 vCPU 和 1.5 GB RAM。如果您指定 MACHINE_CONFIG_VCPU4_RAM4GIB,则沙盒具有 4 个 vCPU 和 4 GB RAM。

(可选)列出和获取沙盒

列出与指定的 Agent Engine 实例关联的所有沙盒:

sandboxes = client.agent_engines.sandboxes.list(name=agent_engine_name)

for sandbox in sandboxes:
    pprint.pprint(sandbox)

以下是示例输出:

SandboxEnvironment(
  create_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC)),
  display_name='test_sandbox',
  name=SANDBOX_NAME,
  spec=SandboxEnvironmentSpec(
    code_execution_environment=SandboxEnvironmentSpecCodeExecutionEnvironment()
  ),
  state=<State.STATE_RUNNING: 'STATE_RUNNING'>,
  update_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC))
)

如需获取现有沙盒,请执行以下操作:

sandbox = client.agent_engines.sandboxes.get(name=sandbox_name)

pprint.pprint(sandbox)

以下是示例输出:

SandboxEnvironment(
  create_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC)),
  display_name='test_sandbox',
  name=SANDBOX_NAME,
  spec=SandboxEnvironmentSpec(
    code_execution_environment=SandboxEnvironmentSpecCodeExecutionEnvironment()
  ),
  state=<State.STATE_RUNNING: 'STATE_RUNNING'>,
  update_time=datetime.datetime(2025, 9, 7, 3, 42, 17, 93656, tzinfo=TzInfo(UTC))
)

在沙盒中执行代码

如需执行代码,请调用 execute_code

my_code = """
with open("input.txt", "r") as input:
   with open("output.txt", "w") as output:
       for line in input:
           print(line)
           output.write(line)
"""
input_data = {
   "code": my_code,
   "files": [{
       "name": "input.txt",
       "content": b"Hello, world!"
   }]
}


response = client.agent_engines.sandboxes.execute_code(
   name = sandbox_name,
   input_data = input_data
)

以下是示例输出:

ExecuteSandboxEnvironmentResponse(
  outputs=[
    Chunk(
      data=b'{
        "msg_err":"",
        "msg_out":"",
      }',
      mime_type='application/json',
    ),
    chunk(
data=b"hello world!",
        mime_type="text/plain"
        attributes={
          "file_name":"output.txt"
        }
    )
  ]
)

请注意以下几点:

  • execute_code 会重置沙盒的存留时间 (TTL)。
  • 输出采用原始字节格式。
  • 每个请求或响应最多可包含 100MB 的文件。

在沙盒中执行更多代码

如需演示沙盒会维护其状态,请在同一沙盒中执行更多代码:

python_code = """
with open("output2.txt", "w") as output:
    for line in lines:
        output.write(line + "World\n")
"""
input_data = {"code": python_code}

response = client.agent_engines.sandboxes.execute_code(
    name = sandbox_name,
    input_data = input_data
)

pprint.pprint(response)

以下是示例输出:

ExecuteSandboxEnvironmentResponse(
  outputs=[
    Chunk(
      data=b'{
        "msg_err":"",
        "msg_out":"",
      }',
      mime_type='application/json',
    ),
    chunk(
      data=b"hello world!",
        mime_type="text/plain"
        attributes={
          "file_name":"output2.txt"
        }
    )

  ]
)

响应包含需要解码的文件。以下是如何解码输出的示例:

import base64
import json

if response.outputs[0].mime_type=="application/json":
    json_output = json.loads(response.outputs[0].data.decode("utf-8"))
    output_file_content = json_output.get("output_files")[0].get("content")
    print(output_file_content.b64decode(output_file_content))

以下是示例输出:

b'HelloWorld\n'

清理

如需清理本快速入门创建的资源,请删除沙盒和 Vertex AI Agent Engine 实例。

client.agent_engines.sandboxes.delete(name=sandbox_name)
agent_engine.delete()

后续步骤