快速入門導覽課程:使用 Memory Bank 為 ADK 代理新增長期記憶

Agent Platform Memory Bank 可讓您使用 Agent Development Kit (ADK) 建構的代理,在不同工作階段中擁有長期記憶。在本快速入門導覽課程中,您將執行一個代理,在一個工作階段中學習使用者的偏好溫度,並在下一個工作階段中回想該偏好設定。

本快速入門導覽課程會引導您完成下列步驟:

  • 設定環境。
  • 建立 Memory Bank 執行個體。
  • 在本機執行具備記憶功能的 ADK 代理。
  • 確認代理在新工作階段中記住偏好設定。

如要直接呼叫 Memory Bank,而不使用 ADK,請參閱 Memory Bank API 快速入門導覽課程。如要選擇其他記憶體工具、回呼或執行階段,請參閱「搭配使用 Memory Bank 與 ADK」。

事前準備

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. 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.

  4. Verify that billing is enabled for your Google Cloud project.

  5. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. 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.

    Enable the API

  6. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  7. 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.

  8. Verify that billing is enabled for your Google Cloud project.

  9. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. 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.

    Enable the API

  10. 設定 Python 開發環境。
  11. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

    gcloud auth application-default login

    如果您使用的是 Cloud Shell,則不必執行這項操作。

    如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

必要的角色

如要取得建立 Memory Bank 執行個體、生成及擷取記憶所需的權限,請要求管理員授予您專案的下列 IAM 角色:

  • 建立或更新 Memory Bank 執行個體:Agent Platform 使用者 (`roles/aiplatform.user`)
  • 讀取、寫入或生成記憶:Memory Bank 使用者 (`roles/aiplatform.memoryUser`)

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

設定環境

  1. 在終端機安裝 ADK 和 Agent Platform SDK:

    pip install --upgrade "google-adk[gcp]" "google-cloud-agentplatform>=2.0.1"
  2. 設定本快速入門導覽課程中指令碼讀取的環境變數:

    export GOOGLE_GENAI_USE_ENTERPRISE=TRUE
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
    export GOOGLE_CLOUD_LOCATION=global

    將 PROJECT_ID 替換為 Google Cloud 專案 ID。

    本快速入門導覽課程會使用全域端點。如要改用區域性或多區域位置,請將 global 替換為其中一個支援的位置。如需客戶自行管理的加密金鑰 (CMEK),請使用區域性或多區域位置,因為全域端點不支援 CMEK。

    在同一個終端機工作階段和目錄中執行本快速入門導覽課程的其餘部分,讓指令碼可以讀取這些變數。

建立記憶庫執行個體

  1. 建立名為 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])
    
  2. 執行指令碼,並將執行個體 ID 儲存在 MEMORY_BANK_ID 環境變數中:

    export MEMORY_BANK_ID=$(python create_memory_bank.py)

    如果這是您第一個記憶庫執行個體,建立作業可能需要 1 到 2 分鐘。

  3. 確認變數包含執行個體 ID:

    echo $MEMORY_BANK_ID

    輸出內容會是 ID,例如 1234567890。如果輸出內容空白,或傳回 401 或 403 錯誤,請檢查必要角色,並執行 gcloud auth application-default login。如果新的 global 執行個體在首次使用時傳回暫時性 403 錯誤,請等待 30 秒,然後再次執行指令碼。

執行具備記憶功能的代理

本節中的指令碼會為同一位使用者執行兩個工作階段。在第一個工作階段中,使用者會說明溫度偏好設定。在第二個工作階段中,代理會從 Memory Bank 叫出該偏好設定。

操作步驟如下:

  1. 建立名為 memory_agent 的目錄:

    mkdir memory_agent
  2. 建立名為 memory_agent/agent.py 的檔案,並加入下列程式碼。程式碼會從您在「設定環境」和「建立 Memory Bank 執行個體」中設定的變數,讀取專案、位置和執行個體 ID。您不需要編輯程式碼。

    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())
    
  3. 執行指令碼:

    python memory_agent/agent.py

    回呼會在每輪對話後等待記憶生成完成,因此第二個工作階段開始時,記憶即可使用。

確認代理是否記得

指令碼執行完畢後,會將對話和儲存的記憶體列印到終端機。將輸出內容與下列範例比較,確認代理在新工作階段中記住偏好設定。

在第一個工作階段中,代理沒有使用者的任何記憶,因此會詢問溫度:

--- 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 擷取記憶,並直接將溫度設為 71 度,儲存的記憶會顯示在輸出內容結尾:

--- 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.

代理回覆和記憶的用詞會因代理和記憶庫使用的模型而異。

選用:在 ADK Web 與代理對話

ADK Web 是瀏覽器介面,可在開發期間測試代理。

  1. 在同一個終端機工作階段中,從包含 memory_agent 目錄的目錄執行下列指令:

    adk web --memory_service_uri=agentengine://$MEMORY_BANK_ID memory_agent
  2. 在瀏覽器中開啟 http://localhost:8000?userId=quickstart_user。

    userId 查詢參數與指令碼中的使用者 ID 相符,因此代理可以擷取指令碼建立的記憶。

  3. 傳送訊息 Fix the temperature.,並確認代理會直接將溫度設為 71 度,不會詢問。代理會使用指令碼儲存在「執行具備記憶功能的代理」中的偏好設定。

  4. 如要停止 ADK Web,請在終端機按下 Control+C。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本頁面所用資源的費用,請刪除 Google Cloud專案。如果不是,請刪除個別資源:

  1. 建立名為 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,
    )
    
  2. 執行指令碼,刪除 Memory Bank 執行個體:

    python clean_up.py
  3. 刪除您建立的本機檔案:

    rm -r memory_agent create_memory_bank.py clean_up.py

後續步驟

快速入門導覽課程

開始使用 Memory Bank API 管理長期記憶。

指南

選擇 ADK 的回呼、工具和執行階段。

指南

瞭解如何在記憶庫中生成記憶。

指南

瞭解如何設定 Memory Bank。