代码执行快速入门

本页面演示了如何直接调用 Agent Engine 代码执行 API,以在隔离的沙盒环境中运行不可信的代码。如果您不希望代理框架为您编排调用,或者希望将代码执行与其他代理框架集成,直接 API 调用会非常有用。

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

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

准备工作

设置您的项目和环境。

设置项目

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  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 (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 (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

  8. 获取所需的角色

    如需获得使用 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()
    

    创建 Agent Engine 实例

    如需使用代码执行,请先创建 Agent Engine 实例。您无需部署代理即可使用代码执行功能。创建 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
    

    替换以下内容:

    • PROJECT_ID:您的 Google Cloud 项目 ID。
    • LOCATION:Agent Engine 的 Google Cloud 区域。

    创建沙盒

    创建用于执行代码的沙盒。

    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=agent_engine_name,
        config=types.CreateAgentEngineSandboxConfig(display_name=sandbox_display_name),
    )
    
    sandbox_name = operation.response.name
    

    在预览期间,仅支持 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

    python_code = """
    lines = []
    with open("input.txt", "r") as input:
        for line in input:
            lines.append(line)
    """
    input_data = {
        "code": python_code,
        "files": [{
            "name": "input.txt",
            "content": "aGVsbG8="
        }]
    }
    
    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":"","output_files":[]}',
          mime_type='application/json'),
      ]
    )
    

    请注意以下几点:

    • execute_code 会重置沙盒的存留时间 (TTL)。
    • 文件必须内嵌在请求中,并采用 base64 编码。
    • 每个请求或响应最多可包含 100MB 的文件。

    在沙盒中执行更多代码

    为了演示沙盒会保持其状态,请在同一沙盒中执行更多代码:

    python_code = """
    with open("output.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":"",
            "output_files":[{"content":"SGVsbG9Xb3JsZAo=", "name":"output.txt"}],
          }',
          mime_type='application/json',
        ),
      ]
    )
    

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

    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'
    

    清理

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

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

    后续步骤