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 ייצור אובייקט שאפשר להריץ כזה על ידי קישור המודל לכלים.
יכול להיות שתרצו להתאים אישית את התזמור אם אתם מתכוונים (i) להטמיע סוכן Assistant שפותר משימה באמצעות מודל, או (ii) להטמיע סוכן User Proxy שיכול להריץ קוד ולספק משוב לסוכנים אחרים, או (iii) להטמיע סוכן Reasoning שפותר משימה באמצעות מודל והסקה מסוג עץ מחשבה. כדי לעשות זאת, צריך לקבוע ידנית את ברירת המחדל של אובייקט שאפשר להריץ כשיוצרים AG2Agent על ידי ציון הארגומנט runnable_builder= עם פונקציית Python מהחתימה הבאה:
def runnable_builder(
**runnable_kwargs,
):
כך אפשר להתאים אישית את לוגיקת התזמור.
סוכן Assistant
במקרה הפשוט ביותר, כדי ליצור סוכן של 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,
)
User Proxy Agent
במקרה הפשוט ביותר, כדי ליצור סוכן 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,
)
המאמרים הבאים
הערכת הסוכנים
יצירה ופריסה של סוכן בסיסי ושימוש בשירות ההערכה של AI גנרטיבי כדי להעריך את הסוכן