פיתוח סוכן באמצעות ערכה לפיתוח סוכנים (ADK)

הסביבה Agent Runtime מאפשרת לכם לפתח ולפרוס סוכנים באמצעות תבנית הערכה לפיתוח סוכנים (ADK). באמצעות המחלקה AdkApp ב-Agent Platform SDK ל-Python, אפשר ליצור סוכנים שמחזירים שערי חליפין ומנהלים אינטראקציות עם שמירת מצב.

במסמך הזה מוסבר איך לפתח סוכן 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)

אם אתם מריצים את הפקודה בסביבה אינטראקטיבית, כמו במסוף או ב-notebook של 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 באופן מקומי, ההוראות הבאות מתייחסות לסשנים בזיכרון.

כדי ליצור סשן לסוכן, משתמשים בשיטה AdkApp.async_create_session:

session = await app.async_create_session(user_id="USER_ID")
print(session)

הסשן נוצר כייצוג מילוני של אובייקט של סשן ADK.

כדי להציג רשימה של סשנים שמשויכים לסוכן, משתמשים בשיטה AdkApp.async_list_sessions:

await app.async_list_sessions(user_id="USER_ID")

כדי לקבל סשן מסוים, משתמשים בשיטה AdkApp.async_get_session:

session = await app.async_get_session(user_id="USER_ID", session_id="SESSION_ID")

איפה

  • ‫USER_ID הוא מזהה המשתמש שהגדרתם. לדוגמה, user-123.

  • ‫SESSION_ID הוא המזהה של הסשן הספציפי שרוצים לאחזר.

כדי לשלוח שאילתה לסוכן באופן אסינכרוני, משתמשים בשיטה 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 באמצעות זיכרונות:

  1. יוצרים סשן ומנהלים אינטראקציה עם הסוכן:

    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)
    

    יכול להיות שהסוכן יחזיר תשובה כמו 'הגדרת הטמפרטורה ל-71 מעלות פרנהייט'. הטמפרטורה שונתה בהצלחה". התשובה של הסוכן עשויה להיות שונה בהתאם למודל שבו השתמשתם.

  2. ליצור זיכרונות מהסשן. כדי לשמור מידע מהסשן לשימוש בסשנים עתידיים, משתמשים בשיטה async_add_session_to_memory:

    await app.async_add_session_to_memory(session=initial_session)
    
  3. כדי לבדוק שהסוכן שמר את הזיכרון של הסשן (באמצעות 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)
    

    יכול להיות שהסוכן יחזיר תשובה כמו 'הגדרת הטמפרטורה ל-71 מעלות'. האם זה נכון?" התשובה של הסוכן עשויה להשתנות בהתאם למודל ולספק שירות הזיכרון שבו השתמשתם.

  4. כדי להציג את הזיכרונות של הסוכן, משתמשים בשיטה async_search_memory:

    response = await app.async_search_memory(
        user_id="USER_ID",
        query="Fix the temperature!",
    )
    print(response)
    

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

מדריך

יש 5 דרכים לפרוס סוכן ב-Agent Platform Runtime בהתאם לצרכים שלכם בפיתוח.

סקירה כללית

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

סקירה כללית

איך משתמשים ב-Memory Bank כדי לאחסן העדפות ונתונים של משתמשים לטווח ארוך

מדריך

שימוש בסוכן של ערכה לפיתוח סוכנים (ADK) עם Agent Platform Runtime.

מדריך

יצירה ופריסה של סוכן בסיסי ושימוש בשירות ההערכה של AI גנרטיבי כדי להעריך את הסוכן

פתרון בעיות

איך פותרים שגיאות נפוצות כשיוצרים סוכנים בהתאמה אישית

Resource

מקורות מידע ותמיכה ל-Google Agent Platform