בדף הזה מוסבר איך לשלוח קריאות ל-API ישירות ל-Code Execution כדי להריץ קוד לא מהימן בסביבת ארגז חול מבודדת. קריאות ישירות ל-API שימושיות כשלא רוצים ש-Agent Framework יתזמר את הקריאות בשבילכם, או אם רוצים לשלב את Code Execution עם Agent Frameworks אחרים.
במדריך למתחילים הזה תבצעו את הפעולות הבאות:
- יצירת מכונה של Agent Platform כדי לגשת להרצת קוד
- יצירת ארגז חול להרצת קוד
- (אופציונלי) הצגת רשימה של ארגזי חול וקבלת ארגזי חול
- הרצת קוד בארגז חול (sandbox)
- להריץ עוד קוד באותו ארגז חול. שימו לב שארגז החול שומר על המצב שלו באופן אוטומטי.
- הסרת המשאבים
מידע נוסף על השימוש בהרצת קוד עם ערכת הפיתוח לסוכנים (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, בקשו מהאדמין להקצות לכם את התפקיד משתמש בפלטפורמת הסוכנים (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 .
LOCATION: האזור של המכונה של Agent Platform. Google Cloud אזורים נתמכים
יצירת ארגז חול (sandbox)
יצירת ארגז חול להרצת קוד.
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 .
LOCATION: האזור של המכונה של Agent Platform. Google Cloud אזורים נתמכים
INSTANCE_ID: המזהה של המכונה של Agent Platform.
יש תמיכה רק ב-LANGUAGE_PYTHON וב-LANGUAGE_JAVASCRIPT. אם לא מציינים את machine_config, הגדרת ברירת המחדל היא 2 vCPU ו-1.5GB RAM. אם מציינים MACHINE_CONFIG_VCPU4_RAM4GIB, לארגז החול יש 4 vCPU ו-4GB של 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))
)
הרצת קוד בארגז חול (sandbox)
כדי להריץ קוד, צריך להפעיל את 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) של ארגז החול. - הפלט הוא בבייטים גולמיים.
- כל בקשה או תשובה יכולה להכיל קבצים בנפח של עד 100MB.
הרצת קוד נוסף בארגז חול (sandbox)
כדי להדגים שארגז החול שומר על המצב שלו, מריצים עוד קוד באותו ארגז חול:
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()