לפני שמתחילים
במדריך הזה אנחנו יוצאים מנקודת הנחה שקראתם את ההוראות במאמרים הבאים ופעלתם לפיהן:
- יצירת סוכן בהתאמה אישית: כדי ליצור
agentבהתאמה אישית. - אימות משתמשים כדי לאמת את המשתמש ששולח שאילתות לנציג.
- מייבאים ומפעילים את ה-SDK כדי להפעיל את הלקוח ולקבל מכונה פרוסה (אם צריך).
קבלת מופע של סוכן
כדי לשלוח שאילתה לסוכן, קודם צריך ליצור מופע של סוכן. אפשר ליצור מכונה חדשה או לקבל מכונה קיימת של סוכן.
כדי לקבל את הסוכן שתואם למזהה משאב ספציפי:
Agent Platform SDK
מריצים את הקוד הבא:
import agentplatform
client = agentplatform.Client( # For service interactions via client.runtimes
project="PROJECT_ID",
location="LOCATION",
)
agent = client.runtimes.get(name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")
print(agent)
כאשר
-
PROJECT_IDהוא מזהה הפרויקט ב- Cloud de Confiance by S3NS שבו יוצרים ופורסים נציגים, וגם LOCATIONהוא אחד מהאזורים הנתמכים.-
RESOURCE_IDהוא המזהה של הנציג שנפרס כמשאבreasoningEngine.
בקשות
מריצים את הקוד הבא:
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
response = requests.get(
f"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
)
REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_IDכשמשתמשים ב-Agent Platform SDK ל-Python, האובייקט agent תואם לכיתה AgentRuntime שמכילה את הפרטים הבאים:
-
agent.api_resourceעם מידע על הנציג שהוטמע. אפשר גם להפעיל אתagent.operation_schemas()כדי להחזיר את רשימת הפעולות שנתמכות על ידיagent. פרטים נוספים זמינים בקטע פעולות נתמכות. -
agent.api_clientשמאפשרת אינטראקציות סינכרוניות בין שירותים -
agent.async_api_clientשמאפשרת אינטראקציות אסינכרוניות עם שירותים
בהמשך החלק הזה אנחנו מניחים שיש לכם מכונה בשם agent.
רשימת הפעולות הנתמכות
כשמפתחים את הנציג באופן מקומי, יש לכם גישה לפעולות שהוא תומך בהן ואתם מכירים אותן. כדי להשתמש בנציג פרוס, אתם יכולים למנות את הפעולות שהוא תומך בהן:
Agent Platform SDK
מריצים את הקוד הבא:
print(agent.operation_schemas())
בקשות
מריצים את הקוד הבא:
import json
json.loads(response.content).get("spec").get("classMethods")
REST
מיוצג ב-spec.class_methods מהתגובה לבקשת ה-curl.
הסכימה של כל פעולה היא מילון שמתעד את המידע של שיטה לסוכן שאפשר לקרוא לה. קבוצת הפעולות הנתמכות תלויה במסגרת שבה השתמשתם כדי לפתח את הנציג:
לדוגמה, הסכימה הבאה היא לפעולה query של LangchainAgent:
{'api_mode': '',
'name': 'query',
'description': """Queries the Agent with the given input and config.
Args:
input (Union[str, Mapping[str, Any]]):
Required. The input to be passed to the Agent.
config (langchain_core.runnables.RunnableConfig):
Optional. The config (if any) to be used for invoking the Agent.
Returns:
The output of querying the Agent with the given input and config.
""", ' ',
'parameters': {'$defs': {'RunnableConfig': {'description': 'Configuration for a Runnable.',
'properties': {'configurable': {...},
'run_id': {...},
'run_name': {...},
...},
'type': 'object'}},
'properties': {'config': {'nullable': True},
'input': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}},
'required': ['input'],
'type': 'object'}}
כאשר
-
nameהוא שם הפעולה (למשלagent.queryלפעולה בשםquery). -
api_modeהוא מצב ה-API של הפעולה (""לסינכרוני,"stream"לסטרימינג). -
descriptionהוא תיאור של הפעולה שמבוסס על ה-docstring של השיטה. -
parametersהיא הסכימה של הארגומנטים של הקלט בפורמט של סכימת OpenAPI.
שליחת שאילתה לסוכן באמצעות פעולות נתמכות
בסוכנים בהתאמה אישית, אתם יכולים להשתמש בכל אחת מהפעולות הבאות של שאילתות או סטרימינג שהגדרתם כשפיתחתם את הסוכן:
חשוב לזכור שחלק מה-frameworks תומכים רק בפעולות ספציפיות של שאילתות או סטרימינג:
| Framework | פעולות נתמכות של שאילתות |
|---|---|
| ערכה לפיתוח סוכנים (ADK) | async_stream_query |
| LangChain | query, stream_query |
| LangGraph | query, stream_query |
| AG2 | query |
| LlamaIndex | query |
שליחת שאילתה לסוכן
שולחים שאילתה לסוכן באמצעות הפעולה query:
Agent Platform SDK
agent.query(input="What is the exchange rate from US dollars to Swedish Krona today?")
בקשות
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
requests.post(
f"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({
"class_method": "query",
"input": {
"input": "What is the exchange rate from US dollars to Swedish Krona today?"
}
})
)
REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{
"class_method": "query",
"input": {
"input": "What is the exchange rate from US dollars to Swedish Krona today?"
}
}'התגובה לשאילתה היא מחרוזת שדומה לפלט של בדיקת אפליקציה מקומית:
{"input": "What is the exchange rate from US dollars to Swedish Krona today?",
# ...
"output": "For 1 US dollar you will get 10.7345 Swedish Krona."}
הצגת התשובות מהסוכן באופן שוטף
כדי להעביר תשובה מהסוכן בסטרימינג, משתמשים בפעולה stream_query:
Agent Platform SDK
agent = client.runtimes.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")
for response in agent.stream_query(
input="What is the exchange rate from US dollars to Swedish Krona today?"
):
print(response)
בקשות
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
requests.post(
f"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({
"class_method": "stream_query",
"input": {
"input": "What is the exchange rate from US dollars to Swedish Krona today?"
},
}),
stream=True,
)
REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery?alt=sse -d '{
"class_method": "stream_query",
"input": {
"input": "What is the exchange rate from US dollars to Swedish Krona today?"
}
}'פלטפורמת Agent מעבירה תשובות בסטרימינג כרצף של אובייקטים שנוצרים באופן איטרטיבי. לדוגמה, קבוצה של שלוש תשובות יכולה להיראות כך:
{'actions': [{'tool': 'get_exchange_rate', ...}]} # first response
{'steps': [{'action': {'tool': 'get_exchange_rate', ...}}]} # second response
{'output': 'The exchange rate is 11.0117 SEK per USD as of 2024-12-03.'} # final response
שליחת שאילתה אסינכרונית לסוכן
אם הגדרתם פעולת async_query כשיצרתם את הנציג, יש תמיכה בשאילתות אסינכרוניות בצד הלקוח של הנציג ב-Agent Platform SDK for Python:
Agent Platform SDK ל-Python
agent = client.runtimes.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")
response = await agent.async_query(
input="What is the exchange rate from US dollars to Swedish Krona today?"
)
print(response)
התגובה לשאילתה היא מילון שזהה לפלט של בדיקה מקומית:
{"input": "What is the exchange rate from US dollars to Swedish Krona today?",
# ...
"output": "For 1 US dollar you will get 10.7345 Swedish Krona."}
שידור תשובות מהסוכן באופן אסינכרוני
אם הגדרתם פעולת async_stream_query כשיצרתם את הנציג, אתם יכולים להעביר תשובה מהנציג בסטרימינג אסינכרוני באמצעות אחת מהפעולות שלו (למשל async_stream_query):
Agent Platform SDK ל-Python
agent = client.runtimes.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")
async for response in agent.async_stream_query(
input="What is the exchange rate from US dollars to Swedish Krona today?"
):
print(response)
הפעולה async_stream_query קוראת לאותה נקודת קצה (endpoint) של streamQuery מאחורי הקלעים, ומעבירה תשובות בסטרימינג באופן אסינכרוני כרצף של אובייקטים שנוצרים באופן איטרטיבי. לדוגמה, קבוצה של שלוש תשובות יכולה להיראות כך:
{'actions': [{'tool': 'get_exchange_rate', ...}]} # first response
{'steps': [{'action': {'tool': 'get_exchange_rate', ...}}]} # second response
{'output': 'The exchange rate is 11.0117 SEK per USD as of 2024-12-03.'} # final response
התשובות צריכות להיות זהות לאלה שנוצרו במהלך הבדיקה המקומית.
משימות של שאילתות ממושכות
שאילתות שהשלמתן עשויה להימשך זמן רב (עד שבעה ימים) אפשר להריץ כמשימות ארוכות. מידע נוסף זמין במאמר שימוש בסוכן ADK.
התחלת משימת שאילתה ממושכת
כדי להתחיל משימת שאילתה שפועלת לאורך זמן:
Agent Platform SDK ל-Python
import agentplatform
client = agentplatform.Client(
project="PROJECT_ID",
location="LOCATION",
)
response = client.runtimes.run_query_job(
name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
config={
"query": '{ "input": {"product": "Google"} }',
"output_gcs_uri": "gs://GCS_BUCKET_NAME/OUTPUT_FILE",
},
)
print(response)
REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:asyncQuery -d \
'{
"input_gcs_uri": "gs://GCS_BUCKET_NAME/INPUT_FILE",
"output_gcs_uri": "gs://GCS_BUCKET_NAME/OUTPUT_FILE"
}'בדיקת הסטטוס של משימת שאילתה ממושכת
כדי לבדוק את הסטטוס ולאחזר את התוצאות של משימת שאילתה ממושכת:
Agent Platform SDK
response = client.runtimes.check_query_job(
name="JOB_NAME",
config={
"retrieve_result": True,
},
)
print(response)