בדף הזה נדגים איך לבצע קריאות ישירות ל-Code Execution API כדי להריץ קוד לא מהימן בסביבת ארגז חול מבודדת. קריאות ישירות ל-API שימושיות אם אתם לא רוצים שמסגרת הסוכנים תתזמן את הקריאות בשבילכם, או אם אתם רוצים לשלב את Code Execution עם מסגרות סוכנים אחרות.
במדריך למתחילים הזה תבצעו את הפעולות הבאות:
- יצירת מופע של Agent Platform כדי לגשת ל-Code Execution
- יצירת ארגז חול לביצוע קוד
- (אופציונלי) הצגת ארגזי חול וקבלת מידע עליהם
- הרצת קוד בארגז חול
- להריץ עוד קוד באמצעות אותו ארגז חול. שימו לב שמצב ארגז החול נשמר באופן אוטומטי.
- הסרת המשאבים
מידע נוסף על השימוש בביצוע קוד עם הערכה לפיתוח סוכנים (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.
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 Gemini Enterprise Agent Platform 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, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד משתמש בפלטפורמת סוכנים (roles/aiplatform.user) בפרויקט.
כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.
יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.
מגדירים את הסביבה
בקטע הזה מניחים שהגדרתם סביבת פיתוח של Python, או שאתם משתמשים בסביבת זמן ריצה עם סביבת פיתוח של Python (כמו Colab).
התקנת ספריות
מתקינים את Vertex AI SDK:
pip install google-cloud-aiplatform>=1.112.0אמת
כדי לבצע אימות:
מעטפת מקומית
gcloud init
gcloud auth application-default login
Colab
from google.colab import auth
auth.authenticate_user()
יצירת מופע של Agent Platform
כדי להשתמש בתכונה Code Execution, קודם צריך ליצור מופע של Agent Platform. לא צריך לפרוס סוכן כדי להשתמש בהרצת קוד. ללא פריסה, יצירת מופע של Agent Platform אמורה להימשך כמה שניות.
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 .
LOCATION: האזור Google Cloud של מופע Agent Platform. מידע נוסף זמין במאמר בנושא אזורים נתמכים.
יצירת ארגז חול
יצירת ארגז חול להרצת קוד.
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/INSTANCE_ID',
config=types.CreateAgentEngineSandboxConfig(
display_name=sandbox_display_name, ttl="3600s"),
)
מחליפים את מה שכתוב בשדות הבאים:
PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
LOCATION: האזור Google Cloud של מופע Agent Platform. אפשר לעיין באזורים נתמכים.
INSTANCE_ID: המזהה של מופע Agent Platform.
יש תמיכה רק בערכים LANGUAGE_PYTHON ו-LANGUAGE_JAVASCRIPT. אם לא מציינים את machine_config, הגדרת ברירת המחדל היא 2 vCPU ו-1.5GB של RAM. אם מציינים MACHINE_CONFIG_VCPU4_RAM4GIB, ל-Sandbox יש 4 vCPU ו-4GB של 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'
הסרת המשאבים
כדי להסיר את המשאבים שנוצרו במדריך למתחילים הזה, מוחקים את ארגז החול ואת המופע של Agent Platform.
client.agent_engines.sandboxes.delete(name=sandbox_name)
agent_engine.delete()