שימוש בסוכן מותאם אישית

לפני שמתחילים

במדריך הזה אנחנו יוצאים מנקודת הנחה שקראתם את ההוראות במאמרים הבאים ופעלתם לפיהן:

אחזור מופע של סוכן

כדי לשלוח שאילתה לסוכן, קודם צריך ליצור מופע של סוכן. אפשר ליצור מופע חדש או לקבל מופע קיים של סוכן.

כדי לקבל את הנציג שמתאים למזהה משאב ספציפי:

Agent Platform SDK

מריצים את הקוד הבא:

import vertexai

client = vertexai.Client(  # For service interactions via client.agent_engines
    project="PROJECT_ID",
    location="LOCATION",
)

agent = client.agent_engines.get(name="projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

print(agent)

איפה

בקשות

מריצים את הקוד הבא:

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 תואם למחלקה AgentEngine שכוללת את הפרטים הבאים:

  • 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 הוא תיאור של הפעולה על סמך מחרוזת התיעוד של השיטה.
  • parameters היא הסכימה של ארגומנטי הקלט בפורמט סכימה של OpenAPI.

שליחת שאילתה לסוכן באמצעות פעולות נתמכות

בסוכנים מותאמים אישית, אפשר להשתמש בכל אחת מהפעולות הבאות של שאילתות או סטרימינג שהגדרתם כשפיתחתם את הסוכן:

שימו לב שחלק מה-frameworks תומכים רק בפעולות ספציפיות של שאילתות או סטרימינג:

Framework פעולות נתמכות בשאילתות
Agent Development Kit 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 = agent_engines.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 Platform מוזרמות כרצף של אובייקטים שנוצרים באופן איטרטיבי. לדוגמה, קבוצה של שלוש תשובות יכולה להיראות כך:

{'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 = agent_engines.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 = agent_engines.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 vertexai

client = vertexai.Client(
    project="PROJECT_ID",
    location="LOCATION",
)

response = client.agent_engines.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.agent_engines.check_query_job(
    name="JOB_NAME",
    config={
        "retrieve_result": True,
    },
)
print(response)

המאמרים הבאים