AG2Agent ב-Agent Platform SDK, אתם יכולים ליצור סוכנים שמבצעים משימות מורכבות ומשתלבים עם כלים חיצוניים.
במאמר הזה מוסבר איך לפתח סוכן AG2, כולל הגדרת המודל, הוספת כלים והתאמה אישית של תהליך התזמור.
מידע נוסף על ניהול הנציגים שנפרסו זמין במאמר ניהול הנציגים שנפרסו.
כדי ליצור סוכן AG2:
לפני שמתחילים
מוודאים שהסביבה מוגדרת לפי השלבים שמפורטים בקטע הגדרת הסביבה.
שלב 1. הגדרה של אובייקט שאפשר להריץ
מציינים את המודל שרוצים להשתמש בו:
model = "gemini-3.5-flash"
מגדירים את השם של האובייקט שאפשר להריץ:
runnable_name = "Get Exchange Rate Agent"
אופציונלי: מגדירים את המודל:
from google.cloud.aiplatform.aiplatform import initializer
llm_config = {
"config_list": [{
"project_id": initializer.global_config.project,
"location": initializer.global_config.location,
"model": "gemini-3.5-flash",
"api_type": "google",
}]
}
מידע נוסף על הגדרת המודל ב-AG2 זמין במאמר Model Configuration Deep-dive.
אופציונלי: קובעים את הגדרות הבטיחות של המודל. הדוגמה הבאה ממחישה איך אפשר לקבוע את הגדרות הבטיחות:
from vertexai.generative_models import HarmBlockThreshold, HarmCategory
safety_settings = {
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
}
for config_item in llm_config["config_list"]:
config_item["safety_settings"] = safety_settings
מידע נוסף על האפשרויות הזמינות להגדרות הבטיחות ב-Gemini מופיע במאמר הגדרת מאפייני בטיחות.
יוצרים AG2Agent באמצעות הגדרות המודל:
from vertexai import agent_engines
agent = agent_engines.AG2Agent(
model=model, # Required.
runnable_name=runnable_name, # Required.
llm_config=llm_config, # Optional.
)
אם אתם מריצים בסביבה אינטראקטיבית (כמו מסוף או נוטבוק של Colab), אתם יכולים להריץ שאילתה כשלב ביניים לבדיקה:
response = agent.query(input="What is the exchange rate from US dollars to SEK today?", max_turns=1)
print(response)
התגובה היא מילון Python שדומה לדוגמה הבאה:
{'chat_id': None,
'chat_history': [{'content': 'What is the exchange rate from US dollars to Swedish currency?',
'role': 'assistant',
'name': 'user'},
{'content': 'I do not have access to real-time information, including currency exchange rates. To get the most up-to-date exchange rate from US dollars to Swedish Krona (SEK), I recommend using a reliable online currency converter or checking with your bank. \n',
'role': 'user',
'name': 'Exchange Rate Agent'}],
'summary': 'I do not have access to real-time information, including currency exchange rates. To get the most up-to-date exchange rate from US dollars to Swedish Krona (SEK), I recommend using a reliable online currency converter or checking with your bank. \n',
'cost': {'usage_including_cached_inference': {'total_cost': 5.2875e-06,
'gemini-3.5-flash': {'cost': 5.2875e-06,
'prompt_tokens': 34,
'completion_tokens': 62,
'total_tokens': 96}},
'usage_excluding_cached_inference': {'total_cost': 5.2875e-06,
'gemini-3.5-flash': {'cost': 5.2875e-06,
'prompt_tokens': 34,
'completion_tokens': 62,
'total_tokens': 96}}},
'human_input': []}
אופציונלי: התאמה אישית מתקדמת
בתבנית AG2Agent נעשה שימוש ב-api_type=="google" כברירת מחדל, כי היא מספקת גישה לכל המודלים הבסיסיים שזמינים ב- Google Cloud. כדי להשתמש במודל שלא זמין דרך api_type=="google", אתם יכולים להתאים אישית את הפרמטר llm_config.
כאן מפורטים המודלים שנתמכים ב-AG2 והיכולות שלהם.
קבוצת הערכים הנתמכים של llm_config= היא ספציפית לכל מודל צ'אט, לכן צריך לעיין במסמכים המתאימים לקבלת פרטים.
Gemini
מותקן כברירת מחדל.
הוא משמש ב-AG2Agent כשמשמיטים את הארגומנט llm_config, לדוגמה:
from vertexai import agent_engines
agent = agent_engines.AG2Agent(
model=model, # Required.
runnable_name=runnable_name # Required.
)
Anthropic
קודם כל, פועלים לפי ההוראות כדי להגדיר חשבון ולהתקין את החבילה.
אחר כך מגדירים llm_config:
llm_config = {
"config_list": [{
"model": "claude-3-5-sonnet-20240620", # Required.
"api_key": "ANTHROPIC_API_KEY", # Required.
"api_type": "anthropic", # Required.
}]
}
לבסוף, משתמשים בו ב-AG2Agent עם הקוד הבא:
from vertexai import agent_engines
agent = agent_engines.AG2Agent(
model="claude-3-5-sonnet-20240620", # Required.
runnable_name=runnable_name, # Required.
llm_config=llm_config, # Optional.
)
OpenAI
אתם יכולים להשתמש ב-OpenAI בשילוב עם ChatCompletions API של Gemini.
קודם כול, מגדירים llm_config:
import google.auth
from google.cloud.aiplatform.aiplatform import initializer
project = initializer.global_config.project
location = initializer.global_config.location
base_url = f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{project}/locations/{location}/endpoints/openapi"
# Note: the credential lives for 1 hour by default.
# After expiration, it must be refreshed.
creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)
llm_config = {
"config_list": [{
"model": "google/gemini-3.5-flash", # Required.
"api_type": "openai", # Required.
"base_url": base_url, # Required.
"api_key": creds.token, # Required.
}]
}
לבסוף, משתמשים בו ב-AG2Agent עם הקוד הבא:
from vertexai import agent_engines
agent = agent_engines.AG2Agent(
model="google/gemini-3.5-flash", # Or "meta/llama3-405b-instruct-maas".
runnable_name=runnable_name, # Required.
llm_config=llm_config, # Optional.
)
שלב 2. הגדרה של כלי ושימוש בו
אחרי שמגדירים את המודל, השלב הבא הוא להגדיר את הכלים שבהם המודל משתמש כדי להסיק מסקנות. כלי יכול להיות כלי AG2 או פונקציית Python.
כשמגדירים את הפונקציה, חשוב לכלול הערות שמתארות באופן מלא וברור את הפרמטרים של הפונקציה, מה הפונקציה עושה ומה הפונקציה מחזירה. המודל משתמש במידע הזה כדי לקבוע באיזו פונקציה להשתמש. אתם צריכים גם לבדוק את הפונקציה באופן מקומי כדי לוודא שהיא פועלת.
משתמשים בקוד הבא כדי להגדיר פונקציה שמחזירה שער חליפין:
def get_exchange_rate(
currency_from: str = "USD",
currency_to: str = "EUR",
currency_date: str = "latest",
):
"""Retrieves the exchange rate between two currencies on a specified date.
Uses the Frankfurter API (https://api.frankfurter.app/) to obtain
exchange rate data.
Args:
currency_from: The base currency (3-letter currency code).
Defaults to "USD" (US Dollar).
currency_to: The target currency (3-letter currency code).
Defaults to "EUR" (Euro).
currency_date: The date for which to retrieve the exchange rate.
Defaults to "latest" for the most recent exchange rate data.
Can be specified in YYYY-MM-DD format for historical rates.
Returns:
dict: A dictionary containing the exchange rate information.
Example: {"amount": 1.0, "base": "USD", "date": "2023-11-24",
"rates": {"EUR": 0.95534}}
"""
import requests
response = requests.get(
f"https://api.frankfurter.app/{currency_date}",
params={"from": currency_from, "to": currency_to},
)
return response.json()
כדי לבדוק את הפונקציה לפני שמשתמשים בה בנציג, מריצים את הפקודה הבאה:
get_exchange_rate(currency_from="USD", currency_to="SEK")
התגובה אמורה להיראות כך:
{'amount': 1.0, 'base': 'USD', 'date': '2024-02-22', 'rates': {'SEK': 10.3043}}
כדי להשתמש בכלי בתוך AG2Agent, צריך להוסיף אותו לרשימת הכלים בארגומנט tools=:
from vertexai import agent_engines
agent = agent_engines.AG2Agent(
model=model, # Required.
runnable_name=runnable_name, # Required.
tools=[get_exchange_rate], # Optional.
)
כדי לבדוק את הנציג באופן מקומי, אפשר להריץ עליו שאילתות בדיקה. מריצים את הפקודה הבאה כדי לבדוק את הנציג באופן מקומי באמצעות דולר ארה"ב וקרונה שוודית:
response = agent.query(input="What is the exchange rate from US dollars to Swedish currency?", max_turns=2)
התגובה היא מילון שדומה לזה:
{'chat_id': None,
'chat_history': [{'content': 'What is the exchange rate from US dollars to Swedish currency?',
'role': 'assistant',
'name': 'user'},
{'content': '',
'tool_calls': [{'id': '2285',
'function': {'arguments': '{"currency_from": "USD", "currency_to": "SEK"}',
'name': 'get_exchange_rate'},
'type': 'function'}],
'role': 'assistant'},
{'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}",
'tool_responses': [{'tool_call_id': '2285',
'role': 'tool',
'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}"}],
'role': 'tool',
'name': 'user'},
{'content': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
'role': 'user',
'name': 'Get Exchange Rate Agent'},
{'content': 'What is the exchange rate from US dollars to Swedish currency?',
'role': 'assistant',
'name': 'user'},
{'content': '',
'tool_calls': [{'id': '4270',
'function': {'arguments': '{"currency_from": "USD", "currency_to": "SEK"}',
'name': 'get_exchange_rate'},
'type': 'function'}],
'role': 'assistant'},
{'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}",
'tool_responses': [{'tool_call_id': '4270',
'role': 'tool',
'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}"}],
'role': 'tool',
'name': 'user'},
{'content': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
'role': 'user',
'name': 'Get Exchange Rate Agent'}],
'summary': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
'cost': {'usage_including_cached_inference': {'total_cost': 0.0002790625,
'gemini-3.5-flash': {'cost': 0.0002790625,
'prompt_tokens': 757,
'completion_tokens': 34,
'total_tokens': 791}},
'usage_excluding_cached_inference': {'total_cost': 0.0002790625,
'gemini-3.5-flash': {'cost': 0.0002790625,
'prompt_tokens': 757,
'completion_tokens': 34,
'total_tokens': 791}}},
'human_input': []}
שלב 3. התאמה אישית של התזמור
כל סוכני AG2 מטמיעים את ממשק ConversableAgent, שמספק סכימות קלט ופלט לתזמור. כדי שהתבנית AG2Agent תגיב לשאילתות, צריך ליצור בשבילה אובייקט שאפשר להריץ. כברירת מחדל, AG2Agent ייצור אובייקט כזה שאפשר להריץ על ידי קישור המודל לכלים.
כדאי להתאים אישית את הניהול אם רוצים (1) להטמיע סוכן Assistant שפותר משימה באמצעות מודל, (2) להטמיע סוכן User Proxy שיכול להריץ קוד ולספק משוב לסוכנים האחרים, או (3) להטמיע סוכן Reasoning שפותר משימה באמצעות מודל וחשיבה מסוג Tree-of-Thought. כדי לעשות את זה, צריך לשנות את ברירת המחדל של האובייקט שאפשר להריץ כשיוצרים את AG2Agent, על ידי ציון הארגומנט runnable_builder= עם פונקציית Python של החתימה הבאה:
def runnable_builder(
**runnable_kwargs,
):
כך אפשר להתאים אישית את לוגיקת התזמור בדרכים שונות.
Assistant Agent
במקרה הפשוט ביותר, כדי ליצור סוכן Assistant בלי תזמור, אפשר לשנות את runnable_builder עבור AG2Agent.
from vertexai import agent_engines
def runnable_builder(**kwargs):
from autogen import agentchat
return agentchat.AssistantAgent(**kwargs)
agent = agent_engines.AG2Agent(
model=model,
runnable_name=runnable_name,
runnable_builder=runnable_builder,
)
סוכן משתמש של שרת proxy
במקרה הפשוט ביותר, כדי ליצור סוכן proxy של משתמש בלי תזמור, אפשר לשנות את runnable_builder עבור AG2Agent.
from vertexai import agent_engines
def runnable_builder(**kwargs):
from autogen import agentchat
return agentchat.UserProxyAgent(**kwargs)
agent = agent_engines.AG2Agent(
model=model,
runnable_name=runnable_name,
runnable_builder=runnable_builder,
)
סוכן חשיבה רציונלית
במקרה הפשוט ביותר, כדי ליצור סוכן מבוסס-הסקה בלי תזמור, אפשר לשנות את runnable_builder של AG2Agent.
from vertexai import agent_engines
def runnable_builder(**kwargs):
from autogen import agentchat
return agentchat.ReasoningAgent(**kwargs)
agent = agent_engines.AG2Agent(
model=model,
runnable_name=runnable_name,
runnable_builder=runnable_builder,
)