将记忆库与 ADK 结合使用

智能体开发套件 (ADK) 通过 VertexAiMemoryBankService(ADK BaseMemoryService 接口的一种实现)将智能体连接到 Agent Platform 记忆库。本文档介绍了如何选择记忆回调和检索工具,以及如何在每个 ADK 运行时中连接记忆服务。

如需先运行完整示例,请参阅记忆库与 ADK 快速入门。

准备工作

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

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

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

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

  5. 为您的用户账号创建本地身份验证凭证:

    gcloud auth application-default login

    如果返回身份验证错误,请确认您已使用联合身份登录 gcloud CLI。

  6. 安装 ADK 和 Agent Platform SDK:
    pip install --upgrade "google-adk[gcp]" "google-cloud-agentplatform>=2.0.1"
  7. 在 Google Cloud 控制台中或使用 Agent Platform SDK 创建记忆库实例。在记忆库页面上,依次点击关联到代理 > 与 ADK 搭配使用,以获取预填充的设置代码。如果 Agent Runtime 为您创建了实例,请跳过此步骤。

所需的角色

如需获得创建 Memory Bank 实例以及生成和检索记忆所需的权限,请让管理员向您授予项目的以下 IAM 角色:

  • 创建或更新记忆库实例: Agent Platform User (`roles/aiplatform.user`)
  • 读取、写入或生成记忆: Memory Bank User (`roles/aiplatform.memoryUser`)

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

ADK 组件如何与记忆库搭配使用

ADK 智能体使用以下组件来读取和写入记忆:

组件 角色 必填
记忆库实例 存储和巩固记忆。 是
VertexAiMemoryBankService 将智能体连接到记忆库,作为 ADK 记忆服务。 是
会话服务 存储对话记录。您可以使用任何 ADK 会话服务。 是
记忆检索工具 检索代理的记忆。请参阅使用工具检索记忆。 读取记忆
记忆生成回调 在智能体做出回答后,将对话事件发送到记忆库。请参阅使用回调生成回忆。 写入记忆
ADK Runner 或 AdkApp 编排智能体、服务、工具和回调。 是

下图展示了当代理使用 PreloadMemoryTool 和记忆回调时,这些组件在每个回合中如何交互:

记忆库会将每条记忆的范围限定于运行智能体的用户 ID 和应用名称,格式为 {"user_id": USER_ID, "app_name": APP_NAME}。只有具有相同用户 ID 和应用名称的请求才能检索这些记忆。

使用回调生成记忆

记忆生成回调会将对话事件发送至记忆库。记忆库会从这些事件中提取记忆,并将其与现有记忆整合。根据您处理事件的频率选择一种方法:

方法 事件已发送 何时使用
callback_context.add_events_to_memory 您选择的一部分事件 推荐。以增量方式处理事件,例如在每个回合之后。
callback_context.add_session_to_memory 会话中的所有事件 在会话结束时调用一次,以免同一事件被处理多次。

以下示例会在每次代理回答后发送近期事件:

from google.adk.agents.callback_context import CallbackContext


async def generate_memories_callback(
    callback_context: CallbackContext,
) -> None:
    await callback_context.add_events_to_memory(
        events=callback_context.session.events[-5:]
    )
    return None

如需改为发送完整会话,请在会话结束时在回调中调用 await callback_context.add_session_to_memory()。

默认情况下,VertexAiMemoryBankService 使用事件提取发送事件。如需在测试或演示中等待记忆生成完成,请将 custom_metadata={"wait_for_completion": True} 传递给 add_events_to_memory。

使用工具检索记忆

记忆检索工具可控制智能体何时检索记忆以及记忆如何进入提示。选择以下工具之一:

工具 检索记忆的时间 何时使用
PreloadMemoryTool 在每个回合开始时。记忆会在当前用户回合之前注入到模型请求上下文中。 在每个回合中建立有关用户的基准上下文。
LoadMemoryTool 当模型认为需要使用记忆功能来回答查询时。 让模型决定何时相关。
自定义 FunctionTool 模型何时调用您的工具,由工具的说明引导。 向智能体发出指令,告知其何时检索记忆。

以下示例创建了一个使用 PreloadMemoryTool 和上一部分中的回调的代理:

from google import adk
from google.adk.tools.preload_memory_tool import PreloadMemoryTool

agent = adk.Agent(
    model="gemini-3.5-flash",
    name="stateful_agent",
    instruction="You are a vehicle voice agent. Limit responses to 30 words.",
    tools=[PreloadMemoryTool()],
    after_agent_callback=generate_memories_callback,
)

如需让模型决定何时检索记忆,请从 google.adk.tools.load_memory_tool 导入 LoadMemoryTool,并在 tools 中传递 LoadMemoryTool()。

如需编写自定义检索工具,请从函数工具调用 tool_context.search_memory:

from typing import Any

from google import adk
from google.adk.tools import FunctionTool, ToolContext


async def search_memories(query: str, tool_context: ToolContext) -> Any:
    """Query this tool when you need information about user preferences."""
    return await tool_context.search_memory(query)


agent = adk.Agent(
    model="gemini-3.5-flash",
    name="stateful_agent",
    instruction=(
        "You are a vehicle voice agent. Before you change a setting, call "
        "search_memories to look up the user's preferences. Limit responses "
        "to 30 words."
    ),
    tools=[FunctionTool(func=search_memories)],
    after_agent_callback=generate_memories_callback,
)

将记忆服务连接到运行时

如何连接 VertexAiMemoryBankService 取决于代理的运行位置。选择运行时:

本地运行器

使用 adk.Runner 运行智能体时,请创建记忆服务并将其传递给运行器:

import asyncio
import os

from google import adk
from google.adk.memory import VertexAiMemoryBankService
from google.adk.sessions import InMemorySessionService
from google.genai import types

os.environ["GOOGLE_GENAI_USE_ENTERPRISE"] = "TRUE"
os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
os.environ["GOOGLE_CLOUD_LOCATION"] = "LOCATION"

memory_service = VertexAiMemoryBankService(
    project="PROJECT_ID",
    location="LOCATION",
    agent_engine_id="MEMORY_BANK_ID",
)

# You can use any ADK session service. This example keeps sessions in memory.
# To persist conversation history, use VertexAiSessionService with a
# Sessions instance instead.
session_service = InMemorySessionService()

runner = adk.Runner(
    agent=agent,
    app_name="APP_NAME",
    session_service=session_service,
    memory_service=memory_service,
)

async def main() -> None:
    session = await session_service.create_session(
        app_name="APP_NAME",
        user_id="USER_ID",
    )
    message = types.Content(
        role="user", parts=[types.Part(text="Can you fix the temperature?")]
    )
    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(event.content.parts[0].text)

asyncio.run(main())

替换以下内容:

  • PROJECT_ID:您的 Google Cloud 项目 ID,例如 my-project。
  • LOCATION:您的位置,例如 global。请参阅记忆库的支持的位置以及全球和多区域端点。
  • MEMORY_BANK_ID:记忆库实例 ID,例如 projects/my-project/locations/us-central1/reasoningEngines/456 中的 456。
  • APP_NAME:ADK 应用名称,例如 my_agent。记忆库会将应用名称纳入记忆范围,从而在不同应用之间隔离记忆。
  • USER_ID:用户的标识符,例如 user-123。 此会话生成的记忆限定于此标识符。

Gemini Enterprise Agent Platform 上的 Agent Runtime

使用 ADK 模板 (AdkApp) 将 ADK 智能体部署到 Agent Runtime 时,该模板默认使用 VertexAiMemoryBankService。您可以一步创建记忆库实例并部署代理:

import asyncio

import agentplatform
from agentplatform.frameworks import AdkApp

client = agentplatform.Client(
    project="PROJECT_ID",
    location="LOCATION",
)

adk_app = AdkApp(agent=agent)

# Create a resource with your agent deployed to Agent Runtime. The
# resource also includes an empty Memory Bank instance.
runtime_instance = client.runtimes.create(
    agent=adk_app,
    config={
        "staging_bucket": "STAGING_BUCKET",
        "requirements": ["google-cloud-agentplatform[runtimes,adk]"],
    },
)

async def main() -> None:
    session = await runtime_instance.async_create_session(
        user_id="USER_ID"
    )
    async for event in runtime_instance.async_stream_query(
        user_id="USER_ID",
        session_id=session.get("id"),
        message="Can you fix the temperature?",
    ):
        print(event)

asyncio.run(main())

如需将智能体部署到现有资源并保留该资源的现有记忆,请改为调用 client.runtimes.update:

runtime_instance = client.runtimes.update(
    name="RUNTIME_NAME",
    agent=adk_app,
    config={
        "staging_bucket": "STAGING_BUCKET",
        "requirements": ["google-cloud-agentplatform[runtimes,adk]"],
    },
)

在本地运行 AdkApp 时,它默认使用 InMemoryMemoryService。如需在本地使用记忆库,请替换记忆服务:

from google.adk.memory import VertexAiMemoryBankService

def memory_bank_service_builder() -> VertexAiMemoryBankService:
    return VertexAiMemoryBankService(
        project="PROJECT_ID",
        location="LOCATION",
        agent_engine_id="MEMORY_BANK_ID",
    )

adk_app = AdkApp(
    agent=agent,
    memory_service_builder=memory_bank_service_builder,
)

替换以下内容:

  • PROJECT_ID:您的 Google Cloud 项目 ID,例如 my-project。
  • LOCATION:Agent Runtime 区域或多区域,例如 us-central1。只有独立 VertexAiMemoryBankService 实例支持 global,client.runtimes.create 不支持。请参阅支持的位置。
  • STAGING_BUCKET:用于暂存 Agent Runtime 的 Cloud Storage 存储桶 URI,例如 gs://my-staging-bucket。
  • USER_ID:用户的标识符,例如 user-123。
  • RUNTIME_NAME:现有 Agent Runtime 的资源名称,格式为 projects/.../locations/.../reasoningEngines/...。
  • MEMORY_BANK_ID:记忆库实例 ID,例如 projects/my-project/locations/us-central1/reasoningEngines/456 中的 456。

Cloud Run

如需将智能体部署到 Cloud Run,请按照 ADK 文档中的说明操作,并将记忆库实例作为记忆服务传递:

adk deploy cloud_run \
    ...
    --memory_service_uri=agentengine://MEMORY_BANK_ID

将 MEMORY_BANK_ID 替换为您的 Memory Bank 实例 ID,例如 456。如需测试已部署的智能体,请参阅 ADK Cloud Run 部署文档。

Google Kubernetes Engine (GKE)

如需将智能体部署到 GKE,请按照 ADK 文档中的说明操作,并将记忆库实例作为记忆服务传递:

adk deploy gke \
    ...
    --memory_service_uri=agentengine://MEMORY_BANK_ID

将 MEMORY_BANK_ID 替换为您的 Memory Bank 实例 ID,例如 456。如需测试已部署的智能体,请参阅 ADK GKE 部署文档的测试智能体部分。

ADK Web

ADK Web 是一个本地浏览器界面,用于在开发期间测试和检查智能体。

ADK Web 会从环境变量中读取您的项目和位置信息。在终端中,从包含代理文件夹的目录运行以下命令:

export GOOGLE_GENAI_USE_ENTERPRISE=TRUE
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
export GOOGLE_CLOUD_LOCATION=LOCATION
adk web --memory_service_uri=agentengine://MEMORY_BANK_ID

替换以下内容:

  • PROJECT_ID:您的 Google Cloud 项目 ID,例如 my-project。
  • LOCATION:您的位置,例如 global。请参阅记忆库的支持的位置以及全球和多区域端点。
  • MEMORY_BANK_ID:记忆库实例 ID,例如 456。

然后在浏览器中打开 http://localhost:8000。默认情况下,ADK Web 会将用户 ID 设置为 user。如需使用其他用户 ID,请添加 userId 查询参数,例如 http://localhost:8000?userId=USER_ID。

将多区域记忆库与区域级运行时搭配使用

默认情况下,当您将 Runtime 与内置记忆库搭配使用时,您的智能体和记忆库会部署在同一区域。如需在区域级部署中维护一个中央记忆库,您可以将多区域记忆库(例如 us)与区域级运行时(例如 us-central1)配对。

如需使用多区域记忆库,请替换默认的 ADK 记忆服务构建器,使其指向多区域位置和实例 ID:

import agentplatform
from agentplatform.frameworks import AdkApp
from google.adk.memory import VertexAiMemoryBankService

# Create the Memory Bank instance in a multi-region location.
client_mb = agentplatform.Client(
    project="PROJECT_ID",
    location="us",
)
memory_bank = client_mb.memory_banks.create()
memory_bank_id = memory_bank.name.split("/")[-1]


# Point the memory service to the multi-regional instance.
def memory_bank_service_builder() -> VertexAiMemoryBankService:
    return VertexAiMemoryBankService(
        project="PROJECT_ID",
        location="us",
        agent_engine_id=memory_bank_id,
    )


adk_app = AdkApp(
    agent=agent,
    memory_service_builder=memory_bank_service_builder,
)

# Deploy the runtime to a specific region.
client_runtime = agentplatform.Client(
    project="PROJECT_ID",
    location="us-central1",
)
runtime_instance = client_runtime.runtimes.create(
    agent=adk_app,
    config={
        "staging_bucket": "STAGING_BUCKET",
        "requirements": ["google-cloud-agentplatform[runtimes,adk]"],
    },
)

替换以下内容:

  • PROJECT_ID:您的 Google Cloud 项目 ID,例如 my-project。
  • STAGING_BUCKET:用于暂存 Agent Runtime 的 Cloud Storage 存储桶 URI,例如 gs://my-staging-bucket。

如需删除这些资源,请删除运行时和多区域实例。 如果你在对话结束后立即删除实例,则在记忆生成完成时,请求可能会失败并显示 FAILED_PRECONDITION 错误。如果发生这种情况,请稍等片刻,然后再次运行删除操作。

client_runtime.runtimes.delete(
    name=runtime_instance.api_resource.name,
    force=True,
)
client_mb.memory_banks.delete(name=memory_bank.name, force=True)

后续步骤

快速入门

构建一个可回忆用户偏好设置的 ADK 智能体。

指南

了解如何在记忆库中生成记忆。

指南

了解如何设置记忆库。