本頁面說明如何直接呼叫 Vertex AI Agent Engine Code Execution 的 API,在隔離的沙箱環境中執行不受信任的程式碼。如果您不希望代理程式架構為您協調呼叫,或是想將程式碼執行作業與其他代理程式架構整合,直接呼叫 API 就很有用。
在本快速入門導覽課程中,您將執行下列工作:
- 建立 Vertex AI Agent Engine 執行個體,存取程式碼執行功能
- 建立程式碼執行沙箱
- (選用) 列出及取得沙箱
- 在沙箱中執行程式碼
- 使用同一個沙箱執行更多程式碼。請注意,沙箱會自動維護其狀態。
- 清除所用資源
如要進一步瞭解如何搭配 Agent Development Kit (ADK) 使用程式碼執行功能,請參閱「搭配 Vertex AI Agent Engine 使用程式碼執行工具」。
事前準備
設定專案和環境。
設定專案
- 登入 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 Vertex AI API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. 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 Vertex AI API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.
取得必要角色
如要取得使用 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()
建立 Vertex AI Agent Engine 執行個體
如要使用程式碼執行功能,請先建立 Vertex AI Agent Engine 執行個體。您不需要部署代理程式,即可使用程式碼執行功能。 建立 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
更改下列內容:
PROJECT_ID: Google Cloud 專案 ID。
LOCATION:Vertex AI Agent Engine 執行個體的 Google Cloud 區域。 請參閱 Vertex AI Agent Engine 支援的區域。
建立沙箱
建立用於執行程式碼的沙箱。
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_PYTHON 和 LANGUAGE_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)。- 輸出內容為原始位元組。
- 每個要求或回應最多可包含 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.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()