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

1. 简介

title

“金鱼”问题

假设您聘请了一位旅行社代理来规划您的东京梦想之旅。使用 Session Agent 观看“金鱼问题”的实际效果。

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

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

代理会热情地回复:

"Great! 我计划参观皇居,并在 Sukiyabashi Jiro 享用寿司晚餐。”

您面带微笑地说:

“听起来很完美!你能把行程发给我吗?”

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

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

这就是“金鱼问题”。如果没有记忆,每次互动都是一张白纸。智能性是有的,代理知道如何规划行程,但缺少连续性。AI 代理要真正有用,就需要具备记忆能力。

您今天的任务

在此研讨会中,您将通过构建一个能够记忆、学习和适应的旅游代理来解决金鱼问题。您将逐步了解 6 个级别的代理记忆,从而创建一个行为更像专用个人助理而非聊天机器人的系统。

级别

概念

“超级功能”

级别 1

会话和状态

进行对话而不遗忘

2 级

多代理状态

在团队成员之间共享笔记

3 级

持久性

即使在系统重启后也能记住您

第 4 级

回调

完全自主地更新记忆

5 级

自定义工具

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

6 级

多模态记忆

“看到”并记住照片和视频

ADK 内存堆栈

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

  1. 会话:对话的容器。它会记录对话内容。
  2. 状态:附加到会话的键值“草稿本”。代理使用此属性来存储具体的事实(例如,destination="Tokyo")。
  3. MemoryService:长期存储。我们会在该位置永久保留用户偏好设置或分析过的文档等内容。

2. 设置

为了让 AI 代理正常运行,我们需要两样东西:一个 Google Cloud 项目来提供基础。

第 1 部分:启用结算账号

  • 您需要声明拥有 5 美元赠金的结算账号,以便进行部署。请务必使用您的 Gmail 账号。

第二部分:开放环境

  1. 👉 点击此链接可直接前往 Cloud Shell 编辑器
  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]
)

指令会告知 LLM 记住,但代码必须提供记忆功能。

第 2 步:两种方案

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

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

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}:运输代理会自动读取该答案。

(无需执行任何操作)第 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. 运输代理:在指令中收到“Jin Sho”。
  4. 结果:“如需从加州列车站前往 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试试看:运行脚本两次

  • 在第二次运行中,查找“恢复现有会话”。
  • 由于代理会从数据库文件中加载数据,因此会记住首次运行时的上下文!

核心要点

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

6. 间谍 - 回调

有状态

有时,您需要根据代理的实际操作(而不仅仅是其所说的话)自动更新内存。您需要一个“间谍”来监视代理并做笔记。

在 ADK 中,此间谍是 Callbackadk_callback

  • after_tool_callback:每次代理运行时都会运行的函数。
  • ToolContext:一种从该函数内部写入状态的方法。

第 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. 代理指令更新:“CULTURAL is BANNED”。
  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 自动处理状态的模块不同,此处的 Agent 处于控制状态。

  • 选择在开始时调用 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 步:运行大脑

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

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

观看最终验证步骤:

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

代理会回复:

“您应该去 Gaeta 看看!您向我展示了一段地中海的视频,以及一段您说自己喜欢加埃塔的音频片段。”

它将过去不同媒体类型中的点连接起来。

核心要点

记忆规则 6:使用 Vertex AI 记忆库获得出色的记忆体验。它将文字、图片和视频整合到一个可搜索的智能大脑中。

9. 总结

您已从健忘的金鱼成长为多模态大象。

您构建的

功能

会话代理

短期对话记忆

多代理

共享团队记忆

持久性代理

长期历史记录

有状态代理

动态的、可自行更新的记忆

Profile Agent

结构化数据内存

多模态代理

类人感觉记忆

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

立即开始打造您的个性化智能体!