Agent Platform Memory Bank נותן לסוכנים שאתם יוצרים באמצעות הערכה לפיתוח סוכנים (ADK) זיכרון לטווח ארוך בין סשנים. במדריך הזה תפעילו נציג שלומד את הטמפרטורה המועדפת על המשתמש בסשן אחד, וזוכר את ההעדפה בסשן הבא.
במדריך למתחילים הזה נסביר איך:
- מגדירים את הסביבה.
- יוצרים מכונה של Memory Bank.
- להריץ באופן מקומי סוכן ADK עם זיכרון.
- מוודאים שהנציג זוכר את ההעדפה בסשן חדש.
כדי לשלוח קריאה ישירות ל-Memory Bank בלי ADK, עיינו במדריך למתחילים בנושא Memory Bank API. כדי לבחור כלים אחרים של Memory Bank, קריאות חוזרות (callbacks) או סביבות זמן ריצה, קראו את המאמר שימוש ב-Memory Bank עם ADK.
לפני שמתחילים
- נכנסים לחשבון Google Cloud . אנחנו ממליצים למשתמשים חדשים ב- Google Cloudליצור חשבון כדי שיוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.- מגדירים סביבת פיתוח ב-Python.
-
אם משתמשים במעטפת מקומית, צריך ליצור פרטי כניסה לאימות מקומי בחשבון המשתמש:
gcloud auth application-default login
אם אתם משתמשים ב-Cloud Shell, אתם לא צריכים לעשות את זה.
אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו שנכנסתם ל-CLI של gcloud באמצעות הזהות המאוחדת.
התפקידים הנדרשים
כדי לקבל את ההרשאות שנדרשות ליצירת מכונה של Memory Bank, וליצירה ולאחזור של זיכרונות, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:
- יצירה או עדכון של מכונה של Memory Bank: משתמש ב-Agent Platform (`roles/aiplatform.user`)
- לקרוא, לכתוב או ליצור זיכרונות: משתמש ב-Memory Bank (`roles/aiplatform.memoryUser`)
להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.
יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.
מגדירים את הסביבה
בטרמינל, מתקינים את ADK ואת Agent Platform SDK:
pip install --upgrade "google-adk[gcp]" "google-cloud-agentplatform>=2.0.1"מגדירים את משתני הסביבה שהסקריפטים במדריך למתחילים הזה קוראים:
export GOOGLE_GENAI_USE_ENTERPRISE=TRUE export GOOGLE_CLOUD_PROJECT=PROJECT_ID export GOOGLE_CLOUD_LOCATION=globalמחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud .
במדריך למתחילים הזה משתמשים בנקודת הקצה הגלובלית. כדי להשתמש במיקום אזורי או במיקום במספר אזורים, מחליפים את
globalבאחד מהמיקומים הנתמכים. אם אתם צריכים מפתחות הצפנה בניהול הלקוח (CMEK), השתמשו במיקום אזורי או במיקום בכמה אזורים, כי CMEK לא זמין בנקודת הקצה הגלובלית.כדי שהסקריפטים יוכלו לקרוא את המשתנים האלה, צריך להריץ את שאר השלבים במדריך למתחילים באותו סשן של הטרמינל ובאותה ספרייה.
יצירת מכונה של Memory Bank
יוצרים קובץ בשם
create_memory_bank.pyעם הקוד הבא:import os import agentplatform client = agentplatform.Client( project=os.environ["GOOGLE_CLOUD_PROJECT"], location=os.environ["GOOGLE_CLOUD_LOCATION"], ) memory_bank = client.memory_banks.create( config={"display_name": "Memory Bank quickstart"} ) # Print only the instance ID, for example 1234567890. print(memory_bank.name.split("/")[-1])מריצים את הסקריפט ושומרים את מזהה המכונה במשתנה הסביבה
MEMORY_BANK_ID:export MEMORY_BANK_ID=$(python create_memory_bank.py)אם זו הפעם הראשונה שאתם יוצרים מכונה של Memory Bank, התהליך יכול להימשך דקה או שתיים.
מוודאים שהמשתנה מכיל את מזהה המכונה:
echo $MEMORY_BANK_IDהפלט הוא מזהה כמו
1234567890. אם הפלט ריק או שמוחזרת שגיאה מסוג401או403, בודקים את התפקידים הנדרשים ומריצים אתgcloud auth application-default login. אם מופע חדש שלglobalמחזיר שגיאת403זמנית בשימוש הראשון, המתינו 30 שניות והריצו את הסקריפט שוב.
הפעלת סוכן עם זיכרון פעיל
הסקריפט בקטע הזה מפעיל שני סשנים לאותו משתמש. בסשן הראשון, המשתמש מציין העדפה לגבי הטמפרטורה. בסשן השני, הנציג מאחזר את ההעדפה הזו מ-Memory Bank.
כך עושים את זה:
יוצרים ספרייה בשם
memory_agent:mkdir memory_agentיוצרים קובץ בשם
memory_agent/agent.pyעם הקוד הבא. הקוד קורא את הפרויקט, המיקום ומזהה המכונה מהמשתנים שהגדרתם בהגדרת הסביבה וביצירת מכונה של Memory Bank. אין צורך לערוך את הקוד.import asyncio import os import agentplatform from google import adk from google.adk.agents.callback_context import CallbackContext from google.adk.memory import VertexAiMemoryBankService from google.adk.sessions import InMemorySessionService from google.adk.tools.preload_memory_tool import PreloadMemoryTool from google.genai import types PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] LOCATION = os.environ["GOOGLE_CLOUD_LOCATION"] MEMORY_BANK_ID = os.environ["MEMORY_BANK_ID"] # Memory Bank scopes memories to this app name and user ID. APP_NAME = "memory_agent" USER_ID = "quickstart_user" async def generate_memories_callback( callback_context: CallbackContext, ) -> None: # Send the latest turn to Memory Bank and wait until memory generation # finishes, so that the next session can retrieve the new memory. await callback_context.add_events_to_memory( events=callback_context.session.events[-5:], custom_metadata={"wait_for_completion": True}, ) return None root_agent = adk.Agent( model="gemini-3.5-flash", name="memory_agent", instruction=( "You are a vehicle voice agent that controls in-vehicle settings. " "Use what you know about the user's preferences. " "If you don't know the user's preferred temperature, ask for it. " "Limit responses to under 30 words." ), tools=[PreloadMemoryTool()], after_agent_callback=generate_memories_callback, ) memory_service = VertexAiMemoryBankService( project=PROJECT_ID, location=LOCATION, agent_engine_id=MEMORY_BANK_ID, ) session_service = InMemorySessionService() runner = adk.Runner( agent=root_agent, app_name=APP_NAME, session_service=session_service, memory_service=memory_service, ) async def send_message(session_id: str, text: str) -> None: print(f"User: {text}") message = types.Content(role="user", parts=[types.Part(text=text)]) async for event in runner.run_async( user_id=USER_ID, session_id=session_id, new_message=message ): if event.is_final_response() and event.content: print(f"Agent: {event.content.parts[0].text}") async def main() -> None: print("--- Session 1: share a preference ---") session = await session_service.create_session( app_name=APP_NAME, user_id=USER_ID ) await send_message(session.id, "Can you fix the temperature?") await send_message(session.id, "I'm comfortable at 71 degrees.") print("--- Session 2: recall the preference ---") session = await session_service.create_session( app_name=APP_NAME, user_id=USER_ID ) await send_message(session.id, "Fix the temperature.") print("--- Memories stored in Memory Bank ---") client = agentplatform.Client(project=PROJECT_ID, location=LOCATION) memory_bank_name = ( f"projects/{PROJECT_ID}/locations/{LOCATION}" f"/reasoningEngines/{MEMORY_BANK_ID}" ) results = client.memory_banks.memories.retrieve( name=memory_bank_name, scope={"app_name": APP_NAME, "user_id": USER_ID}, ) for retrieved_memory in results.page: print(f"* {retrieved_memory.memory.fact}") if __name__ == "__main__": asyncio.run(main())מריצים את הסקריפט:
python memory_agent/agent.pyהקריאה החוזרת (callback) ממתינה לסיום תהליך יצירת הזיכרון אחרי כל תור, כדי שהזיכרון יהיה זמין כשהסשן השני יתחיל.
איך לוודא שהסוכן זוכר את הפרטים
כשהסקריפט יסתיים, הוא ידפיס את שתי השיחות ואת הזיכרון המאוחסן בטרמינל. השוו את הפלט הזה לדוגמאות הבאות כדי לוודא שהסוכן זכר את ההעדפה בסשן חדש.
בסשן הראשון, לנציג אין זיכרונות לגבי המשתמש, ולכן הוא מבקש טמפרטורה:
--- Session 1: share a preference ---
User: Can you fix the temperature?
Agent: Sure. What temperature would you like?
User: I'm comfortable at 71 degrees.
Agent: Okay, I've set the temperature to 71 degrees.
בסשן השני, הנציג מאחזר את הזיכרון מ-Memory Bank ומגדיר את הטמפרטורה ל-21 מעלות בלי לשאול. הזיכרון השמור מופיע בסוף הפלט:
--- Session 2: recall the preference ---
User: Fix the temperature.
Agent: Okay, I've set the temperature to 71 degrees, as you prefer.
--- Memories stored in Memory Bank ---
* I like the temperature to be 71 degrees.
הניסוח של התשובות והזיכרונות של הסוכן משתנה בהתאם למודלים שבהם הסוכן ו-Memory Bank משתמשים.
אופציונלי: צ'אט עם הסוכן ב-ADK Web
ADK Web הוא ממשק מבוסס-דפדפן לבדיקת נציגים במהלך הפיתוח.
באותו סשן במסוף, מריצים את הפקודה הבאה מהספרייה שמכילה את הספרייה
memory_agent:adk web --memory_service_uri=agentengine://$MEMORY_BANK_ID memory_agentפותחים את
http://localhost:8000?userId=quickstart_userבדפדפן.פרמטר השאילתה
userIdתואם למזהה המשתמש בסקריפט, כך שהנציג יכול לאחזר את הזיכרון שהסקריפט יצר.שולחים את ההודעה
Fix the temperature.ומוודאים שהנציג מגדיר את הטמפרטורה ל-71 מעלות בלי לשאול. הנציג משתמש בהעדפה שהסקריפט שמר בהפעלת נציג עם זיכרון.כדי לעצור את ADK Web, מקישים על Control+C בטרמינל.
הסרת המשאבים
כדי להימנע מחיובים בחשבון Google Cloud על המשאבים שבהם השתמשתם בדף הזה, אתם יכולים למחוק את הפרויקט ב- Google Cloud. אחרת, מוחקים את המשאבים הנפרדים:
יוצרים קובץ בשם
clean_up.pyעם הקוד הבא:import os import agentplatform project = os.environ["GOOGLE_CLOUD_PROJECT"] location = os.environ["GOOGLE_CLOUD_LOCATION"] memory_bank_id = os.environ["MEMORY_BANK_ID"] client = agentplatform.Client(project=project, location=location) client.memory_banks.delete( name=f"projects/{project}/locations/{location}/reasoningEngines/{memory_bank_id}", force=True, )מריצים את הסקריפט כדי למחוק את המכונה של Memory Bank:
python clean_up.pyמוחקים את הקבצים המקומיים שיצרתם:
rm -r memory_agent create_memory_bank.py clean_up.py
המאמרים הבאים
מדריך למתחילים: Memory Bank API
איך מתחילים להשתמש ב-Memory Bank API כדי לנהל זיכרונות לטווח ארוך.