本頁面說明如何直接呼叫 Code Execution API,在獨立沙箱環境中執行不受信任的程式碼。如果不想讓代理架構自動調度呼叫,或想將程式碼執行功能與其他代理架構整合,直接呼叫 API 會很有幫助。
在本快速入門導覽課程中,您會執行下列工作:
- 建立 Agent Platform 執行個體,以便存取程式碼執行功能
- 建立執行程式碼沙箱
- (選用) 列出及取得沙箱
- 在沙箱中執行程式碼
- 使用同一個沙箱執行更多程式碼。請注意,沙箱會自動維護其狀態。
- 清除所用資源
如要進一步瞭解如何搭配使用執行程式碼功能和 Agent Development Kit (ADK),請參閱「執行程式碼工具」。
事前準備
設定專案和環境。
設定專案
- 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.
取得必要角色
如要取得使用 Vertex AI Agent Engine 所需的權限,請要求管理員授予您專案的 Agent Platform 使用者 (roles/aiplatform.user) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
設定環境
本節假設您已設定 Python 開發環境,或使用具備 Python 開發環境的執行階段 (例如 Colab)。
安裝程式庫
安裝 Agent Platform SDK:
pip install google-cloud-agentplatform>=2.0.1驗證
驗證方法:
本機殼層
gcloud init
gcloud auth application-default login
Colab
from google.colab import auth
auth.authenticate_user()
建立 Agent Platform 執行個體
如要執行程式碼,請先建立 Agent Platform 執行個體。您不需要部署代理,即可使用執行程式碼功能。如果不部署,建立 Agent Platform 執行個體應該只需要幾秒鐘。
import agentplatform
from agentplatform import types
client = agentplatform.Client(project=PROJECT_ID, location=LOCATION)
remote_agent = client.runtimes.create()
remote_agent_name = remote_agent.api_resource.name
更改下列內容:
PROJECT_ID: Google Cloud 專案 ID。
LOCATION:Agent Platform 執行個體的 Google Cloud 區域。請參閱「支援的地區」。
建立沙箱
建立執行程式碼的沙箱。
operation = client.sandboxes.create(
spec={"code_execution_environment": {}},
name=remote_agent_name,
config=types.CreateRuntimeSandboxConfig(display_name=SANDBOX_DISPLAY_NAME)
)
sandbox_name = operation.response.name
更改下列內容:
SANDBOX_DISPLAY_NAME:執行程式碼沙箱環境的人類可讀名稱。
您也可以調整沙箱設定,例如程式設計語言和機器設定:
operation = client.sandboxes.create(
spec={
"code_execution_environment": {
"code_language": "LANGUAGE_JAVASCRIPT",
"machine_config": "MACHINE_CONFIG_VCPU4_RAM4GIB"
}
},
name='projects/PROJECT_ID/locations/LOCATION/reasoningEngines/INSTANCE_ID',
config=types.CreateRuntimeSandboxConfig(
display_name=sandbox_display_name, ttl="3600s"),
)
更改下列內容:
PROJECT_ID: Google Cloud 專案 ID。
LOCATION:Agent Platform 執行個體的 Google Cloud 區域。請參閱「支援的地區」。
INSTANCE_ID:Agent Platform 執行個體的 ID。
僅支援 LANGUAGE_PYTHON 和 LANGUAGE_JAVASCRIPT。如未指定 machine_config,預設設定為 2 個 vCPU 和 1.5 GB RAM。如果指定 MACHINE_CONFIG_VCPU4_RAM4GIB,沙箱會有 4 個 vCPU 和 4 GB 的 RAM。
(選用) 列出及取得沙箱
列出與指定 Agent Engine 執行個體相關聯的所有沙箱:
sandboxes = client.sandboxes.list(name=remote_agent_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.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.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)。- 輸出內容為原始位元組。
- 每項要求或回覆最多可包含 100 MB 的檔案。
在沙箱中執行更多程式碼
為證明沙箱會維持狀態,請在同一個沙箱中執行更多程式碼:
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.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'
清除所用資源
如要清除本快速入門導覽課程建立的資源,請刪除沙箱和 Agent Platform 執行個體。
client.sandboxes.delete(name=sandbox_name)
remote_agent.delete()