AdkApp ב-Agent Platform SDK ל-Python, אתם יכולים ליצור סוכנים שמחזירים שערי חליפין ומנהלים אינטראקציות עם שמירת מצב (stateful).
במאמר הזה מוסבר איך לפתח סוכן ADK, כולל הגדרת המודל, הוספת כלים וניהול סשנים וזיכרונות.
מידע נוסף על ניהול הנציגים שנפרסו זמין במאמר ניהול הנציגים שנפרסו.
לפני שמתחילים
מוודאים שהסביבה מוגדרת לפי השלבים שמפורטים בקטע הגדרת הסביבה.
הגדרה של מודל
מציינים את המודל שרוצים להשתמש בו:
model = "gemini-2.0-flash"
אופציונלי: קובעים את הגדרות הבטיחות של המודל. במאמר הגדרת מאפייני בטיחות מוסבר איך להגדיר את מאפייני הבטיחות ב-Gemini. הדוגמה הבאה ממחישה איך אפשר לקבוע את הגדרות הבטיחות:
from google.genai import types
safety_settings = [
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=types.HarmBlockThreshold.OFF,
),
]
אופציונלי: מציינים פרמטרים ליצירת תוכן:
from google.genai import types
generate_content_config = types.GenerateContentConfig(
safety_settings=safety_settings,
temperature=0.28,
max_output_tokens=1000,
top_p=0.95,
)
יוצרים AdkApp באמצעות הגדרות המודל:
from google.adk.agents import Agent
from vertexai.agent_engines import AdkApp
agent = Agent(
model=model, # Required.
name='currency_exchange_agent', # Required.
generate_content_config=generate_content_config, # Optional.
)
app = AdkApp(agent=agent)
אם אתם מריצים בסביבה אינטראקטיבית, כמו הטרמינל או נוטבוק של Colab, אתם יכולים להריץ שאילתה באמצעות השיטה AdkApp.async_stream_query כשלב בדיקה ביניים:
async for event in app.async_stream_query(
user_id="USER_ID", # Required
message="What is the exchange rate from US dollars to Swedish currency?",
):
print(event)
- USER_ID: בוחרים מזהה משתמש משלכם עם מגבלת תווים של 128.
לדוגמה,
user-123.
התגובה היא מילון Python שדומה לדוגמה הבאה:
{'actions': {'artifact_delta': {},
'requested_auth_configs': {},
'state_delta': {}},
'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'To provide you with the most accurate '
'exchange rate, I need to know the specific '
'currencies you\'re asking about. "Swedish '
'currency" could refer to:\n'
'\n'
'* **Swedish Krona (SEK):** This is the '
'official currency of Sweden.\n'
'\n'
"Please confirm if you're interested in the "
'exchange rate between USD and SEK. Once you '
'confirm, I can fetch the latest exchange rate '
'for you.\n'}],
'role': 'model'},
'id': 'LYg7wg8G',
'invocation_id': 'e-113ca547-0f19-4d50-9dde-f76cbc001dce',
'timestamp': 1744166956.925927}
אופציונלי: הגדרה של כלי ושימוש בו
אחרי שמגדירים את המודל, מגדירים את הכלים שבהם המודל משתמש כדי להסיק מסקנות.
כשמגדירים את הפונקציה, חשוב לכלול הערות שמתארות באופן מלא וברור את הפרמטרים של הפונקציה, מה הפונקציה עושה ומה הפונקציה מחזירה. המודל משתמש במידע הזה כדי לקבוע באיזו פונקציה להשתמש. אתם צריכים גם לבדוק את הפונקציה באופן מקומי כדי לוודא שהיא פועלת.
משתמשים בקוד הבא כדי להגדיר פונקציה שמחזירה שער חליפין:
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': '2025-04-03', 'rates': {'SEK': 9.6607}}
כדי להשתמש בכלי בתוך AdkApp, מוסיפים אותו לרשימת הכלים בארגומנט tools=:
from google.adk.agents import Agent
agent = Agent(
model=model, # Required.
name='currency_exchange_agent', # Required.
tools=[get_exchange_rate], # Optional.
)
כדי לבדוק את הנציג באופן מקומי, אפשר להריץ עליו שאילתות בדיקה באמצעות ה-method AdkApp.async_stream_query. מריצים את הפקודה הבאה כדי לבדוק את הנציג באופן מקומי באמצעות דולר ארה"ב וקרונה שוודית:
from vertexai.agent_engines import AdkApp
app = AdkApp(agent=agent)
async for event in app.async_stream_query(
user_id="USER_ID",
message="What is the exchange rate from US dollars to SEK on 2025-04-03?",
):
print(event)
כאשר USER_ID הוא מזהה המשתמש שהגדרתם. לדוגמה, user-123.
התגובה היא רצף של מילונים שדומה לדוגמה הבאה:
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
'currency_from': 'USD',
'currency_to': 'SEK'},
'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
'name': 'get_exchange_rate'}}],
'role': 'model'},
'id': 'zFyIaaif',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_response': {'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
'name': 'get_exchange_rate',
'response': {'amount': 1.0,
'base': 'USD',
'date': '2025-04-03',
'rates': {'SEK': 9.6607}}}}],
'role': 'user'},
'id': 'u2YR4Uom',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
'2025-04-03 is 9.6607.'}],
'role': 'model'},
'id': 'q3jWA3wl',
# ...
}
אופציונלי: ניהול הסשנים
AdkApp משתמש בסשנים בזיכרון כשהוא פועל באופן מקומי, ובסשנים מנוהלים בענן אחרי שפורסים את הנציג ב-Agent Runtime. בקטע הזה מוסבר איך להגדיר את סוכן ה-ADK כך שיעבוד עם סשנים מנוהלים.
אופציונלי: התאמה אישית של מסד הנתונים של הסשנים
אם אתם רוצים לשנות את שירות הסשנים המנוהל שמוגדר כברירת מחדל ולהשתמש במסד נתונים משלכם, אתם יכולים להגדיר פונקציית session_service_builder באופן הבא:
def session_service_builder():
from google.adk.sessions import InMemorySessionService
return InMemorySessionService()
מעבירים את מסד הנתונים אל AdkApp בתור session_service_builder=:
from vertexai.agent_engines import AdkApp
app = AdkApp(
agent=agent, # Required.
session_service_builder=session_service_builder, # Optional.
)
שימוש בסוכן בסשנים
כשמריצים את AdkApp באופן מקומי, ההוראות הבאות משתמשות בסשנים בזיכרון.
כדי ליצור סשן לסוכן, משתמשים ב-method AdkApp.async_create_session:
session = await app.async_create_session(user_id="USER_ID")
print(session)
הסשן נוצר כייצוג מילוני של אובייקט סשן של ADK.
כדי להציג את הסשנים שמשויכים לנציג, משתמשים ב-method AdkApp.async_list_sessions:
await app.async_list_sessions(user_id="USER_ID")
כדי לקבל סשן מסוים, משתמשים ב-method AdkApp.async_get_session:
session = await app.async_get_session(user_id="USER_ID", session_id="SESSION_ID")
כאשר
USER_ID הוא מזהה המשתמש שהגדרתם. לדוגמה,
user-123.SESSION_ID הוא המזהה של הסשן הספציפי שרוצים לאחזר.
כדי לשלוח שאילתה אסינכרונית לסוכן, משתמשים ב-method AdkApp.async_stream_query:
async for event in app.async_stream_query(
user_id="USER_ID",
session_id=SESSION_ID, # Optional. you can pass in the session_id when querying the agent
message="What is the exchange rate from US dollars to Swedish currency on 2025-04-03?",
):
print(event)
יכול להיות שהנציג יבקש מכם מידע כמו:
{'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'I need to know the Swedish currency code to '
'provide you with the exchange rate.'}],
'role': 'model'},
'id': 'wIgZAtQ4',
#...
}
אפשר לשלוח תשובה (לדוגמה, "SEK") בשם USER_ID בסשן שמתאים ל-session, על ידי ציון:
async for event in app.async_stream_query(
user_id="USER_ID",
session_id=session.id, # Optional. you can pass in the session_id when querying the agent
message="SEK",
):
print(event)
אתם אמורים לקבל המשך של השיחה, כמו רצף המילונים הבא:
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
'currency_from': 'USD',
'currency_to': 'SEK'},
'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
'name': 'get_exchange_rate'}}],
'role': 'model'},
'id': 'bOPHtzji',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_response': {'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
'name': 'get_exchange_rate',
'response': {'amount': 1.0,
'base': 'USD',
'date': '2025-04-03',
'rates': {'SEK': 9.6607}}}}],
'role': 'user'},
'id': '9AoDFmiL',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
'2025-04-03 is 1 USD to 9.6607 SEK.'}],
'role': 'model'},
'id': 'hmle7trT',
# ...
}
אופציונלי: ניהול הזיכרונות
כברירת מחדל, AdkApp משתמש בהטמעה בזיכרון של זיכרון הסוכן כשהוא פועל באופן מקומי, ומשתמש ב-Agent Platform Memory Bank אחרי שפורסים את הסוכן ב-Agent Runtime.
כשאתם מפתחים את סוכן ה-ADK, אתם יכולים לכלול PreloadMemoryTool שקובע מתי הסוכן מבצע שליפה אג'נטית של זיכרונות ואיך הזיכרונות נכללים בפרומפט. הסוכן לדוגמה הבא תמיד מאחזר זיכרונות בתחילת כל תור וכולל את הזיכרונות בהוראות המערכת:
from google.adk.agents import Agent
from google.adk.tools.preload_memory_tool import PreloadMemoryTool
from vertexai.agent_engines import AdkApp
agent = Agent(
model="gemini-2.0-flash",
name='stateful_agent',
instruction="""You are a Vehicle Voice Agent, designed to assist users with information and in-vehicle actions.
1. **Direct Action:** If a user requests a specific vehicle function (e.g., "turn on the AC"), execute it immediately using the corresponding tool. You don't have the outcome of the actual tool execution, so provide a hypothetical tool execution outcome.
2. **Information Retrieval:** Respond concisely to general information requests with your own knowledge (e.g., restaurant recommendation).
3. **Clarity:** When necessary, try to seek clarification to better understand the user's needs and preference before taking an action.
4. **Brevity:** Limit responses to under 30 words.
""",
tools=[PreloadMemoryTool()],
)
app = AdkApp(agent=agent)
אופציונלי: התאמה אישית של שירות הזיכרונות
אם אתם רוצים לשנות את שירות הזיכרון שמוגדר כברירת מחדל, אתם יכולים להגדיר פונקציית memory_service_builder שמחזירה BaseMemoryService, באופן הבא:
def memory_service_builder():
from google.adk.memory import InMemoryMemoryService
return InMemoryMemoryService()
מעבירים את מסד הנתונים אל AdkApp בתור memory_service_builder=:
from vertexai.agent_engines import AdkApp
app = AdkApp(
agent=agent, # Required.
memory_service_builder=memory_service_builder, # Optional.
)
שימוש בסוכן עם זיכרונות
כדי לבדוק את סוכן ה-ADK עם זיכרונות:
יוצרים סשן ומקיימים אינטראקציה עם הסוכן:
initial_session = await app.async_create_session(user_id="USER_ID") async for event in app.async_stream_query( user_id="USER_ID", session_id=initial_session.id, message="Can you update the temperature to my preferred temperature?", ): print(event)בסשן הראשון אין זיכרונות זמינים והסוכן לא מכיר את ההעדפות של המשתמש, לכן הוא יכול להשיב בתשובה כמו "מה הטמפרטורה המועדפת עליך?" אפשר להשיב באמצעות הפקודה הבאה:
async for event in app.async_stream_query( user_id="USER_ID", session_id=initial_session.id, message="I like it at 71 degrees", ): print(event)הנציג עשוי להחזיר תשובה כמו "הגדרת הטמפרטורה ל-21 מעלות צלזיוס. הטמפרטורה שונתה." התשובה של הסוכן עשויה להשתנות בהתאם למודל שבו השתמשתם.
ליצור זיכרונות מהסשן. כדי לאחסן מידע מהסשן לשימוש בסשנים עתידיים, משתמשים ב-method
async_add_session_to_memory:await app.async_add_session_to_memory(session=initial_session)כדי לבדוק אם הסוכן זוכר את הסשן (באמצעות
PreloadMemoryTool), יוצרים סשן חדש ונותנים לסוכן את ההנחיה הבאה:new_session = await app.async_create_session(user_id="USER_ID") async for event in app.async_stream_query( user_id="USER_ID", session_id=initial_session.id, message="Fix the temperature!", ): print(event)הנציג עשוי להחזיר תשובה כמו "הגדרת הטמפרטורה ל-21 מעלות. זה נכון?" התשובה של הנציג עשויה להשתנות בהתאם למודל ולספק שירות הזיכרון שבהם השתמשתם.
כדי להציג את הזיכרונות של הסוכן, משתמשים ב-method
async_search_memory:response = await app.async_search_memory( user_id="USER_ID", query="Fix the temperature!", ) print(response)
המאמרים הבאים
סקירה כללית על Memory Bank
איך משתמשים ב-Memory Bank כדי לאחסן עובדות והעדפות של משתמשים לטווח ארוך.
שימוש בסוכן שנוצר באמצעות ערכה לפיתוח סוכנים (ADK)
שימוש בסוכן של ערכה לפיתוח סוכנים (ADK) עם סביבת זמן הריצה של פלטפורמת הסוכנים.