智能体开发套件快速入门

将智能体开发套件 (ADK) 智能体配置为使用记忆库后,该智能体会为您编排对记忆库的调用,以管理长期记忆

本教程演示了如何将记忆库与 ADK 搭配使用来管理长期记忆:

  1. 创建本地 ADK 代理和运行器

  2. 与智能体互动,动态生成可在不同会话中访问的长期记忆。

  3. 清理.

如需在不使用 ADK 编排的情况下直接调用记忆库,请参阅使用 Agent Engine SDK 快速入门。使用 Agent Engine SDK 有助于了解记忆库如何生成记忆,或检查记忆库的内容。

准备工作

如需完成本教程中演示的步骤,您必须先按照设置内存库中的步骤操作。

设置环境变量

如需使用 ADK,请设置环境变量:

import os

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

替换以下内容:

  • PROJECT_ID:您的项目 ID。
  • LOCATION:您的区域。 如需了解 Memory Bank 支持的区域,请参阅支持的区域

创建 ADK 智能体

  1. 开发 ADK 智能体时,请添加一个 Memory 工具,用于控制智能体何时检索记忆以及如何在提示中包含记忆。示例代理使用了 PreloadMemoryTool,它总会在每轮对话一开始就去获取记忆,然后把这些记忆放进系统指令里:

    from google import adk
    
    agent = adk.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=[adk.tools.preload_memory_tool.PreloadMemoryTool()]
    )
    
  2. 创建 VertexAiMemoryBankService 记忆服务,ADK 运行器会使用该服务来检索记忆。如果您使用的是 Agent Engine ADK 模板,而不是定义自己的 ADK 运行时,则此参数为可选参数。

    from google.adk.memory import VertexAiMemoryBankService
    
    agent_engine_id = agent_engine.api_resource.name.split("/")[-1]
    
    memory_service = VertexAiMemoryBankService(
        project="PROJECT_ID",
        location="LOCATION",
        agent_engine_id=agent_engine_id
    )
    

    VertexAiMemoryBankService 是 ADK 对记忆库的封装,由 ADK 的 BaseMemoryService 定义,并使用与 Agent Engine SDK 不同的接口。您可以使用 Agent Engine SDK 直接调用记忆库 APIVertexAiMemoryBankService 接口包括:

    • memory_service.add_session_to_memory,这会使用提供的 adk.Session 作为源内容触发对记忆库的 GenerateMemories 请求。对该方法的调用不受 ADK 运行程序的协调。如果您想使用 ADK 自动生成内存,需要定义自己的回调函数。

    • memory_service.search_memory,这会触发向记忆库发送 RetrieveMemories 请求,以提取当前 user_idapp_name 的相关记忆。当您为智能体提供记忆工具时,ADK 运行器会协调对该方法的调用。

  3. 创建 ADK 运行时,它负责对智能体、工具及回调的执行进行编排。ADK Runner 设置取决于您使用的部署环境:

adk.Runner

adk.Runner 通常在本地环境(例如 Colab)中使用。大多数部署选项(例如 Agent Engine 运行时)都为 ADK 提供自己的运行时。

from google.adk.sessions import VertexAiSessionService
from google.genai import types

# You can use any ADK session service.
session_service = VertexAiSessionService(
    project="PROJECT_ID",
    location="LOCATION",
    agent_engine_id=agent_engine_id
)

app_name="APP_NAME"

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

def call_agent(query, session, user_id):
  content = types.Content(role='user', parts=[types.Part(text=query)])
  events = runner.run(user_id=user_id, session_id=session, new_message=content)

  for event in events:
      if event.is_final_response():
          final_response = event.content.parts[0].text
          print("Agent Response: ", final_response)

替换以下内容:

  • APP_NAME:您的 ADK 应用的名称。

Agent Engine ADK 模板

Agent Engine ADK 模板 (AdkApp) 既可在本地使用,也可用于将 ADK 代理部署到 Agent Engine 运行时。部署在 Agent Engine 运行时上时,Agent Engine ADK 模板使用 VertexAiMemoryBankService 作为默认记忆库服务,并使用与 Agent Engine 运行时相同的 Agent Engine 实例作为记忆库。在这种情况下,您无需明确提供内存服务。

如需详细了解如何设置 Agent Engine 运行时(包括如何自定义 Memory Bank 的行为),请参阅配置 Agent Engine

使用以下代码将 ADK 代理部署到 Agent Engine 运行时:

import vertexai
from vertexai.preview.reasoning_engines import AdkApp

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

adk_app = AdkApp(agent=agent)

# Create a new Agent Engine with your agent deployed to Agent Engine Runtime.
# The Agent Engine instance will also include an empty Memory Bank.
agent_engine = client.agent_engines.create(
      agent_engine=adk_app,
      config={
            "staging_bucket": "STAGING_BUCKET",
            "requirements": ["google-cloud-aiplatform[agent_engines,adk]"]
      }
)

# Alternatively, update an existing Agent Engine to deploy your agent to Agent Engine Runtime.
# Your agent will have access to the Agent Engine instance's existing memories.
agent_engine = client.agent_engines.update(
      name=agent_engine.api_resource.name,
      agent_engine=adk_app,
      config={
            "staging_bucket": "STAGING_BUCKET",
            "requirements": ["google-cloud-aiplatform[agent_engines,adk]"]
      }
)

async def call_agent(query, session_id, user_id):
    async for event in agent_engine.async_stream_query(
        user_id=user_id,
        session_id=session_id,
        message=query,
    ):
        print(event)

替换以下内容:

  • PROJECT_ID:您的项目 ID。
  • LOCATION:您的区域。 如需了解 Memory Bank 支持的区域,请参阅支持的区域
  • AGENT_ENGINE_ID:要用于记忆库的 Agent Engine ID。例如,projects/my-project/locations/us-central1/reasoningEngines/456 中的 456
  • STAGING_BUCKET:用于暂存 Agent Engine Runtime 的 Cloud Storage 存储桶。

在本地运行时,ADK 模板使用 InMemoryMemoryService 作为默认内存服务。不过,您可以替换默认内存服务以使用 VertexAiMemoryBankService

def memory_bank_service_builder():
    return VertexAiMemoryBankService(
        project="PROJECT_ID",
        location="LOCATION",
        agent_engine_id="AGENT_ENGINE_ID"
    )

adk_app = AdkApp(
      agent=adk_agent,
      # Override the default memory service.
      memory_service_builder=memory_bank_service_builder
)

async def call_agent(query, session_id, user_id):
  # adk_app is a local agent. If you want to deploy it to Agent Engine Runtime,
  # use `client.agent_engines.create(...)` or `client.agent_engines.update(...)`
  # and call the returned Agent Engine instance instead.
  async for event in adk_app.async_stream_query(
      user_id=user_id,
      session_id=session_id,
      message=query,
  ):
      print(event)

替换以下内容:

  • PROJECT_ID:您的项目 ID。
  • LOCATION:您的区域。 如需了解 Memory Bank 支持的区域,请参阅支持的区域
  • AGENT_ENGINE_ID:要用于记忆库的 Agent Engine ID。例如,projects/my-project/locations/us-central1/reasoningEngines/456 中的 456

与您的代理互动

定义智能体并设置记忆库后,您可以与智能体互动。

  1. 创建您的第一个会话。由于在与用户的第一次会话期间没有可用的记忆,因此代理不知道任何用户偏好设置,例如用户偏好的温度:

    adk.Runner

    使用 adk.Runner 时,您可以直接调用 ADK 记忆库和会话服务。

    session = await session_service.create_session(
        app_name="APP_NAME",
        user_id="USER_ID"
    )
    
    call_agent(
        "Can you update the temperature to my preferred temperature?",
        session.id,
        "USER_ID"
    )
    
    # Agent response: "What is your preferred temperature?"
    call_agent("I like it at 71 degrees", session.id, "USER_ID")
    # Agent Response:  Setting the temperature to 71 degrees Fahrenheit.
    # Temperature successfully changed.
    

    替换以下内容:

    • APP_NAME:跑步者的应用名称。
    • USER_ID:用户的标识符。由此会话生成的记忆会以此不透明标识符为键。生成的记忆的范围存储为 {"user_id": "USER_ID"}

    Agent Engine ADK 模板

    使用 Agent Engine ADK 模板时,您可以调用 Agent Engine 运行时与记忆库和会话进行交互。

    session = await agent_engine.async_create_session(user_id="USER_ID")
    
    await call_agent(
        "Can you update the temperature to my preferred temperature?",
        session.get("id"),
        "USER_ID"
    )
    
    # Agent response: "What is your preferred temperature?"
    await call_agent("I like it at 71 degrees", session.get("id"), "USER_ID")
    # Agent Response:  Setting the temperature to 71 degrees Fahrenheit.
    # Temperature successfully changed.
    

    替换以下内容:

    • USER_ID:用户的标识符。由此会话生成的记忆会以此不透明标识符为键。生成的记忆的范围存储为 {"user_id": "USER_ID"}
  2. 为当前会话生成记忆。如果记忆库从对话中提取记忆,则这些记忆会存储在范围 {"user_id": USER_ID, "app_name": APP_NAME} 下。

    adk.Runner

    session = await session_service.get_session(
        app_name=app_name,
        user_id="USER_ID",
        session_id=session.id
    )
    memory_service.add_session_to_memory(session)
    

    Agent Engine ADK 模板

    await agent_engine.async_add_session_to_memory(session=session)
    
  3. 创建第二个会话。如果您使用了 PreloadMemoryTool,智能体会在每个对话回合开始时检索记忆,以访问用户之前向智能体表达的偏好。

    adk.Runner

    session = await session_service.create_session(
        app_name=app_name,
        user_id="USER_ID"
    )
    
    call_agent("Fix the temperature!", session.id, "USER_ID")
    # Agent Response:  Setting temperature to 71 degrees.  Is that correct?
    

    您还可以使用 memory_service.search_memory 直接检索记忆:

    await memory_service.search_memory(
        app_name="APP_NAME",
        user_id="USER_ID",
        query="Fix the temperature!",
    )
    

    Agent Engine ADK 模板

    session = await agent_engine.async_create_session(user_id="USER_ID")
    
    await call_agent("Fix the temperature!", session.get("id"), "USER_ID")
    # Agent Response:  Setting temperature to 71 degrees.  Is that correct?
    

    您还可以使用 agent_engine.async_search_memory 直接检索记忆:注意:如需使用 async_search_memory,您的 AdkApp 必须是使用 google-cloud-aiplatform 1.110.0 版或更高版本创建的。否则,您可以通过直接调用记忆库来检索记忆。

    await agent_engine.async_search_memory(
        user_id="USER_ID",
        query="Fix the temperature!",
    )
    

清理

如需清理此项目中使用的所有资源,您可以删除用于本快速入门的 Google Cloud 项目

否则,您可以按如下所示逐个删除在本教程中创建的资源:

  1. 使用以下代码示例删除 Vertex AI Agent Engine 实例,这也会删除属于该 Vertex AI Agent Engine 的所有会话或记忆。

    agent_engine.delete(force=True)
    
  2. 删除所有本地创建的文件。

后续步骤