程式碼執行快速入門

本頁面說明如何直接呼叫 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 使用者 (roles/aiplatform.user) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

    您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

    設定環境

    本節假設您已設定 Python 開發環境,或是使用具備 Python 開發環境的執行階段 (例如 Colab)。

    安裝程式庫

    安裝 Vertex AI SDK:

      pip install google-cloud-aiplatform>=1.112.0

    驗證 Vertex AI

    如要進行驗證,請按照下列步驟操作:

    本機殼層

    gcloud init
    gcloud auth application-default login
    

    Colab

    from google.colab import auth
    
    auth.authenticate_user()
    

    建立 Agent Engine 執行個體

    如要使用程式碼執行功能,請先建立 Agent Engine 執行個體。您不需要部署代理程式,即可使用程式碼執行功能。如果沒有部署作業,建立 AgentEngine 執行個體應該只需要幾秒鐘。

    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 編碼。
    • 每個要求或回應最多可包含 100 MB 的檔案。

    在沙箱中執行更多程式碼

    如要證明沙箱會維持狀態,請在同一個沙箱中執行更多程式碼:

    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()
    

    後續步驟