使用 ADK 构建有状态的个性化智能体

1. 简介

title

“金鱼”问题

想象一下,您聘请了一位旅行代理来规划您的东京梦想假期。使用会话智能体,了解“金鱼问题”的实际应用。

您走进他们的办公室,说道:

“您好!我想规划一次为期 2 天的东京之旅。我对历史遗迹和寿司感兴趣。”

智能体热情地回答:

"Great! 我计划参观皇居,并在数寄屋桥次郎享用寿司晚餐。”

您微笑着说:

“听起来不错!能把行程发给我吗?”

客服人员茫然地看着您,问道:

“您好!今天需要我帮您规划行程吗?”

这就是“金鱼问题”。如果没有记忆功能,每次互动都像是一张白纸。智能性是有的,智能体知道如何规划行程,但缺乏连贯性。AI 智能体要想真正发挥作用,就必须具备记忆能力。

今日任务

在本研讨会中,您将通过构建一个能够记忆、学习和适应的旅行智能体来解决“金鱼问题”。您将逐步完成智能体内存的 6 个级别,打造一个行为更像专属个人助理而非聊天机器人的系统。

级别

概念

“超能力”

级别 1

会话和状态

对话不忘词

级别 2

多智能体状态

在团队成员之间共享备注

级别 3

持久性

即使系统重启,也能记住您

级别 4

回调

完全自主更新记忆

级别 5

自定义工具

读取和写入结构化用户个人资料

第 6 级

多模态记忆

“查看”和记住照片和视频

ADK 记忆堆栈

在编写代码之前,我们先来了解一下要使用的工具。Google 智能体开发套件 (ADK) 提供了一种结构化的记忆处理方式:

  1. 会话:对话的容器。它会保存对话的历史记录。
  2. 状态:附加到会话的键值对“暂存器”。智能体使用此存储空间来存储特定事实(例如 destination="Tokyo")。
  3. MemoryService:长期存储。这里是永久存储数据的地方,比如用户偏好设置或分析过的文档。

2. 设置

为了让 AI 智能体发挥作用,我们需要两样东西:一个 Google Cloud 项目作为基础。

第一部分:启用结算账号

如需运行此 Codelab,您需要一个有一定赠金的结算账号。使用本 Codelab 顶部横幅中的赠金即可开始。如果您已关联到结算账号,则可以跳过此步骤。

第二部分:开放环境

  1. 👉 点击此链接可直接前往 Cloud Shell Editor
  2. 👉 如果今天在任何时候系统提示您进行授权,请点击授权继续。点击即可为 Cloud Shell 授权
  3. 👉 如果终端未显示在屏幕底部,请打开它:
    • 点击查看
    • 点击终端在 Cloud Shell 编辑器中打开新终端
  4. 👉💻 在终端中,使用以下命令验证您是否已通过身份验证,以及项目是否已设置为您的项目 ID:
    gcloud auth list
    
  5. 👉💻 从 GitHub 克隆引导项目:
    git clone https://github.com/cuppibla/memory_agent_starter
    
    
  6. 👉💻 从项目目录运行设置脚本。
    cd ~/memory_agent_starter
    ./init.sh
    
    脚本会自动处理其余设置流程。
  7. 👉💻 设置所需的项目 ID:
    gcloud config set project $(cat ~/project_id.txt) --quiet
    

第三部分:设置权限

  1. 👉💻 使用以下命令启用所需的 API。这可能需要几分钟的时间。
    gcloud services enable \
        cloudresourcemanager.googleapis.com \
        servicenetworking.googleapis.com \
        run.googleapis.com \
        aiplatform.googleapis.com \
        compute.googleapis.com
    
  2. 👉💻 在终端中运行以下命令,授予必要的权限:
    . ~/memory_agent_starter/set_env.sh
    

请注意,系统会为您创建一个 .env 文件。其中会显示您的项目信息。

3. 基础 - 会话和状态

有状态

概念:背景信息至关重要

最基本的记忆形式是会话记忆。这样,智能体就能知道“我想买它”这句话中的“它”指的是您 10 秒前谈到的鞋子。

在 ADK 中,我们使用 Session 对象来管理此操作。

  • 无状态方法:为每条消息创建新会话。
  • 有状态方法:创建一个会话,并在整个对话过程中重复使用该会话。

第 1 步:检查智能体

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/01_session_agent/agent.py

打开 ~/memory_agent_starter/01_session_agent/agent.py。

👉 在 agent.py 函数中找到注释 # TODO: Create a root agent。

将整行代码替换为以下代码:

root_agent = LlmAgent(
    name="multi_day_trip_agent",
    model="gemini-2.5-flash",
    description="Agent that progressively plans a multi-day trip, remembering previous days and adapting to user feedback.",
    instruction="""
    You are the "Adaptive Trip Planner" 🗺️ - an AI assistant that builds multi-day travel itineraries step-by-step.

    Your Defining Feature:
    You have short-term memory. You MUST refer back to our conversation to understand the trip's context, what has already been planned, and the user's preferences. If the user asks for a change, you must adapt the plan while keeping the unchanged parts consistent.

    Your Mission:
    1.  **Initiate**: Start by asking for the destination, trip duration, and interests.
    2.  **Plan Progressively**: Plan ONLY ONE DAY at a time. After presenting a plan, ask for confirmation.
    3.  **Handle Feedback**: If a user dislikes a suggestion (e.g., "I don't like museums"), acknowledge their feedback, and provide a *new, alternative* suggestion for that time slot that still fits the overall theme.
    4.  **Maintain Context**: For each new day, ensure the activities are unique and build logically on the previous days. Do not suggest the same things repeatedly.
    5.  **Final Output**: Return each day's itinerary in MARKDOWN format.
    """,
    tools=[google_search]
)

指令告诉大语言模型要记住,但代码必须提供记住的能力。

第 2 步:两种场景

打开 ~/memory_agent_starter/01_session_agent/main.py。

👉 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell Editor 中打开该文件:

cloudshell edit ~/memory_agent_starter/01_session_agent/main.py

打开 ~/memory_agent_starter/01_session_agent/main.py,在 main.py 函数中找到注释 # TODO: Create a runner with in memorysession service。

将整行代码替换为以下代码:

    runner = Runner(
        agent=agent,
        session_service=session_service,
        app_name=agent.name
    )

👉 在 main.py 函数中找到注释 # TODO: create a different session to test。

将整行代码替换为以下代码:

    tokyo_session_2 = await session_service.create_session(
        app_name=multi_day_agent.name,
        user_id=user_id
    )

测试应用

我们有两个函数,分别演示了“金鱼”记忆和“大象”记忆之间的区别。

场景 1:有状态(共享会话)

async def run_trip_same_session_scenario(session_service, user_id):
    # 1. Create ONE session
    trip_session = await session_service.create_session(...)

    # 2. Turn 1
    await run_agent_query(..., trip_session, ...)

    # 3. Turn 2 - REUSING the same session!
    # The agent can "see" Turn 1 because it's in the session history.
    await run_agent_query(..., trip_session, ...)

场景 2:无状态(每次都是新会话)

async def run_trip_different_session_scenario(session_service, user_id):
    # Turn 1
    tokyo_session = await session_service.create_session(...)
    await run_agent_query(..., tokyo_session, ...)

    # Turn 2 - Creating a FREASH session
    # The agent has NO IDEA what happened in Turn 1.
    tokyo_session_2 = await session_service.create_session(...)
    await run_agent_query(..., tokyo_session_2, ...)

第 3 步:运行智能体

我们来看看实际效果有何不同。运行脚本:

👉💻 在命令行中,运行以下命令行:

cd ~/memory_agent_starter
uv run python ~/memory_agent_starter/01_session_agent/main.py

观察场景 1:智能体记住了您在第一条消息中表达的偏好,并在第二条消息中调整了方案。

观察场景 2:在第二轮对话(“你还记得我喜欢什么食物吗?”)中,智能体完全无法回答,因为这是一个新的会话。它实际上是在说:“我不知道你在说什么。”

要点总结

记忆功能规则 1:始终重复使用 session.id 以保持对话上下文。Session 对象是智能体的短期记忆缓冲区。

4. 团队 - 多智能体状态

食物

概念:“传话游戏”

当多个智能体协同工作时,它们就像同事之间来回传递文件夹一样。如果一个智能体在文件夹中写入了备注,下一个智能体应该能够读取该备注。

在 ADK 中,这个“文件夹”就是状态。

  • 状态是会话中的一个字典 ({"key": "value"})。
  • 会话中的任何智能体都可以读取或写入该会话。

第 1 步:检查工作流

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/02_multi_agent/agent.py

👉在 ~/memory_agent_starter/02_multi_agent/agent.py 文件中,找到注释 # TODO: foodie agent。

将整行代码替换为以下代码:

foodie_agent = LlmAgent(
    name="foodie_agent",
    model="gemini-2.5-flash",
    tools=[google_search],
    instruction="""You are an expert food critic. Your goal is to find the best restaurant based on a user's request.

    When you recommend a place, you must output *only* the name of the establishment and nothing else.
    For example, if the best sushi is at 'Jin Sho', you should output only: Jin Sho
    """,
    output_key="destination"  # ADK will save the agent's final response to state['destination']
)

👉 在 agent.py 函数中找到注释 # TODO: transportation agent。

将整行代码替换为以下代码:

transportation_agent = LlmAgent(
    name="transportation_agent",
    model="gemini-2.5-flash",
    tools=[google_search],
    instruction="""You are a navigation assistant. Given a destination, provide clear directions.
    The user wants to go to: {destination}.

    Analyze the user's full original query to find their starting point.
    Then, provide clear directions from that starting point to {destination}.
    """,
)

👉 在 agent.py 函数中找到注释 # TODO: root_agent。

将整行代码替换为以下代码:

root_agent = SequentialAgent(
    name="find_and_navigate_agent",
    sub_agents=[foodie_agent, transportation_agent],
    description="A workflow that first finds a location and then provides directions to it."
)

现在,我们有两个智能体按顺序工作:

  1. 美食家智能体:查找餐馆。
  2. 交通代理:提供前往该餐厅的路线。

魔力交接:请注意 foodie_agent 如何将接力棒交给 transportation_agent。

foodie_agent = LlmAgent(
    # ...
    # CRITICAL: This tells ADK to save the agent's output to state['destination']
    output_key="destination"
)

transportation_agent = LlmAgent(
    # ...
    # CRITICAL: This injects state['destination'] into the prompt
    instruction="""
    The user wants to go to: {destination}.
    Provide clear directions...
    """,
)
  1. output_key="destination":美食家智能体的回答已高效保存。
  2. {destination}:Transportation Agent 会自动读取该答案。

(无需执行任何操作)第 2 步:Orchestrator

打开 02_multi_agent/main.py。

我们使用 SequentialAgent 按顺序运行它们。

# 1. Create a single session for the sequential agent
session = await session_service.create_session(...)

# 2. Run the query
# The SequentialAgent manages the state flow:
# Query -> Foodie -> state['destination'] -> Transportation -> Final Answer
await run_agent_query(root_agent, query, ...)

用户发送一个提示:

"Find best sushi in Palo Alto and then tell me how to get there."

智能体协同工作,共同回答问题。

第 3 步:运行团队

👉💻 在 Cloud Shell 终端中,执行多智能体工作流:

cd ~/memory_agent_starter
uv run python ~/memory_agent_starter/02_multi_agent/main.py

会出现什么情况?

  1. 美食家智能体:找到“Jin Sho”(或类似餐厅)。
  2. ADK:将“Jin Sho”保存到 state['destination']。
  3. Transportation Agent:在其指令中接收“Jin Sho”。
  4. 结果:“要从 Caltrain 车站前往 Jin Sho,请沿 University Ave 步行…”

要点总结

记忆功能规则 #2:使用状态在智能体之间传递结构化信息。使用 output_key 进行写入,使用 {placeholders} 进行读取。

5. 重启 - 持久性

有状态

概念:“重启问题”

到目前为止,我们的记忆功能InMemory。如果您停止脚本并重新启动,智能体会忘记所有内容。这就像一台电脑,每次关机时都会清空硬盘。

为了解决这个问题,我们需要持久性。我们将 InMemorySessionService 替换为 DatabaseSessionService。

第 1 步:数据库切换

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/03_persistent_agent/main.py

👉 在 ~/memory_agent_starter/03_persistent_agent/main.py 文件中,找到注释 # TODO: Configuration for Persistent Sessions。

将整行代码替换为以下代码:

SESSIONS_DIR = Path(os.path.expanduser("~")) / ".adk_codelab" / "sessions"
os.makedirs(SESSIONS_DIR, exist_ok=True)
SESSION_DB_FILE = SESSIONS_DIR / "trip_planner.db"
SESSION_URL = f"sqlite:///{SESSION_DB_FILE}"

现在,每个会话和事件都会保存到 SQLite 文件中。

第 2 步:跨会话检索

持久性不仅能让对话继续,还能让智能体从过去的对话中学习。

在同一文件 ~/memory_agent_starter/03_persistent_agent/main.py 中,查看测试用例 3:跨会话检索。

👉 找到评论 # TODO: retrieve the previous session manually

将整行代码替换为以下代码:

    old_session = await session_service.get_session(
        app_name=root_agent.name, user_id="user_01", session_id=session_id
    )

👉 在 main.py 函数中找到注释 # TODO: Extract content from the OLD session。

将整行代码替换为以下代码:

                    previous_context += f"- {role}: {text}\n"

👉 在 main.py 函数中找到注释 # TODO: Manually inject the context to the query。

将整行代码替换为以下代码:

    query_3 = f"""
    {previous_context}

    I'm planning a new trip to Osaka this time. 
    Based on my previous preferences (above), what should I eat?
    """

这会模拟用户在几个月后返回。只有使用数据库,您才能检索这些旧历史记录。

第 3 步:在重启后继续运行

👉💻 在终端中运行以下脚本:

cd ~/memory_agent_starter
uv run python ~/memory_agent_starter/03_persistent_agent/main.py

它会创建一个文件 ~/memory_agent_starter/trip_planner.db。试试看:运行脚本两次。

  • 在第二次运行时,查找“Resumed existing session”(已恢复现有会话)。
  • 智能体会记住第一次运行时的上下文,因为它会从数据库文件中加载!

要点总结

记忆功能规则 3:在生产环境中使用 DatabaseSessionService。它可确保用户对话在服务器重启后仍能保留,并支持长期历史记录分析。

6. 间谍 - 回调

有状态

有时,您需要根据智能体的行为(而不仅仅是其言语)自动更新记忆。您需要一个“间谍”来观察智能体并记录笔记。

在 ADK 中,此 spy 是回调。adk_callback

  • after_tool_callback:每次代理工作时都会运行的函数。
  • ToolContext:从该函数内部写入 State 的方法。

第 1 步:逻辑架构

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/04_stateful_agent/agent.py

👉 在文件 ~/memory_agent_starter/04_stateful_agent/agent.py 中,找到注释 # TODO: Implement call back logic

将整行代码替换为以下代码:

def save_activity_type_callback(
    tool,
    args: Dict[str, Any],
    tool_context: ToolContext,
    tool_response: Dict[str, Any],
) -> Optional[Dict[str, Any]]:
    """
    Callback to save the TYPE of activity just planned into the session state.
    """
    # 1. Get the actual agent name.
    if tool.name == "transfer_to_agent":
         agent_name = args.get("agent_name")
    else:
         agent_name = tool.name

    activity_type = "unknown"

    # 2. Determine the type based on which agent was actually used
    if agent_name == "museum_expert":
        activity_type = "CULTURAL"
    elif agent_name == "restaurant_expert":
        activity_type = "FOOD"
    elif agent_name == "outdoor_expert":
        activity_type = "OUTDOOR"

    print(f"\n🔔 [CALLBACK] The planner transferred to '{agent_name}'.")

    # 3. Update the state directly
    tool_context.state["last_activity_type"] = activity_type
    print(f"💾 [STATE UPDATE] 'last_activity_type' is now set to: {activity_type}\n")

    return tool_response

👉 在同一文件中,找到 04_stateful_agent/agent.py 函数内的注释 # TODO: add callback to root agent。

将整行代码替换为以下代码:

    after_tool_callback=save_activity_type_callback,

动态指令:智能体的指令现在是一个函数,而不是一个字符串。它会根据状态而变化!

def get_planner_instruction(context):
    last_activity = context.state.get("last_activity_type", "None")
    
    return f"""
    The last activity was: {last_activity}
    
    If last_activity is 'CULTURAL' -> `museum_expert` is BANNED.
    """

第 3 步:测试 Spy

👉💻 在终端中,复制并粘贴以下命令来运行脚本:

cd ~/memory_agent_starter
uv run python ~/memory_agent_starter/04_stateful_agent/main.py

运行此智能体时,您会看到一个循环。

  1. 第 1 轮:您询问博物馆。间谍设置 last_activity="CULTURAL"。
  2. 第 2 轮:您询问另一家博物馆。
  3. 智能体指令更新:“禁止文化类内容”。
  4. 客服人员说:“我不想再逛博物馆了。去公园怎么样?”

查看 [CALLBACK] 和 [STATE UPDATE] 的控制台日志。您可以看到,随着智能体的运行,记忆会实时发生变化。

要点总结

记忆功能规则 #4:使用回调自动管理状态。智能体只需执行其工作,即可自行构建上下文。

7. 文件箱式页面 - 自定义工具

概念:“结构化记忆”

有状态

到目前为止,“记忆”功能一直采用聊天记录或简单键值对的形式。但如果您需要记住复杂的用户画像,该怎么办?例如:diet: vegan, budget: high, pets: [cat, dog]。

为此,我们将记忆功能视为一种工具。智能体明确决定何时打开文件箱式页面(读取)以及何时归档报告(写入)。自定义工具图

第 1 步:工具

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/05_profile_agent/tools.py

👉 在此文件中:~/memory_agent_starter/05_profile_agent/tools.py。

我们需要实现以下两个特定工具:

  1. save_user_preferences:写入数据库。
  2. recall_user_preferences:从数据库中读取数据。

在 ~/memory_agent_starter/05_profile_agent/tools.py 函数中找到注释 # TODO: implement save_user_preferences tools。

将整行代码替换为以下代码:

def save_user_preferences(tool_context: ToolContext, new_preferences: Dict[str, Any]) -> str:
    user_id = tool_context.session.user_id
    with sqlite3.connect(USER_DB_FILE) as conn:
        for key, value in new_preferences.items():
            conn.execute("INSERT INTO user_preferences (user_id, pref_key, pref_value) VALUES (?, ?, ?) ON CONFLICT(user_id, pref_key) DO UPDATE SET pref_value = excluded.pref_value;",
                         (user_id, key, json.dumps(value)))
    return f"Preferences updated: {list(new_preferences.keys())}"

👉 在 05/tools.py 函数中找到注释 # TODO: implement recall_user_preferences tools。

将整行代码替换为以下代码:

def recall_user_preferences(tool_context: ToolContext) -> Dict[str, Any]:
    user_id = tool_context.session.user_id
    preferences = {}
    with sqlite3.connect(USER_DB_FILE) as conn:
        rows = conn.execute("SELECT pref_key, pref_value FROM user_preferences WHERE user_id = ?", (user_id,)).fetchall()
        if not rows: return {"message": "No preferences found."}
        for key, value_str in rows: preferences[key] = json.loads(value_str)
    return preferences

该指令会强制执行以下工作流程:

instruction="""
1. RECALL FIRST: First action MUST be `recall_user_preferences`.
3. LEARN: If a user states a new preference, use `save_user_preferences`.
"""

第 2 步:执行

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/05_profile_agent/main.py

打开 ~/memory_agent_starter/05_profile_agent/main.py。

在之前的模块中,ADK 会自动处理状态,但在这里,智能体会掌控一切。

  • 它选择在开始时调用 recall_user_preferences。
  • 当您说“我是素食主义者”时,它会选择调用 save_user_preferences。

第 3 步:构建配置文件

👉💻 运行脚本:

cd ~/memory_agent_starter
uv run python ~/memory_agent_starter/05_profile_agent/main.py

尝试以下对话流程:

  1. “你好,帮我规划一顿晚餐。”-> 智能体检查数据库,未找到任何内容。询问偏好。
  2. “我是纯素食主义者。”-> 代理将“素食”保存到数据库。
  3. 重启脚本。
  4. “你好,帮我规划一顿晚餐。”-> 智能体检查数据库,看到“纯素食”,并立即推荐一家纯素食餐厅。

要点总结

记忆功能规则 #5:对于复杂的结构化数据,请为智能体提供读写工具。让 LLM 管理自己的长期存储。

8. 大脑 - 多模态记忆

有状态

概念:“人类体验”

人类记忆的内容不限于文字。我们记得照片的氛围、声音的音色、视频的感觉。

Vertex AI 记忆库可让您的智能体处理多模态记忆。它可以提取图片、视频和音频,并“理解”这些内容,以便日后检索。

第 1 步:配置

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/06_multimodal_agent/main.py

👉 打开 06_multimodal_agent/main.py。找到注释 # TODO: Configure Memory Bank Topic。

将整行代码替换为以下代码:

travel_topics = [
    MemoryTopic(
        managed_memory_topic=ManagedMemoryTopic(
            managed_topic_enum=ManagedTopicEnum.USER_PREFERENCES
        )
    ),
    MemoryTopic(
        managed_memory_topic=ManagedMemoryTopic(
            managed_topic_enum=ManagedTopicEnum.USER_PERSONAL_INFO
        )
    ),
    MemoryTopic(
        custom_memory_topic=CustomMemoryTopic(
            label="travel_experiences",
            description="""Memorable travel experiences including:
                - Places visited and impressions
                - Favorite restaurants, cafes, and food experiences
                - Preferred accommodation types and locations
                - Activities enjoyed (museums, hiking, beaches, etc.)
                - Travel companions and social preferences
                - Photos and videos from trips with location context""",
        )
    ),
    MemoryTopic(
        custom_memory_topic=CustomMemoryTopic(
            label="travel_preferences",
            description="""Travel style and preferences:
                - Budget preferences (luxury, mid-range, budget)
                - Transportation preferences (flying, trains, driving)
                - Trip duration preferences
                - Season and weather preferences
                - Cultural interests and language abilities
                - Dietary restrictions and food preferences""",
        )
    ),
    MemoryTopic(
        custom_memory_topic=CustomMemoryTopic(
            label="travel_logistics",
            description="""Practical travel information:
                - Passport and visa information
                - Frequent flyer numbers and hotel loyalty programs
                - Emergency contacts
                - Medical considerations and insurance
                - Packing preferences and essentials
                - Time zone preferences and jet lag strategies""",
        )
    ),
]

找到评论 # TODO: Configure Memory Bank Customization

将整行代码替换为以下代码:

memory_bank_config = {
    "customization_configs": [
        {
            "memory_topics": travel_topics,
        }
    ],
    "similarity_search_config": {
        "embedding_model": f"projects/{PROJECT_ID}/locations/{LOCATION}/publishers/google/models/gemini-embedding-001"
    },
    "generation_config": {
        "model": f"projects/{PROJECT_ID}/locations/{LOCATION}/publishers/google/models/gemini-2.5-flash"
    },
}

第 2 步:提取世界

在 test_trip_planner 中,我们发送:

  1. 短信(“你好”)
  2. 图片(地标)
  3. 视频(地中海)
  4. 音频片段(关于加埃塔的语音记事)

在 6_multimodal_agent/main.py 函数中找到注释 # TODO create session service and memory service。

将整行代码替换为以下代码:

session_service = VertexAiSessionService(
    project=PROJECT_ID, location=LOCATION, agent_engine_id=agent_engine_id
)
memory_service = VertexAiMemoryBankService(
    project=PROJECT_ID, location=LOCATION, agent_engine_id=agent_engine_id
)

👉 在同一文件 06_multimodal_agent/main.py 中,找到注释 # TODO: create memory from session

将整行代码替换为以下代码:

    await memory_service.add_session_to_memory(final_session_state)

这就是神奇的一行代码。它会将所有这些富媒体发送到 Vertex AI,由后者进行处理和索引。

第 3 步:检索

👉💻 在 Cloud Shell 终端中,运行以下命令,在 Cloud Shell 编辑器中打开该文件:

cloudshell edit ~/memory_agent_starter/06_multimodal_agent/agent.py

该智能体具有 PreloadMemoryTool。

tools=[PreloadMemoryTool(), budget_tool]

当新会话开始时,此工具会自动在记忆库中搜索相关的过往体验,并将其注入到上下文。

第 4 步:运行 Brain

👉💻 在 Cloud Shell 终端中运行脚本(注意:这需要一个已启用 Vertex AI 的 Google Cloud 项目):

cd ~/memory_agent_starter
uv run python ~/memory_agent_starter/06_multimodal_agent/main.py

观看最终验证步骤:

“根据我之前与你分享的图片、视频和音频…”

智能体将回复:

“你应该去加埃塔!你给我看了一段地中海的视频,还播放了一段音频,里面说你喜欢加埃塔。”

它将过去不同媒体类型的数据串联起来。

要点总结

记忆功能规则 6:使用 Vertex AI 记忆库,获得极致的记忆体验。它将文本、图片和视频整合到一个可搜索的“大脑”中。

9. 总结

您已经从“健忘的金鱼”进阶为“多模态的大象”。

您构建了

功能

Session Agent

短期对话记忆

多智能体

团队共享记忆

持久性代理

长期历史记录

有状态智能体

动态、自我更新的记忆

Profile Agent

结构化数据记忆

多模态智能体

类人感官记忆

信任建立在记忆之上。通过实现这些模式,您可以创建尊重用户时间和历史记录的代理,从而实现更深入、更有效的互动。

立即开始构建您的个性化智能体!