使用 Google ADK 和 AP2 构建值得信赖的公益智能体

1. 建立信任,激发善举

横幅

灵感瞬间

您的手机振动。您看到一则新闻报道,内容是关于一个成功的扫盲项目,该项目帮助资源匮乏社区的儿童学习阅读。您感到一种强烈的贡献冲动。您打开浏览器,搜索“儿童扫盲计划捐款”。

google 搜索

系统会显示数百条结果。

您点击了第一个链接。网站看起来很专业。您向下滚动到其财务信息。“管理费用:28%。”你停了下来。您捐赠的每一美元中,只有 72 美分会实际用于该计划。这样可以吗?您不确定。

您尝试了另一家组织。您从未听说过这些公司。这些请求是否合法?快速搜索后,您会发现自己陷入了信息海洋。您发现了一个两年前的 Reddit 帖子,其中一位用户声称:“这是个骗局,我的捐款根本没到账。”另一位则极力为他们辩护:“他们是在实地做实事!”这种不确定性让人感到无所适从。

30 分钟后,您深陷于各种相互矛盾的评价、效率评级和 IRS 记录中,却仍然没有捐款。最初的慷慨之举已被研究的摩擦所取代。这个标签页会保持打开状态几天,提醒您有这个好意图,直到您最终将其关闭。

这不是个人失败,而是系统失败

这种体验是普遍存在的。人们的捐赠意愿很强烈,但捐赠过程却充满障碍,让人犹豫不决、心生疑虑:

  • ❌ 研究阻力:每个慈善机构都需要单独调查。
  • ❌ 信任验证:很难区分高效组织与低效组织,甚至无法识别纯粹的欺诈行为。
  • ❌ 分析瘫痪:选项过多会导致决策疲劳。
  • ❌ 动力丧失:随着物流负担的增加,捐赠的情感动力逐渐减弱。

这种摩擦会带来惊人的实际成本。根据 Giving USA 2024 的数据,美国个人捐赠规模巨大,仅 2023 年,个人捐赠者就捐赠了约 3, 740 亿美元。然而,研究表明,捐赠障碍(包括搜索成本、心理阻力和时间限制)会显著减少慈善事业获得的捐赠金额。涉及数百万捐赠者的研究发现,在线捐赠过程中即使存在微小的阻碍,也会妨碍人们实现其慈善意愿。

这意味着,有数十亿美元的捐款未能送达需要这些资金的公益事业。

愿景

想象一下不同的体验。无需进行 30 分钟的研究,只需说:

“我想向儿童扫盲计划捐赠 50 美元。帮我找一家评分高、效率高且经过验证的慈善机构。”

几秒钟后,您就会收到一个令人安心的回答:

慈善结果卡片

这就是 AI 捐赠智能体的愿景。但要实现这一愿景,我们必须解决一个根本性挑战:当自主 AI 智能体处理资金时,信任不是可选项,而是整个基础。

  • 我们如何证明用户授权了什么?
  • 如果出现错误,谁来负责?
  • 我们如何让捐赠人、慈善机构和支付网络有信心参与其中?

今日任务

在本研讨会中,您将结合使用以下两项强大的技术来构建该可靠智能体:

Google 智能体开发套件 (ADK)

Agent Payments Protocol (AP2)

角色

用于构建生产级 AI 智能体的工厂

架构蓝图:打造值得信赖的 AI 交易

提供的内容

• 多智能体编排框架
• 内置安全功能(例如工具确认)
• 可用于生产用途的可观测性和跟踪功能
• 简单的 Python 界面,可实现复杂的智能体行为

• 基于角色的安全边界
• 可验证的数字凭证(授权)
• 同意的加密证明
• 完整的审核跟踪记录,确保问责制

了解详情

ADK 文档

AP2 协议

构建内容

架构

完成本研讨会后,您将创建:

✅ 多智能体系统,其中包含具有专门角色的智能体:

  • 一个可查找经过验证的慈善机构的导购智能体
  • 创建具有约束力的捐赠优惠的商家代理
  • 安全处理付款的凭证提供方
  • 协调整个流程的编排器

✅ 三种类型的可验证凭证:

  • IntentMandate:“帮我找一家教育慈善机构”
  • CartMandate:“向 Room to Read 捐赠 50 美元,由商家签名”
  • PaymentMandate:“通过模拟付款进行处理”

✅ 层层守护,安全无忧:

  • 基于角色的信任边界
  • 明确的用户同意

✅ 完整的审核跟踪记录:

  • 每个决策都可追溯
  • 记录的每项同意声明
  • 每次转接都清晰可见

🔒 重要提示:这是一个安全的学习环境

准备好建立信任了吗?

在下一个单元中,我们将设置开发环境并构建您的首个 AI 智能体。您很快就会发现为什么简单的智能体不可靠,然后在研讨会的其余部分学习如何解决这个问题。

我们首先来了解一下问题。

2. 准备工作区

值得信赖的智能体的基础

在构建 AI Giving Agent 之前,我们需要准备一个干净、一致且配置正确的开发环境。本单元是一个重点步骤,旨在确保所有必要的工具和服务都已准备就绪。

成功完成此设置后,您就可以完全专注于在后续模块中构建智能体逻辑这一令人兴奋的工作,而无需担心配置问题。

访问 Cloud Shell

首先,我们将打开 Cloud Shell,这是一个基于浏览器的终端,预装了 Google Cloud SDK 和其他基本工具。

点击 Google Cloud 控制台顶部的激活 Cloud Shell(右上角导航栏中的终端图标)。

Cloud Shell

查找 Google Cloud 项目 ID:

  • 打开 Google Cloud 控制台:https://console.cloud.google.com
  • 从页面顶部的项目下拉菜单中,选择您要在此研讨会中使用的项目。
  • 项目 ID 会显示在信息中心的“项目信息”卡片上 项目 ID

Cloud Shell 打开后,验证您是否已通过身份验证:

# Check that you are logged in
gcloud auth list

您应该会看到自己的账号列为 (ACTIVE)。

配置项目

现在,我们来设置 Google Cloud 项目并启用必要的 API。

设置项目 ID

# Set your project using the auto-detected environment variable in Cloud Shell
gcloud config set project $GOOGLE_CLOUD_PROJECT

# Verify the project has been set
echo "Your active Google Cloud project is: $(gcloud config get-value project)"

启用必需的 API

您的代理需要访问多项 Google Cloud 服务:

gcloud services enable \
    aiplatform.googleapis.com \
    secretmanager.googleapis.com \
    cloudtrace.googleapis.com

此过程可能需要 1-2 分钟。您会看到:

Operation "operations/..." finished successfully.

这些 API 的功能:

  • aiplatform.googleapis.com:访问 Gemini 模型,以便智能体进行推理
  • secretmanager.googleapis.com:安全存储 API 密钥(生产环境最佳实践)
  • cloudtrace.googleapis.com:为我们的问责跟踪提供可观测性

克隆起始代码

获取包含所有模板代码和资源的研讨会代码库:

git clone https://github.com/ayoisio/adk-ap2-charity-agents
cd adk-ap2-charity-agents
git checkout codelab

我们来验证一下:

ls -la

您应该会看到:

  • charity_advisor/ - 我们将在此处构建智能体和工具
  • scripts/ - 用于测试和验证的辅助脚本
  • deploy.sh - 部署辅助脚本
  • setup.py - 用于模块安装的辅助脚本
  • .env.template - 环境变量文件

设置 Python 环境

现在,我们将为项目创建一个隔离的 Python 环境。

创建并激活虚拟环境

# Create the virtual environment
python3 -m venv venv

# Activate it
source venv/bin/activate

✅ 验证:您的提示现在应该会显示 (venv) 前缀。

安装依赖项

pip install -r charity_advisor/requirements.txt
pip install -e .

此命令会安装:

  • google-adk:智能体开发套件框架
  • google-cloud-aiplatform:Vertex AI 和 Gemini 集成
  • ap2:Agent Payments Protocol SDK(来自 GitHub)
  • python-dotenv:环境变量管理

借助 -e 标志,您可以从任何位置导入 adk_ap2_charity_agents 模块。

配置环境文件

根据模板创建配置:

# Copy the template
cp .env.template .env

# Get your current Project ID
PROJECT_ID=$(gcloud config get-value project)

# Replace the placeholder with your actual project ID
sed -i "s/your-project-id/$PROJECT_ID/g" .env

# Verify the replacement worked
grep GOOGLE_CLOUD_PROJECT .env

您应该会看到:

GOOGLE_CLOUD_PROJECT=your-actual-project-id

验证

运行验证脚本,确保所有配置都正确无误:

python scripts/verify_setup.py

您应该会看到所有绿色对勾标记:

======================================================================
SETUP VERIFICATION
======================================================================

✓ Python version: 3.11.x
✓ google-adk: 1.17.0
✓ google-cloud-aiplatform: 1.111.0+
✓ ap2: 0.1.0
✓ python-dotenv: 1.0.0+
✓ .env file found and contains project ID
✓ Google Cloud project configured: your-project-id

✓ Mock charity database found
✓ Agent templates ready
✓ All directories present

======================================================================
✓ Setup complete! You are ready to build trustworthy agents.
======================================================================

问题排查

后续步骤

您的环境现已准备就绪!您已完成以下操作:

  • ✅ Google Cloud 项目已配置
  • ✅ 已启用必需的 API
  • ✅ 已安装 ADK 和 AP2 库
  • ✅ 模板代码已准备好,可供修改

在下一个单元中,您将使用几行代码构建您的首个 AI 智能体,并了解为什么简单的智能体在处理金融交易时不可靠。

3. 您的第一个智能体和发现信任差距

横幅

从创意到互动

在上一单元中,我们准备了开发环境。现在,激动人心的工作开始了。我们将构建并运行我们的第一个智能体,赋予它第一个功能,并在此过程中发现我们必须解决的根本挑战,才能使其真正值得信赖。

本单元是您的“之前”画面,揭示了为什么构建值得信赖的智能体不仅仅是让 LLM 能够访问工具。

第 1 步:检查 Starter Agent

首先,我们来看看第一个智能体的模板。它包含一个基本结构和一些占位符,我们将在后续步骤中完成这些占位符。

👉 打开文件

charity_advisor/simple_agent/agent.py

。

您会看到:

"""
A simple agent that can research charities using Google Search.
"""

# MODULE_3_STEP_2_IMPORT_COMPONENTS


simple_agent = Agent(
    name="SimpleAgent",
    model="gemini-2.5-flash",
    
    # MODULE_3_STEP_3_WRITE_INSTRUCTION
    instruction="""""",
    
    # MODULE_3_STEP_4_ADD_TOOLS
    tools=[]
)

请注意,占位注释遵循以下模式:MODULE_3_STEP_X_DESCRIPTION。我们将替换这些标记,以便逐步构建智能体。

第 2 步:导入所需组件

在实例化 Agent 类或使用 google_search 工具之前,我们需要将它们导入到文件中。

👉 查找:

# MODULE_3_STEP_2_IMPORT_COMPONENTS

👉 将该行替换为:

from google.adk.agents import Agent
from google.adk.tools import google_search

现在,Agent 类和 google_search 工具已在我们的文件中可用。

第 3 步:编写智能体指令

指令是智能体的“工作说明”,它会告诉 LLM 何时以及如何使用其工具。我们来编写一个提示,引导代理搜索慈善机构信息。

👉 查找:

# MODULE_3_STEP_3_WRITE_INSTRUCTION
instruction="""""",

👉 将这两行代码替换为:

instruction="""You are a helpful research assistant. When a user asks you to find information about charities,
use the google_search tool to find the most relevant and up-to-date results from the web.
Synthesize the search results into a helpful summary.""",

第 4 步:添加搜索工具

没有工具的智能体只是一个对话者。我们先为智能体添加第一个功能:网络搜索。

👉 查找:

# MODULE_3_STEP_4_ADD_TOOLS
tools=[]

👉 将这两行代码替换为:

tools=[google_search]

第 5 步:验证完整的智能体

在测试之前,我们先确认所有部分都已就绪。

👉 您的完整

charity_advisor/simple_agent/agent.py

文件现在应如下所示:

"""
A simple agent that can research charities using Google Search.
"""

from google.adk.agents import Agent
from google.adk.tools import google_search


simple_agent = Agent(
    name="SimpleAgent",
    model="gemini-2.5-flash",
    instruction="""You are a helpful research assistant. When a user asks you to find information about charities,
use the google_search tool to find the most relevant and up-to-date results from the web.
Synthesize the search results into a helpful summary.""",
    tools=[google_search]
)

第 6 步:测试智能体 - 暴露信任差距

现在,我们的智能体已配置完毕,接下来我们来测试一下,并分析其行为。在这里,我们将探讨为什么简单的智能体在处理财务决策时不可靠。

测试 1:发现问题

👉 在 Cloud Shell 终端中,运行以下命令:

adk run charity_advisor/simple_agent

您应该会看到如下所示的输出:

INFO:google.adk.agents:Loading agent from charity_advisor/simple_agent
INFO:google.adk.agents:Agent 'SimpleAgent' ready

[user]:

[user]: 提示现在正在等待您输入。

👉 在 [user]: 提示符处,输入:

Can you find me a verified, highly-rated charity for children's literacy?

👉 按 Enter 键,然后观察回答。

片刻之后,智能体会将搜索结果整合为如下回答:

根据网页搜索结果,Reading Is Fundamental 和 Room to Read 似乎是两家备受好评的儿童识字慈善机构。通常建议通过 Charity Navigator 和 GuideStar 等来源验证其状态和评级。我还发现了一些在线讨论,包括在 Reddit 等论坛上,用户分享了他们参与各种规模较小的本地扫盲计划的个人经历。

我们来分析一下。客服人员是否解决了我们的问题?

❌ 不正确。它完美地复制了我们在第 1 单元中描述的人类体验。它成功地将“Google 一下”的过程自动化,并将“分析瘫痪”问题直接抛回给我们。

这暴露了第一个信任缺口:缺乏权威数据。

智能体正在搜索开放网络,这意味着:

  • ✅ 快速找到结果(提升用户体验)
  • ❌ 它将评价较高的组织与 Reddit 讨论(不可靠来源)混为一谈
  • ❌ 无法区分经过审核的慈善机构和潜在的欺诈行为(未经验证)
  • ❌ 它要求我们验证它刚刚提供的信息(将负担转嫁回来)

测试 2:执行问题

现在进入关键的第二项测试。在 [user]: 提示符处,尝试完成捐款:

Okay, please donate $50 to Room to Read for me.

智能体会回复道歉,承认其局限性:

我们了解到,您想捐款,这太棒了!不过,我是一名研究助理,无法处理金融交易或付款。如需捐款,您需要直接访问 Room to Read 的官方网站。

这是第二个同样重要的“顿悟”时刻。

不仅无法信任智能体能找到合适的慈善机构,也无法信任它能执行捐赠操作。

👉 按

Ctrl+C

,在测试完成后退出。

两个差距的可视化

信任问题

要点回顾

在本单元中,您成功构建并装备了您的第一个 AI 智能体。在此过程中,您发现了构建可信系统的两个基本挑战。

掌握的关键概念

✅ 智能体类:

  • ADK 的核心组成部分
  • 将 LLM 推理(大脑)与工具(双手)相结合
  • 配置了模型、指令和工具

✅ 基于文件夹的结构:

  • 每个智能体都位于自己的文件夹中
  • ADK 会查找 agent_folder/agent.py
  • 使用 adk run agent_folder 运行

✅ 工具列表:

  • 定义智能体功能
  • LLM 决定何时以及如何使用工具
  • 可包含多个工具,用于执行不同的操作

✅ 指令提示:

  • 像职位说明一样引导智能体行为
  • 指定角色、触发器、操作和输出格式
  • 对可靠的工具使用至关重要

✅ 信任问题:

  • 发现差距:来源未经审核,质量参差不齐
  • 执行差距:缺乏安全功能、未征得用户同意、没有审核跟踪记录

后续步骤

在下一个单元中,我们将开始通过实现 AP2 的基于角色的架构来构建解决方案。

我们来构建第一个智能体,看看角色分离的实际效果。

4. 构建导购智能体 - 基于角色的发现

横幅

信任的基础:角色分离

在上一单元中,您了解到简单的通用代理在两个方面存在不足:无法提供可靠的发现功能,也无法执行安全的交易。现在,我们将开始解决这些问题,首先实现 Agent Payments Protocol 中的第一个原则:基于角色的架构。

在编写任何代码之前,我们先来了解一下为什么这一原则如此重要。

AP2 原则:角色分离

“万能”智能体的问题

假设您聘请了一个人来担任您的财务顾问、会计师和投资经纪人。方便吗?可以。安全?绝对不用。他们将拥有:

  • 您的投资目标(顾问角色)
  • 访问您的账号(会计角色)
  • 有权转移您的资金(经纪人角色)

如果此人遭到入侵或犯错,所有内容都会面临风险。

AP2 的解决方案:一个智能体,一项任务

AP2 采用关注点分离原则来创建信任边界:

架构

重要意义:

  • ✅ 有限的爆炸半径:如果导购智能体遭到入侵,攻击者无法访问支付凭证
  • ✅ 隐私保护:凭证提供方绝不会看到您的购物对话
  • ✅ 合规性:隔离支付数据后,更容易满足 PCI-DSS 要求
  • ✅ 问责机制:明确每个步骤的责任

智能体如何通信:状态作为共享记事本

由于代理无法直接访问彼此的数据,因此它们通过共享状态进行通信。您可以将其视为所有智能体都可以写入和读取的白板:

# Shopping Agent writes:
state["intent_mandate"] = {
    "natural_language_description": "Donate $50 to Room to Read",
    "merchants": ["Room to Read"],
    "intent_expiry": "2024-11-07T15:32:16Z",
    "amount": 50.0
}

# Merchant Agent reads:
intent = state["intent_mandate"]
charity_name = intent["merchants"][0]
amount = intent["amount"]
# Creates CartMandate based on IntentMandate...

# Credentials Provider reads:
cart_mandate = state["cart_mandate"]
# Processes payment...

这就是我们在实现协作的同时维护信任边界的方式。

我们的首个导购智能体

导购智能体的职责简单而专注:

  1. 使用 find_charities 工具查询我们可信的数据库
  2. 向用户显示选项
  3. 使用 save_user_choice 工具创建 IntentMandate 并将其保存到状态
  4. 移交给下一个代理(商家)

大功告成。无需处理付款,无需创建购物车,只需发现和转接。

我们来一步步构建。

第 1 步:添加输入验证辅助程序

在构建生产工具时,输入验证至关重要。我们来创建一个辅助函数,用于在将慈善机构数据保存到状态之前对其进行验证。

👉 开放

charity_advisor/tools/charity_tools.py

您会在顶部看到 find_charities 函数(已完成)。向下滚动,找到以下内容:

# MODULE_4_STEP_1_ADD_VALIDATION_HELPER

👉 将该行替换为:

def _validate_charity_data(charity_name: str, charity_ein: str, amount: float) -> tuple[bool, str]:
    """
    Validates charity selection data before saving to state.
    
    This helper function performs basic validation to ensure data quality
    before it gets passed to other agents in the pipeline.
    
    Args:
        charity_name: Name of the selected charity
        charity_ein: Employer Identification Number (should be format: XX-XXXXXXX)
        amount: Donation amount in USD
        
    Returns:
        (is_valid, error_message): Tuple where is_valid is True if all checks pass,
                                    and error_message contains details if validation fails
    """
    # Validate charity name
    if not charity_name or not charity_name.strip():
        return False, "Charity name cannot be empty"
    
    # Validate EIN format (should be XX-XXXXXXX)
    if not charity_ein or len(charity_ein) != 10 or charity_ein[2] != '-':
        return False, f"Invalid EIN format: {charity_ein}. Expected format: XX-XXXXXXX"
    
    # Validate amount
    if amount <= 0:
        return False, f"Donation amount must be positive, got: ${amount}"
    
    if amount > 1_000_000:
        return False, f"Donation amount exceeds maximum of $1,000,000: ${amount}"
    
    # All checks passed
    return True, ""

第 2 步:添加 IntentMandate 创建辅助程序

现在,我们来创建用于构建 AP2 IntentMandate 结构的辅助程序。这是 AP2 中的三种可验证凭证之一。

👉 在同一文件中,找到以下内容:

# MODULE_4_STEP_2_ADD_INTENTMANDATE_CREATION_HELPER

👉 将该行替换为:

def _create_intent_mandate(charity_name: str, charity_ein: str, amount: float) -> dict:
    """
    Creates an IntentMandate - AP2's verifiable credential for user intent.
    
    This function uses the official Pydantic model from the `ap2` package
    to create a validated IntentMandate object before converting it to a dictionary.
    
    Args:
        charity_name: Name of the selected charity
        charity_ein: Employer Identification Number
        amount: Donation amount in USD
        
    Returns:
        Dictionary containing the IntentMandate structure per AP2 specification
    """
    from datetime import datetime, timedelta, timezone
    from ap2.types.mandate import IntentMandate
    
    # Set the expiry for the intent
    expiry = datetime.now(timezone.utc) + timedelta(hours=1)
    
    # Step 1: Instantiate the Pydantic model with official AP2 fields
    intent_mandate_model = IntentMandate(
        user_cart_confirmation_required=True,
        natural_language_description=f"Donate ${amount:.2f} to {charity_name}",
        merchants=[charity_name],
        skus=None,
        requires_refundability=False,
        intent_expiry=expiry.isoformat()
    )
    
    # Step 2: Convert the validated model to a dictionary for state storage
    intent_mandate_dict = intent_mandate_model.model_dump()
    
    # Step 3: Add the codelab's custom fields to the dictionary
    timestamp = datetime.now(timezone.utc)
    intent_mandate_dict.update({
        "timestamp": timestamp.isoformat(),
        "intent_id": f"intent_{charity_ein.replace('-', '')}_{int(timestamp.timestamp())}",
        "charity_ein": charity_ein,
        "amount": amount,
        "currency": "USD"
    })
    
    return intent_mandate_dict

第 3 步:使用 IntentMandate 构建状态交接工具

现在,我们来构建用于创建 IntentMandate 并将其保存到状态的工具。

👉 在同一文件中,向下滚动到

save_user_choice

函数。查找:

# MODULE_4_STEP_3_COMPLETE_SAVE_TOOL

👉 将该行替换为:

    # Validate inputs before creating IntentMandate
    is_valid, error_message = _validate_charity_data(charity_name, charity_ein, amount)
    if not is_valid:
        logger.error(f"Validation failed: {error_message}")
        return {"status": "error", "message": error_message}
    
    # Create AP2 IntentMandate using our updated helper function
    intent_mandate = _create_intent_mandate(charity_name, charity_ein, amount)
    
    # Write the IntentMandate to shared state for the next agent
    tool_context.state["intent_mandate"] = intent_mandate
    
    logger.info(f"Successfully created IntentMandate and saved to state")
    logger.info(f"Intent ID: {intent_mandate['intent_id']}")
    logger.info(f"Intent expires: {intent_mandate['intent_expiry']}")
    
    # Return success confirmation
    return {
        "status": "success",
        "message": f"Created IntentMandate: ${amount:.2f} donation to {charity_name} (EIN: {charity_ein})",
        "intent_id": intent_mandate["intent_id"],
        "expiry": intent_mandate["intent_expiry"]
    }

第 4 步:添加显示格式辅助程序

在构建智能体之前,我们再添加一个辅助函数,用于设置慈善机构数据的格式,以便于用户查看。

👉 滚动查找:

# MODULE_4_STEP_4_ADD_FORMATTING_HELPER

👉 将该行替换为:

def _format_charity_display(charity: dict) -> str:
    """
    Formats a charity dictionary into a user-friendly display string.
    
    This helper function demonstrates how to transform structured data
    into readable text for the user.
    
    Args:
        charity: Dictionary containing charity data (name, ein, mission, rating, efficiency)
        
    Returns:
        Formatted string suitable for display to the user
    """
    name = charity.get('name', 'Unknown')
    ein = charity.get('ein', 'N/A')
    mission = charity.get('mission', 'No mission statement available')
    rating = charity.get('rating', 0.0)
    efficiency = charity.get('efficiency', 0.0)
    
    # Format efficiency as percentage
    efficiency_pct = int(efficiency * 100)
    
    # Build formatted string
    display = f"""
**{name}** (EIN: {ein})
⭐ Rating: {rating}/5.0
💰 Efficiency: {efficiency_pct}% of funds go to programs
📋 Mission: {mission}
    """.strip()
    
    return display

第 5 步:构建导购智能体 - 导入组件

现在,我们的工具已经完善且可靠,接下来我们来创建将使用这些工具的智能体。

👉 开放

charity_advisor/shopping_agent/agent.py

您会看到一个包含占位评论的模板。我们来一步步构建。

👉 查找:

# MODULE_4_STEP_5_IMPORT_COMPONENTS

👉 将该行替换为:

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.charity_tools import find_charities, save_user_choice

第 6 步:编写智能体指令

指令用于定义智能体的工作说明和工作流。这一点至关重要,因为指令写得不好会导致行为不可靠。

👉 查找:

# MODULE_4_STEP_6_WRITE_INSTRUCTION
instruction="""""",

👉 将这两行代码替换为:

    instruction="""You are a research specialist helping users find verified charities.

Your workflow:

1. When the user describes what cause they want to support (e.g., "education", "health", "environment"),
   use the find_charities tool to search our vetted database.

2. Present the results clearly. The tool returns formatted charity information that you should
   show to the user.

3. When the user selects a charity and specifies an amount, use the save_user_choice tool
   to create an IntentMandate and record their decision. You MUST call save_user_choice with:
   - charity_name: The exact name of the chosen charity
   - charity_ein: The EIN of the chosen charity  
   - amount: The donation amount in dollars (as a number, not a string)

4. After successfully saving, inform the user:
   - That you've created an IntentMandate (mention the intent ID if provided)
   - When the intent expires
   - That you're passing their request to the secure payment processor

IMPORTANT BOUNDARIES:
- Your ONLY job is discovery and creating the IntentMandate
- You do NOT process payments
- You do NOT see the user's payment methods
- You do NOT create cart offers (that's the Merchant Agent's job)
- After calling save_user_choice, your work is done

WHAT IS AN INTENTMANDATE:
An IntentMandate is a structured record of what the user wants to do. It includes:
- Natural language description ("Donate $50 to Room to Read")
- Which merchants can fulfill it
- When the intent expires
- Whether user confirmation is required

This is the first of three verifiable credentials in our secure payment system.

If the user asks you to do anything related to payment processing, politely explain that
you don't have that capability and that their request will be handled by the appropriate
specialist agent.""",

第 7 步:向智能体添加工具

现在,我们让智能体能够访问这两个工具。

👉 查找:

# MODULE_4_STEP_7_ADD_TOOLS

👉 将这两行代码替换为:

    tools=[
        FunctionTool(func=find_charities),
        FunctionTool(func=save_user_choice)
    ]

第 8 步:验证完整的智能体

我们来检查一下所有连接是否正确。

👉 您的完整

charity_advisor/shopping_agent/agent.py

现在应如下所示:

"""
Shopping Agent - Finds charities from a trusted database and saves the user's choice.
This agent acts as our specialized "Research Analyst."
"""

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.charity_tools import find_charities, save_user_choice


shopping_agent = Agent(
    name="ShoppingAgent",
    model="gemini-2.5-pro",
    description="Finds and recommends vetted charities from a trusted database, then creates an IntentMandate capturing the user's donation intent.",
    instruction="""You are a research specialist helping users find verified charities.

Your workflow:

1. When the user describes what cause they want to support (e.g., "education", "health", "environment"),
   use the find_charities tool to search our vetted database.

2. Present the results clearly. The tool returns formatted charity information that you should
   show to the user.

3. When the user selects a charity and specifies an amount, use the save_user_choice tool
   to create an IntentMandate and record their decision. You MUST call save_user_choice with:
   - charity_name: The exact name of the chosen charity
   - charity_ein: The EIN of the chosen charity  
   - amount: The donation amount in dollars (as a number, not a string)

4. After successfully saving, inform the user:
   - That you've created an IntentMandate (mention the intent ID if provided)
   - When the intent expires
   - That you're passing their request to the secure payment processor

IMPORTANT BOUNDARIES:
- Your ONLY job is discovery and creating the IntentMandate
- You do NOT process payments
- You do NOT see the user's payment methods
- You do NOT create cart offers (that's the Merchant Agent's job)
- After calling save_user_choice, your work is done

WHAT IS AN INTENTMANDATE:
An IntentMandate is a structured record of what the user wants to do. It includes:
- Natural language description ("Donate $50 to Room to Read")
- Which merchants can fulfill it
- When the intent expires
- Whether user confirmation is required

This is the first of three verifiable credentials in our secure payment system.

If the user asks you to do anything related to payment processing, politely explain that
you don't have that capability and that their request will be handled by the appropriate
specialist agent.""",
    tools=[
        FunctionTool(func=find_charities),
        FunctionTool(func=save_user_choice)
    ]
)

✅ 太棒了!您已构建出一个符合 AP2 标准、达到生产质量的智能体,它具有以下特点:

  • 输入验证
  • 使用 AP2 Pydantic 模型正确创建 IntentMandate
  • 格式化输出
  • 明确角色边界
  • 详细说明
  • 错误处理

第 9 步:测试导购智能体

让我们验证一下代理是否能正常运行、创建正确的 IntentMandate 并遵守其边界。

👉 在 Cloud Shell 终端中,运行以下命令:

adk run charity_advisor/shopping_agent

系统会显示 [user]: 提示符。

测试 1:使用可信数据库进行发现

👉 类型:

I want to donate to an education charity. What are my options?

片刻之后,智能体将提供回答。得益于我们的 _format_charity_display 辅助函数,结果的格式非常美观:

我在我们的数据库中找到了 3 家经过验证的教育慈善机构:

Room to Read(EIN:77-0479905)
⭐ 评分:4.9/5.0
💰 效率:88% 的资金用于项目
📋 使命:专注于扫盲和教育领域的性别平等,改变低收入社区数百万儿童的生活。

Teach For America(EIN:13-3541913)
⭐ 评分:4.7/5.0
💰 效率:81% 的资金用于项目
📋 使命:致力于为面临逆境的儿童提供更多教育机会。

Tech Education Alliance(EIN:45-2345678)
⭐ 评分:4.8/5.0
💰 效率:92% 的资金用于项目
📋 使命:为资源匮乏的学校提供计算机科学教育。

您想支持哪家慈善机构?捐款金额是多少?

与第 3 单元中的简单智能体相比,后者会提供未经审核的 Google 搜索结果。这就是不受信任的发现和受信任的发现之间的区别。

测试 2:记录用户选择并创建 IntentMandate

👉 类型:

I'll donate $50 to Room to Read.

您应该会看到智能体使用正确的参数调用 save_user_choice 工具。由于我们使用 AP2 模型创建了 IntentMandate,您会看到更有条理的回答:

太好了!我已为您的捐款创建了 IntentMandate:

意图详情:

  • Intent ID: intent_774795905_1730927536
  • 金额:50.00 美元,捐给 Room to Read(EIN:77-0479905)
  • 到期时间:2024-11-07T15:32:16Z(1 小时后)

此 IntentMandate 会捕获您的捐款意向,并包含一些限制条件,以确保交易安全处理。我现在将此信息传递给我们的安全付款处理方,以便创建正式优惠并完成您的捐赠。

在后台,刚刚发生了以下几件事:

  1. _validate_charity_data()验证了输入内容
  2. _create_intent_mandate() 使用 AP2 Pydantic 模型构建了以下结构:
   # Created and validated via Pydantic
   intent_mandate_model = IntentMandate(
       user_cart_confirmation_required=True,
       natural_language_description="Donate $50.00 to Room to Read",
       merchants=["Room to Read"],
       skus=None,
       requires_refundability=False,
       intent_expiry="2024-11-07T15:32:16Z"
   )
   
   # Converted to dict and extended with custom fields
   intent_mandate_dict = intent_mandate_model.model_dump()
   intent_mandate_dict.update({
       "charity_ein": "77-0479905",
       "amount": 50.0,
       "currency": "USD"
   })
  1. 该工具仅将 IntentMandate 写入了共享状态:
   state["intent_mandate"] = intent_mandate_dict
  1. 系统向 LLM 返回了一条包含 intent 详细信息的成功消息
  2. LLM 撰写了最终的用户消息

此 IntentMandate 现在已准备就绪,可供商家代理(模块 5)获取。商家将从 IntentMandate 中提取慈善机构名称和金额,并验证其是否已过期。

测试 3:验证实际效果

我们来验证一下验证辅助函数是否能捕获错误输入。

👉 类型:

I'll donate -$25 to Room to Read.

智能体应能识别出无效金额:

我遇到了一个问题:捐款金额必须为正数,但实际金额为:$-25.0

请指定一个正数捐款金额,我会为您创建 IntentMandate。

这就是防御性编程的实际应用。我们的 _validate_charity_data 辅助程序阻止了无效数据进入系统并创建格式错误的 IntentMandate。

测试 4:验证信任边界

👉 尝试让智能体处理付款:

Now process my credit card payment.

智能体应拒绝,遵守其角色边界:

我无法处理付款,这不是我的职责范围。我的职责是帮助您找到经过验证的慈善机构,并创建 IntentMandate 来记录您的捐赠意向。

您的 IntentMandate 已创建并传递给我们的安全付款处理方。商家代理会创建一份正式要约 (CartMandate),然后凭证提供方会在征得您明确同意的情况下处理实际付款。

这就是信任边界的实际应用。代理知道自己无权处理支付数据,并且其指令明确引导它向用户解释这一点,同时向用户介绍 IntentMandate 概念。

👉 按

Ctrl+C

,在测试完成后退出。

您刚刚构建的内容

您已成功使用 AP2 Pydantic 模型创建了正确的 IntentMandate,从而实现了 AP2 架构的第一部分。

掌握的关键概念

✅ 基于角色的架构:

  • 每个智能体都有一个明确定义的任务
  • 智能体通过共享状态进行通信,而不是直接访问
  • 信任边界可限制入侵的影响

✅ IntentMandate(AP2 凭证 #1):

  • 使用官方 AP2 Pydantic 模型创建,用于验证
  • 结构化捕获用户意图
  • 包含过期时间,以确保安全性(防范重放攻击)
  • 指定限制条件(商家、可退款性、确认)
  • 供人类使用的自然语言说明
  • 机器可读,便于智能体理解
  • 在转换为字典之前已验证模型

✅ 状态作为共享内存:

  • tool_context.state是所有代理都可以访问的“记事本”
  • 写入状态 = 提供可验证的凭证
  • 从状态读取 = 使用和验证凭据
  • 下游代理从凭证中提取所需信息

✅ FunctionTool:

  • 将 Python 函数转换为 LLM 可调用的工具
  • 依赖文档字符串和类型提示,以便 LLM 理解
  • 自动处理调用
  • 工具可组合性:小型专注工具 > 单体式工具

✅客服人员操作说明:

  • 分步工作流指导
  • 明确的边界(“请勿…”)
  • 参数规范,可防止出错
  • 技术定义(什么是 IntentMandate)
  • 极端情况处理(在…时该说什么)

后续步骤

在下一个单元中,我们将构建商家代理,用于接收 IntentMandate 并创建第二个可验证凭证:CartMandate。

导购智能体已创建 IntentMandate,其中包含用户的意图和有效期。现在,我们需要一个代理来读取该凭证,验证其是否有效,并创建一份正式的、经过签名的报价单,内容为:“我,即商家,将遵守此价格并交付这些商品。”

我们来构建商家代理,看看第二个 AP2 凭证的实际应用。

5. 构建商家代理 - 绑定优惠和 CartMandate

横幅

从发现到承诺

在上一模块中,您构建了导购智能体,这是一个专门负责查找经过验证的慈善机构并创建 IntentMandate 以捕获用户意图的智能体。现在,我们需要一个智能体来接收该 IntentMandate,并创建一份正式的、具有约束力的报价。

这正是 AP2 的第二个关键原则发挥作用的地方:通过 CartMandate 提供可验证的凭证。

AP2 原则:购物车授权和绑定优惠

为什么我们需要商家角色

在第 4 单元中,Shopping Agent 创建了一个 IntentMandate 并将其保存到状态中:

state["intent_mandate"] = {
    "natural_language_description": "Donate $50 to Room to Read",
    "merchants": ["Room to Read"],
    "amount": 50.0,
    "intent_expiry": "2024-11-07T15:32:16Z"
}

但这只是用户意图。在处理任何付款之前,我们需要:

  • 支付系统可理解的正式优惠结构
  • 证明商家会遵守此价格
  • 具有约束力的承诺,在交易过程中无法更改
  • 验证 intent 是否未过期

这就是 Merchant Agent 的工作。

什么是 CartMandate?

CartMandate 是 AP2 中表示“数字购物车”的术语,用作具有约束力的要约。它根据 W3C PaymentRequest 标准进行结构化,这意味着:

  • 全球付款处理方均可识别该格式
  • 它以标准化方式包含所有交易详情
  • 可以进行加密签名以证明真实性

您可以将其视为承包商提供的书面报价:

  • ❌ 口头:“是的,我可以以大约 50 美元的价格完成这项工作”
  • ✅ 书面报价单:分项费用、总费用、签名、日期

书面报价具有约束力。CartMandate 是数字等效项。

加入购物车意向

CartMandate 的结构

AP2 中的 CartMandate 具有特定的嵌套结构:

cart_mandate = {
    "contents": {  # ← AP2 wrapper
        "id": "cart_xyz123",
        "cart_expiry": "2024-11-07T15:47:16Z",
        "merchant_name": "Room to Read",
        "user_cart_confirmation_required": False,
        
        "payment_request": {  # ← W3C PaymentRequest nested inside
            "method_data": [...],
            "details": {...},
            "options": {...}
        }
    },
    "merchant_authorization": "SIG_a3f7b2c8"  # ← Merchant signature
}

三大核心组件:

1. contents - 购物车封装容器,包含:

  • 购物车 ID 和有效期
  • 商家名称
  • W3C PaymentRequest

2. payment_request(在 contents 内)- 购买的内容:

  • method_data:接受的支付方式
  • 详细信息:商品和总金额
  • 选项:配送、付款人信息要求

3. merchant_authorization - 加密签名

商家签名:承诺证明

商家签名至关重要。它证明了:

  • 此优惠来自授权商家
  • 商家承诺遵守此确切价格
  • 优惠自创建后未被篡改

在生产环境中,这会是使用 PKI(公钥基础架构)或 JWT(JSON Web 令牌)的加密签名。在我们的教育研讨会中,我们将使用 SHA-256 哈希来模拟此过程。

# Production (real signature):
signature = sign_with_private_key(cart_data, merchant_private_key)

# Workshop (simulated signature):
cart_hash = hashlib.sha256(cart_json.encode()).hexdigest()
signature = f"SIG_{cart_hash[:16]}"

我们的使命:打造 Merchant Agent

商家代理将:

  1. 从状态中读取 IntentMandate(导购智能体写入的内容)
  2. 验证 intent 是否未过期
  3. 提取慈善机构名称、金额和其他详细信息
  4. 使用 AP2 Pydantic 模型创建符合 W3C 标准的 PaymentRequest 结构
  5. 将其封装在 AP2 的 CartMandate 中,并设置到期时间
  6. 添加模拟商家签名
  7. 将 CartMandate 写入状态,以便凭据提供程序(下一个模块)使用

我们来一步步构建。

第 1 步:添加 Expiry Validation Helper

首先,我们来设置与商家相关的工具文件,并添加一个辅助函数来验证 IntentMandate 的到期时间。

👉 开放

charity_advisor/tools/merchant_tools.py

我们来添加过期验证:

👉 查找:

# MODULE_5_STEP_1_ADD_EXPIRY_VALIDATION_HELPER

👉 将该行替换为:

def _validate_intent_expiry(intent_expiry_str: str) -> tuple[bool, str]:
    """
    Validates that the IntentMandate hasn't expired.
    
    This is a critical security check - expired intents should not be processed.
    
    Args:
        intent_expiry_str: The ISO 8601 timestamp string from the IntentMandate.
        
    Returns:
        (is_valid, error_message): Tuple indicating if intent is still valid.
    """
    try:
        # The .replace('Z', '+00:00') is for compatibility with older Python versions
        expiry_time = datetime.fromisoformat(intent_expiry_str.replace('Z', '+00:00'))
        now = datetime.now(timezone.utc)
        
        if expiry_time < now:
            return False, f"IntentMandate expired at {intent_expiry_str}"
        
        time_remaining = expiry_time - now
        logger.info(f"IntentMandate valid. Expires in {time_remaining.total_seconds():.0f} seconds")
        
        return True, ""
        
    except (ValueError, TypeError) as e:
        return False, f"Invalid intent_expiry format: {e}"

第 2 步:添加签名生成辅助程序

现在,我们来创建一个用于生成模拟商家签名的辅助函数。

👉 查找:

# MODULE_5_STEP_2_ADD_SIGNATURE_HELPER

👉 将该行替换为:

def _generate_merchant_signature(cart_contents: CartContents) -> str:
    """
    Generates a simulated merchant signature for the CartMandate contents.
    
    In production, this would use PKI or JWT with the merchant's private key.
    For this codelab, we use a SHA-256 hash of the sorted JSON representation.
    
    Args:
        cart_contents: The Pydantic model of the cart contents to sign.
        
    Returns:
        Simulated signature string (format: "SIG_" + first 16 chars of hash).
    """
    # Step 1: Dump the Pydantic model to a dictionary. The `mode='json'` argument
    # ensures that complex types like datetimes are serialized correctly.
    cart_contents_dict = cart_contents.model_dump(mode='json')
    
    # Step 2: Use the standard json library to create a stable, sorted JSON string.
    # separators=(',', ':') removes whitespace for a compact and canonical representation.
    cart_json = json.dumps(cart_contents_dict, sort_keys=True, separators=(',', ':'))
    
    # Step 3: Generate SHA-256 hash.
    cart_hash = hashlib.sha256(cart_json.encode('utf-8')).hexdigest()
    
    # Step 4: Create signature in a recognizable format.
    signature = f"SIG_{cart_hash[:16]}"
    
    logger.info(f"Generated merchant signature: {signature}")
    return signature

第 3A 步:创建工具签名和设置

现在,我们开始构建主要工具。我们将通过四个子步骤逐步创建该应用。首先是函数签名和初始设置。

👉 查找:

# MODULE_5_STEP_3A_CREATE_TOOL_SIGNATURE

👉 将该行替换为:

async def create_cart_mandate(tool_context: Any) -> Dict[str, Any]:
    """
    Creates a W3C PaymentRequest-compliant CartMandate from the IntentMandate.
    
    This tool reads the IntentMandate from shared state, validates it, and
    creates a formal, signed offer using the official AP2 Pydantic models.
    
    Returns:
        Dictionary containing status and the created CartMandate.
    """
    logger.info("Tool called: Creating CartMandate from IntentMandate")
    
    # MODULE_5_STEP_3B_ADD_VALIDATION_LOGIC

第 3B 步:添加验证逻辑

现在,我们来添加逻辑,使用 AP2 Pydantic 模型读取和验证 IntentMandate,并提取所需的数据。

👉 查找:

# MODULE_5_STEP_3B_ADD_VALIDATION_LOGIC

👉 将该行替换为:

    # 1. Read IntentMandate dictionary from state
    intent_mandate_dict = tool_context.state.get("intent_mandate")
    if not intent_mandate_dict:
        logger.error("No IntentMandate found in state")
        return {
            "status": "error",
            "message": "No IntentMandate found. Shopping Agent must create intent first."
        }
    
    # 2. Parse dictionary into a validated Pydantic model
    try:
        intent_mandate_model = IntentMandate.model_validate(intent_mandate_dict)
    except Exception as e:
        logger.error(f"Could not validate IntentMandate structure: {e}")
        return {"status": "error", "message": f"Invalid IntentMandate structure: {e}"}
    
    # 3. Validate that the intent hasn't expired (CRITICAL security check)
    is_valid, error_message = _validate_intent_expiry(intent_mandate_model.intent_expiry)
    if not is_valid:
        logger.error(f"IntentMandate validation failed: {error_message}")
        return {"status": "error", "message": error_message}
    
    # 4. Extract data. Safely access standard fields from the model, and
    # custom fields (like 'amount') from the original dictionary.
    charity_name = intent_mandate_model.merchants[0] if intent_mandate_model.merchants else "Unknown Charity"
    amount = intent_mandate_dict.get("amount", 0.0)
    
    # MODULE_5_STEP_3C_CREATE_CARTMANDATE_STRUCTURE

第 3C 步:创建 CartMandate 结构

现在,我们来构建符合 W3C 规范的 PaymentRequest 结构,并使用 Pydantic 模型将其封装在 AP2 CartMandate 中。

👉 查找:

# MODULE_5_STEP_3C_CREATE_CARTMANDATE_STRUCTURE

👉 将该行替换为:

    # 5. Build the nested Pydantic models for the CartMandate
    timestamp = datetime.now(timezone.utc)
    cart_id = f"cart_{hashlib.sha256(f'{charity_name}{timestamp.isoformat()}'.encode()).hexdigest()[:12]}"
    cart_expiry = timestamp + timedelta(minutes=15)
    
    payment_request_model = PaymentRequest(
        method_data=[PaymentMethodData(
            supported_methods="CARD",
            data={"supported_networks": ["visa", "mastercard", "amex"], "supported_types": ["debit", "credit"]}
        )],
        details=PaymentDetailsInit(
            id=f"order_{cart_id}",
            display_items=[PaymentItem(
                label=f"Donation to {charity_name}",
                amount=PaymentCurrencyAmount(currency="USD", value=amount)  # Pydantic v2 handles float -> str conversion
            )],
            total=PaymentItem(
                label="Total Donation",
                amount=PaymentCurrencyAmount(currency="USD", value=amount)
            )
        ),
        options=PaymentOptions(request_shipping=False)
    )
    
    cart_contents_model = CartContents(
        id=cart_id,
        cart_expiry=cart_expiry.isoformat(),
        merchant_name=charity_name,
        user_cart_confirmation_required=False,
        payment_request=payment_request_model
    )
    
    # MODULE_5_STEP_3D_ADD_SIGNATURE_AND_SAVE

第 3D 步:添加签名并保存到状态

最后,我们使用 Pydantic 模型对 CartMandate 进行签名,并将其保存到状态中,以供下一个智能体使用。

👉 查找:

# MODULE_5_STEP_3D_ADD_SIGNATURE_AND_SAVE

👉 将该行替换为:

    # 6. Generate signature from the validated Pydantic model
    signature = _generate_merchant_signature(cart_contents_model)
    
    # 7. Create the final CartMandate model, now including the signature
    cart_mandate_model = CartMandate(
        contents=cart_contents_model,
        merchant_authorization=signature
    )
    
    # 8. Convert the final model to a dictionary for state storage and add the custom timestamp
    cart_mandate_dict = cart_mandate_model.model_dump(mode='json')
    cart_mandate_dict["timestamp"] = timestamp.isoformat()
    
    # 9. Write the final dictionary to state
    tool_context.state["cart_mandate"] = cart_mandate_dict
    
    logger.info(f"CartMandate created successfully: {cart_id}")
    
    return {
        "status": "success",
        "message": f"Created signed CartMandate {cart_id} for ${amount:.2f} donation to {charity_name}",
        "cart_id": cart_id,
        "cart_expiry": cart_expiry.isoformat(),
        "signature": signature
    }

第 4 步:构建商家代理 - 导入组件

现在,我们来创建将使用此工具的智能体。

👉 开放

charity_advisor/merchant_agent/agent.py

您会看到一个带有占位符标记的模板。首先,导入所需的内容。

👉 查找:

# MODULE_5_STEP_4_IMPORT_COMPONENTS

👉 将该行替换为:

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.merchant_tools import create_cart_mandate

第 5 步:编写商家代理指令

现在,我们来编写指令,告诉智能体何时以及如何使用其工具。

👉 查找:

# MODULE_5_STEP_5_WRITE_INSTRUCTION
instruction="""""",

👉 将这两行代码替换为:

    instruction="""You are a merchant specialist responsible for creating formal, signed offers (CartMandates).

Your workflow:

1. Read the IntentMandate from shared state.
   The IntentMandate was created by the Shopping Agent and contains:
   - merchants: List of merchant names
   - amount: Donation amount
   - charity_ein: Tax ID
   - intent_expiry: When the intent expires

2. Use the create_cart_mandate tool to create a W3C PaymentRequest-compliant CartMandate.
   This tool will:
   - Validate the IntentMandate hasn't expired (CRITICAL security check)
   - Extract the charity name and amount from the IntentMandate
   - Create a structured offer with payment methods, transaction details, and merchant info
   - Generate a merchant signature to prove authenticity
   - Save the CartMandate to state for the payment processor

3. After creating the CartMandate, inform the user:
   - That you've created a formal, signed offer
   - The cart ID
   - When the cart expires (15 minutes)
   - That you're passing it to the secure payment processor

IMPORTANT BOUNDARIES:
- Your ONLY job is creating signed CartMandates from valid IntentMandates
- You do NOT process payments
- You do NOT see the user's payment methods or credentials
- You do NOT interact with payment networks
- You MUST validate that the IntentMandate hasn't expired before creating a cart
- After calling create_cart_mandate, your work is done

WHAT IS A CARTMANDATE:
A CartMandate is a binding commitment that says:
"I, the merchant, commit to accepting $X for this charity donation, and I prove it with my signature."

This commitment is structured using the W3C PaymentRequest standard and includes:
- Payment methods accepted (card, bank transfer)
- Transaction details (amount, charity name)
- Cart expiry (15 minutes from creation)
- Merchant signature (proof of commitment)

This is the second of three verifiable credentials in our secure payment system.""",

第 6 步:向商家代理添加工具

👉 查找:

# MODULE_5_STEP_6_ADD_TOOLS
tools=[],

👉 将这两行代码替换为:

    tools=[
        FunctionTool(func=create_cart_mandate)
    ],

第 7 步:验证完整的商家代理

我们来确认一下所有线路是否都已正确连接。

👉 您的完整

charity_advisor/merchant_agent/agent.py

现在应如下所示:

"""
Merchant Agent - Creates W3C-compliant CartMandates with merchant signatures.
This agent acts as our "Contract Creator."
"""

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.merchant_tools import create_cart_mandate


merchant_agent = Agent(
    name="MerchantAgent",
    model="gemini-2.5-flash",
    description="Creates formal, signed CartMandates for charity donations following W3C PaymentRequest standards.",
    tools=[
        FunctionTool(func=create_cart_mandate)
    ],
    instruction="""You are a merchant specialist responsible for creating formal, signed offers (CartMandates).

Your workflow:

1. Read the IntentMandate from shared state.
   The IntentMandate was created by the Shopping Agent and contains:
   - merchants: List of merchant names
   - amount: Donation amount
   - charity_ein: Tax ID
   - intent_expiry: When the intent expires

2. Use the create_cart_mandate tool to create a W3C PaymentRequest-compliant CartMandate.
   This tool will:
   - Validate the IntentMandate hasn't expired (CRITICAL security check)
   - Extract the charity name and amount from the IntentMandate
   - Create a structured offer with payment methods, transaction details, and merchant info
   - Generate a merchant signature to prove authenticity
   - Save the CartMandate to state for the payment processor

3. After creating the CartMandate, inform the user:
   - That you've created a formal, signed offer
   - The cart ID
   - When the cart expires (15 minutes)
   - That you're passing it to the secure payment processor

IMPORTANT BOUNDARIES:
- Your ONLY job is creating signed CartMandates from valid IntentMandates
- You do NOT process payments
- You do NOT see the user's payment methods or credentials
- You do NOT interact with payment networks
- You MUST validate that the IntentMandate hasn't expired before creating a cart
- After calling create_cart_mandate, your work is done

WHAT IS A CARTMANDATE:
A CartMandate is a binding commitment that says:
"I, the merchant, commit to accepting $X for this charity donation, and I prove it with my signature."

This commitment is structured using the W3C PaymentRequest standard and includes:
- Payment methods accepted (card, bank transfer)
- Transaction details (amount, charity name)
- Cart expiry (15 minutes from creation)
- Merchant signature (proof of commitment)

This is the second of three verifiable credentials in our secure payment system."""
)

✅ 检查点:您现在拥有了一个完整的商家代理,该代理使用 Pydantic 模型正确创建了 AP2 CartMandate。

第 8 步:测试商家代理

现在,我们来验证智能体是否能正确创建带有签名的 CartMandate 并验证其有效期。

测试设置:运行测试脚本

👉 在 Cloud Shell 终端中,运行以下命令:

python scripts/test_merchant.py

预期输出:

======================================================================
MERCHANT AGENT TEST
======================================================================

Simulated IntentMandate from Shopping Agent:
  charity: Room to Read
  amount: $50.00
  expiry: 2024-11-07T16:32:16Z

----------------------------------------------------------------------
Merchant Agent Response:
----------------------------------------------------------------------
Perfect! I've received your IntentMandate and created a formal, signed offer (CartMandate) for your donation.

**CartMandate Details:**
- **Cart ID**: cart_3b4c5d6e7f8a
- **Donation Amount**: $50.00 to Room to Read
- **Payment Methods Accepted**: Credit/debit cards (Visa, Mastercard, Amex) or bank transfer
- **Cart Expires**: 2024-11-07T15:47:16Z (in 15 minutes)
- **Merchant Signature**: SIG_a3f7b2c8d9e1f4a2

This signed CartMandate proves my commitment to accept this donation amount. I'm now passing this to the secure payment processor to complete your transaction.

======================================================================
CARTMANDATE CREATED:
======================================================================
  ID: cart_3b4c5d6e7f8a
  Amount: 50.00
  Merchant: Room to Read
  Expires: 2024-11-07T15:47:16Z
  Signature: SIG_a3f7b2c8d9e1f4a2
======================================================================

测试 2:验证 W3C 合规性

我们来验证一下 CartMandate 结构是否完全符合 AP2 和 W3C PaymentRequest 标准。

👉 运行验证脚本:

python scripts/validate_cartmandate.py

预期输出:

======================================================================
AP2 & W3C PAYMENTREQUEST VALIDATION
======================================================================
✅ CartMandate is AP2 and W3C PaymentRequest compliant

Structure validation passed:
  ✓ AP2 'contents' wrapper present
  ✓ AP2 'merchant_authorization' signature present
  ✓ cart_expiry present
  ✓ payment_request nested inside contents
  ✓ method_data present and valid
  ✓ details.total.amount present with currency and value
  ✓ All required W3C PaymentRequest fields present
======================================================================

您刚刚构建的内容

您已成功使用 Pydantic 模型实现了 AP2 的 CartMandate,确保了结构正确、到期验证和商家签名。

掌握的关键概念

✅ CartMandate(AP2 凭证 #2):

  • 使用官方 AP2 Pydantic 模型创建
  • 包含内容封装容器的 AP2 结构
  • W3C PaymentRequest 嵌套在
  • 购物车过期时间(短于意向)
  • 商家签署具有约束力的承诺
  • 模型验证可确保符合规范

✅ 到期验证:

  • 正在从状态读取 IntentMandate
  • 正在使用 IntentMandate.model_validate() 验证结构
  • 解析 ISO 8601 时间戳
  • 与当前时间进行比较
  • 防止过时处理的安全功能

✅ 商家签名:

  • 证明真实性和承诺
  • 根据经过验证的 Pydantic 模型生成
  • 使用 model_dump(mode='json') 表示规范形式
  • 使用 SHA-256 模拟,仅用于教育目的
  • 生产环境使用 PKI/JWT
  • 对内容模型(而非字典)进行签名

✅ W3C PaymentRequest:

  • 使用 AP2 的 PaymentRequest Pydantic 模型构建
  • 支付数据业界标准
  • 嵌套在 AP2 结构中
  • 包含 method_data、details、options
  • 实现互操作性

✅ 包含模型的凭证链:

  • 购物 → IntentMandate(已验证)
  • 商家读取 IntentMandate → CartMandate(两个模型均已验证)
  • 凭证提供程序将读取 CartMandate → PaymentMandate
  • 每个步骤都使用 Pydantic 验证上一个凭证

✅ 模型驱动开发:

  • 通过 model_validate() 进行输入验证
  • 类型安全构造
  • 通过 model_dump() 自动序列化
  • 可用于生产用途的模式

后续步骤

在下一个单元中,我们将构建凭证提供程序,以安全地处理付款。

商家代理已使用 AP2 模型创建了具有有效期的约束性报价。现在,我们需要一个智能体来读取 CartMandate、征得用户同意并执行付款。

让我们构建凭证提供程序并完成 AP2 凭证链。

6. 构建凭证提供程序 - 安全支付执行

横幅

从约束性要约到付款执行

在单元 5 中,您构建了商家智能体,这是一个专门读取 IntentMandate、验证其是否过期并创建带有商家签名的绑定 CartMandate 的智能体。现在,我们需要一个智能体来接收 CartMandate 并执行实际付款。

这就需要用到 AP2 的第三个也是最后一个原则:通过 PaymentMandate 安全执行付款。

AP2 原则:PaymentMandate 和 Payment Execution

为什么我们需要凭证提供方角色

在第 5 单元中,商家代理创建了 CartMandate 并将其保存到状态中:

state["cart_mandate"] = {
    "contents": {
        "id": "cart_abc123",
        "cart_expiry": "2025-11-07:15:47:16Z",
        "payment_request": {
            "details": {
                "total": {
                    "amount": {"currency": "USD", "value": "50.00"}
                }
            }
        }
    },
    "merchant_authorization": "SIG_a3f7b2c8"
}

但这只是一个有约束力的报价。在执行付款之前,我们需要:

  • 验证购物车是否未过期
  • 用户同意继续付款
  • 授权执行付款的凭据
  • 实际付款处理(或研讨会模拟)

这是凭据提供者的工作。

什么是 PaymentMandate?

PaymentMandate 是 AP2 中用于表示允许执行付款的最终授权的术语。这是 AP2 链中的第三个也是最后一个可验证凭证。

您可以将这三种凭证视为合同签署流程:

  • IntentMandate:“我有兴趣购买此产品”(意向书)
  • CartMandate:“我(商家)愿意以此价格出售”(书面报价)
  • PaymentMandate:“我授权您通过我的支付方式扣款”(已签署合同)

只有在所有这三种凭证都存在后,才能执行付款。

完整凭证链

PaymentMandate 的结构

AP2 中的 PaymentMandate 具有特定结构:

payment_mandate = {
    "payment_mandate_contents": {  # ← AP2 wrapper
        "payment_mandate_id": "payment_xyz123",
        "payment_details_id": "cart_abc123",  # Links to CartMandate
        "user_consent": True,
        "consent_timestamp": "2025-11-07T15:48:00Z",
        "amount": {
            "currency": "USD",
            "value": "50.00"
        },
        "merchant_name": "Room to Read"
    },
    "agent_present": True,  # Human-in-the-loop flow
    "timestamp": "2025-11-07T15:48:00Z"
}

关键组件:

1. payment_mandate_contents - 授权封装容器,包含:

  • payment_mandate_id:唯一标识符
  • payment_details_id:链接回 CartMandate
  • user_consent:用户是否已批准
  • amount:付款金额(从 CartMandate 中提取)

2. agent_present - 是否为人机协同流程

3. timestamp - 授权创建时间

我们的使命:构建凭证提供程序

凭证提供程序将:

  1. 从状态(商家代理写入的内容)中读取 CartMandate
  2. 使用 AP2 Pydantic 模型验证购物车是否已过期
  3. 从嵌套结构中提取付款详情
  4. 使用 AP2 模型在征得用户同意的情况下创建 PaymentMandate
  5. 模拟付款处理(在生产环境中,会调用实际的付款 API)
  6. 将 PaymentMandate 和支付结果写入状态

我们来一步步构建。

第 1 步:添加购物车失效验证辅助程序

首先,我们来创建一个辅助函数,用于验证 CartMandate 是否已过期,就像我们在第 5 单元中验证 IntentMandate 过期一样。

👉 开放

charity_advisor/tools/payment_tools.py

我们来添加过期验证:

👉 查找:

# MODULE_6_STEP_1_ADD_CART_EXPIRY_VALIDATION_HELPER

👉 将该行替换为:

def _validate_cart_expiry(cart: CartMandate) -> tuple[bool, str]:
    """
    Validates that the CartMandate hasn't expired.
    
    This is a critical security check - expired carts should not be processed.
    
    Args:
        cart: The Pydantic CartMandate model to validate.
        
    Returns:
        (is_valid, error_message): Tuple indicating if cart is still valid.
    """
    try:
        expiry_str = cart.contents.cart_expiry
        expiry_time = datetime.fromisoformat(expiry_str.replace('Z', '+00:00'))
        now = datetime.now(timezone.utc)
        
        if expiry_time < now:
            return False, f"CartMandate expired at {expiry_str}"
        
        time_remaining = expiry_time - now
        logger.info(f"CartMandate valid. Expires in {time_remaining.total_seconds():.0f} seconds")
        
        return True, ""
        
    except (ValueError, TypeError, AttributeError) as e:
        return False, f"Invalid cart_expiry format or structure: {e}"

第 2 步:添加 PaymentMandate Creation Helper

现在,我们来创建一个辅助函数,使用官方 AP2 Pydantic 模型构建 PaymentMandate 结构。

👉 查找:

# MODULE_6_STEP_2_ADD_PAYMENT_MANDATE_CREATION_HELPER

👉 将该行替换为:

def _create_payment_mandate(cart: CartMandate, consent_granted: bool) -> dict:
    """
    Creates a PaymentMandate using the official AP2 Pydantic models.
    
    It links to the CartMandate and includes user consent status.
    
    Args:
        cart: The validated Pydantic CartMandate model being processed.
        consent_granted: Whether the user has consented to the payment.
        
    Returns:
        A dictionary representation of the final, validated PaymentMandate.
    """
    timestamp = datetime.now(timezone.utc)
    
    # Safely extract details from the validated CartMandate model
    cart_id = cart.contents.id
    merchant_name = cart.contents.merchant_name
    total_item = cart.contents.payment_request.details.total
    
    # Create the nested PaymentResponse model for the mandate
    payment_response_model = PaymentResponse(
        request_id=cart_id,
        method_name="CARD",  # As per the simulated flow
        details={"token": "simulated_payment_token_12345"}
    )
    
    # Create the PaymentMandateContents model
    payment_mandate_contents_model = PaymentMandateContents(
        payment_mandate_id=f"payment_{hashlib.sha256(f'{cart_id}{timestamp.isoformat()}'.encode()).hexdigest()[:12]}",
        payment_details_id=cart_id,
        payment_details_total=total_item,
        payment_response=payment_response_model,
        merchant_agent=merchant_name,
        timestamp=timestamp.isoformat()
    )
    
    # Create the top-level PaymentMandate model
    # In a real system, a user signature would be added to this model
    payment_mandate_model = PaymentMandate(
        payment_mandate_contents=payment_mandate_contents_model
    )
    
    # Convert the final Pydantic model to a dictionary for state storage
    final_dict = payment_mandate_model.model_dump(mode='json')
    
    # Add any custom/non-standard fields required by the codelab's logic to the dictionary
    # The spec does not have these fields, but your original code did. We add them
    # back to ensure compatibility with later steps.
    final_dict['payment_mandate_contents']['user_consent'] = consent_granted
    final_dict['payment_mandate_contents']['consent_timestamp'] = timestamp.isoformat() if consent_granted else None
    final_dict['agent_present'] = True
    
    return final_dict

第 3A 步:创建工具签名和设置

现在,我们开始逐步构建主要工具。首先是函数签名和初始设置。

👉 查找:

# MODULE_6_STEP_3A_CREATE_TOOL_SIGNATURE

👉 将该行替换为:

async def create_payment_mandate(tool_context: Any) -> Dict[str, Any]:
    """
    Creates a PaymentMandate and simulates payment processing using Pydantic models.
    
    This tool now reads the CartMandate from state, parses it into a validated model,
    and creates a spec-compliant PaymentMandate.
    """
    logger.info("Tool called: Creating PaymentMandate and processing payment")
    
    # MODULE_6_STEP_3B_VALIDATE_CARTMANDATE

第 3B 步:验证 CartMandate

现在,我们来添加逻辑,以读取 CartMandate、使用 AP2 Pydantic 模型验证 CartMandate,并检查其是否过期。

👉 查找:

# MODULE_6_STEP_3B_VALIDATE_CARTMANDATE

👉 将该行替换为:

    # 1. Read CartMandate dictionary from state
    cart_mandate_dict = tool_context.state.get("cart_mandate")
    if not cart_mandate_dict:
        logger.error("No CartMandate found in state")
        return { "status": "error", "message": "No CartMandate found. Merchant Agent must create cart first." }
    
    # 2. Parse dictionary into a validated Pydantic model
    try:
        cart_model = CartMandate.model_validate(cart_mandate_dict)
    except Exception as e:
        logger.error(f"Could not validate CartMandate structure: {e}")
        return {"status": "error", "message": f"Invalid CartMandate structure: {e}"}
    
    # 3. Validate that the cart hasn't expired using the Pydantic model
    is_valid, error_message = _validate_cart_expiry(cart_model)
    if not is_valid:
        logger.error(f"CartMandate validation failed: {error_message}")
        return {"status": "error", "message": error_message}
    
    # MODULE_6_STEP_3C_EXTRACT_PAYMENT_DETAILS

第 3C 步:从嵌套结构中提取付款详情

现在,我们来浏览经过验证的 CartMandate 模型,以提取所需的付款详细信息。

👉 查找:

# MODULE_6_STEP_3C_EXTRACT_PAYMENT_DETAILS

👉 将该行替换为:

    # 4. Safely extract data from the validated model
    cart_id = cart_model.contents.id
    merchant_name = cart_model.contents.merchant_name
    amount_value = cart_model.contents.payment_request.details.total.amount.value
    currency = cart_model.contents.payment_request.details.total.amount.currency
    consent_granted = True  # Assume consent for this codelab flow
    
    # MODULE_6_STEP_3D_CREATE_PAYMENTMANDATE_AND_SIMULATE

第 3D 步:创建 PaymentMandate 并模拟付款

最后,我们使用基于 Pydantic 的辅助函数创建 PaymentMandate,模拟付款处理,并将所有内容保存到状态中。

👉 查找:

# MODULE_6_STEP_3D_CREATE_PAYMENTMANDATE_AND_SIMULATE

👉 将该行替换为:

    # 5. Create the spec-compliant PaymentMandate using the validated CartMandate model
    payment_mandate_dict = _create_payment_mandate(cart_model, consent_granted)
    
    # 6. Simulate payment processing
    transaction_id = f"txn_{hashlib.sha256(f'{cart_id}{datetime.now(timezone.utc).isoformat()}'.encode()).hexdigest()[:16]}"
    payment_result = {
        "transaction_id": transaction_id,
        "status": "completed",
        "amount": amount_value,
        "currency": currency,
        "merchant": merchant_name,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "simulation": True
    }
    
    # 7. Write the compliant PaymentMandate dictionary and result to state
    tool_context.state["payment_mandate"] = payment_mandate_dict
    tool_context.state["payment_result"] = payment_result
    
    logger.info(f"Payment processed successfully: {transaction_id}")
    
    return {
        "status": "success",
        "message": f"Payment of {currency} {amount_value:.2f} to {merchant_name} processed successfully",
        "transaction_id": transaction_id,
        "payment_mandate_id": payment_mandate_dict["payment_mandate_contents"]["payment_mandate_id"]
    }

第 4 步:构建 Credentials Provider Agent - 导入组件

现在,我们来创建使用此工具的智能体。

👉 开放

charity_advisor/credentials_provider/agent.py

您会看到一个带有占位符标记的模板。首先,导入所需的内容。

👉 查找:

# MODULE_6_STEP_4_IMPORT_COMPONENTS

👉 将该行替换为:

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.payment_tools import create_payment_mandate

第 5 步:编写凭证提供程序指令

现在,我们来编写用于指导智能体的指令。

👉 查找:

# MODULE_6_STEP_5_WRITE_INSTRUCTION
instruction="""""",

👉 将这两行代码替换为:

    instruction="""You are a payment specialist responsible for securely processing payments with user consent.

Your workflow:

1. Read the CartMandate from shared state.
   The CartMandate was created by the Merchant Agent and has this structure:
   - contents: AP2 wrapper containing:
     - id: Cart identifier
     - cart_expiry: When the cart expires
     - merchant_name: Who is receiving payment
     - payment_request: W3C PaymentRequest with transaction details
   - merchant_authorization: Merchant's signature

2. Extract payment details from the nested structure:
   - Navigate: cart_mandate["contents"]["payment_request"]["details"]["total"]["amount"]
   - This gives you the currency and value

3. **IMPORTANT - Two-Turn Conversational Confirmation Pattern:**
   Before calling create_payment_mandate, you MUST:
   - Present the payment details clearly to the user
   - Ask explicitly: "I'm ready to process a payment of $X to [Charity Name]. Do you want to proceed with this donation?"
   - WAIT for the user's explicit confirmation (e.g., "yes", "proceed", "confirm")
   - ONLY call create_payment_mandate AFTER receiving explicit confirmation
   - If user says "no" or "cancel", DO NOT call the tool

4. After user confirms, use the create_payment_mandate tool to:
   - Validate the CartMandate hasn't expired (CRITICAL security check)
   - Create a PaymentMandate (the third AP2 credential)
   - Simulate payment processing
   - Record the transaction result

5. After processing, inform the user:
   - That payment was processed successfully (this is a simulation)
   - The transaction ID
   - The amount and merchant
   - That this completes the three-agent AP2 credential chain

IMPORTANT BOUNDARIES:
- Your ONLY job is creating PaymentMandates and processing payments
- You do NOT discover charities (that's Shopping Agent's job)
- You do NOT create offers (that's Merchant Agent's job)
- You MUST validate that the CartMandate hasn't expired before processing
- You MUST get explicit user confirmation before calling create_payment_mandate
- In production, this consent mechanism would be even more robust

WHAT IS A PAYMENTMANDATE:
A PaymentMandate is the final credential that authorizes payment execution. It:
- Links to the CartMandate (proving the merchant's offer)
- Records user consent
- Contains payment details extracted from the CartMandate
- Enables the actual payment transaction

This is the third and final verifiable credential in our secure payment system.

THE COMPLETE AP2 CREDENTIAL CHAIN:
1. Shopping Agent creates IntentMandate (user's intent)
2. Merchant Agent reads IntentMandate, creates CartMandate (merchant's binding offer)
3. You read CartMandate, get user confirmation, create PaymentMandate (authorized payment execution)

Each credential:
- Has an expiry time (security feature)
- Links to the previous credential
- Is validated before the next step
- Creates an auditable chain of trust""",

第 6 步:向凭证提供程序添加工具

👉 查找:

# MODULE_6_STEP_6_ADD_TOOLS
tools=[],

👉 将这两行代码替换为:

    tools=[
        FunctionTool(func=create_payment_mandate)
    ],

第 7 步:验证完整的凭据提供程序

我们来确认一下所有线路是否都已正确连接。

👉 您的完整

charity_advisor/credentials_provider/agent.py

现在应如下所示:

"""
Credentials Provider Agent - Handles payment processing with user consent.
This agent acts as our "Payment Processor."
"""

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.payment_tools import create_payment_mandate


credentials_provider = Agent(
    name="CredentialsProvider",
    model="gemini-2.5-flash",
    description="Securely processes payments by creating PaymentMandates and executing transactions with user consent.",
    tools=[
        FunctionTool(func=create_payment_mandate)
    ],
    instruction="""You are a payment specialist responsible for securely processing payments with user consent.

Your workflow:

1. Read the CartMandate from shared state.
   The CartMandate was created by the Merchant Agent and has this structure:
   - contents: AP2 wrapper containing:
     - id: Cart identifier
     - cart_expiry: When the cart expires
     - merchant_name: Who is receiving payment
     - payment_request: W3C PaymentRequest with transaction details
   - merchant_authorization: Merchant's signature

2. Extract payment details from the nested structure:
   - Navigate: cart_mandate["contents"]["payment_request"]["details"]["total"]["amount"]
   - This gives you the currency and value

3. **IMPORTANT - Two-Turn Conversational Confirmation Pattern:**
   Before calling create_payment_mandate, you MUST:
   - Present the payment details clearly to the user
   - Ask explicitly: "I'm ready to process a payment of $X to [Charity Name]. Do you want to proceed with this donation?"
   - WAIT for the user's explicit confirmation (e.g., "yes", "proceed", "confirm")
   - ONLY call create_payment_mandate AFTER receiving explicit confirmation
   - If user says "no" or "cancel", DO NOT call the tool

4. After user confirms, use the create_payment_mandate tool to:
   - Validate the CartMandate hasn't expired (CRITICAL security check)
   - Create a PaymentMandate (the third AP2 credential)
   - Simulate payment processing
   - Record the transaction result

5. After processing, inform the user:
   - That payment was processed successfully (this is a simulation)
   - The transaction ID
   - The amount and merchant
   - That this completes the three-agent AP2 credential chain

IMPORTANT BOUNDARIES:
- Your ONLY job is creating PaymentMandates and processing payments
- You do NOT discover charities (that's Shopping Agent's job)
- You do NOT create offers (that's Merchant Agent's job)
- You MUST validate that the CartMandate hasn't expired before processing
- You MUST get explicit user confirmation before calling create_payment_mandate
- In production, this consent mechanism would be even more robust

WHAT IS A PAYMENTMANDATE:
A PaymentMandate is the final credential that authorizes payment execution. It:
- Links to the CartMandate (proving the merchant's offer)
- Records user consent
- Contains payment details extracted from the CartMandate
- Enables the actual payment transaction

This is the third and final verifiable credential in our secure payment system.

THE COMPLETE AP2 CREDENTIAL CHAIN:
1. Shopping Agent creates IntentMandate (user's intent)
2. Merchant Agent reads IntentMandate, creates CartMandate (merchant's binding offer)
3. You read CartMandate, get user confirmation, create PaymentMandate (authorized payment execution)

Each credential:
- Has an expiry time (security feature)
- Links to the previous credential
- Is validated before the next step
- Creates an auditable chain of trust"""
)

✅ 检查点:您现在拥有一个完整的凭证提供程序,该提供程序能够使用 AP2 Pydantic 模型正确读取 CartMandate 并创建 PaymentMandate。

第 8 步:测试凭据提供程序

现在,我们来验证代理是否正确处理付款并完成凭证链。

👉 在 Cloud Shell 终端中,运行以下命令:

python scripts/test_credentials_provider.py

预期输出:

======================================================================
CREDENTIALS PROVIDER TEST (MOCK - NO CONFIRMATION)
======================================================================

Simulated CartMandate from Merchant Agent:
  - Cart ID: cart_test123
  - Merchant: Room to Read
  - Amount: $50.00
  - Expires: 2025-11-07T15:47:16Z
  - Signature: SIG_test_signature

Calling Credentials Provider to process payment...
======================================================================
INFO:charity_advisor.tools.payment_tools:Tool called: Creating PaymentMandate and processing payment
INFO:charity_advisor.tools.payment_tools:CartMandate valid. Expires in 900 seconds
INFO:charity_advisor.tools.payment_tools:Payment processed successfully: txn_a3f7b2c8d9e1f4a2

======================================================================
CREDENTIALS PROVIDER RESPONSE:
======================================================================
I've successfully processed your payment. Here are the details:

**Payment Completed** (Simulated)
- Transaction ID: txn_a3f7b2c8d9e1f4a2
- Amount: USD 50.00
- Merchant: Room to Read
- Status: Completed

This completes the three-agent AP2 credential chain:
1. ✓ Shopping Agent created IntentMandate (your intent)
2. ✓ Merchant Agent created CartMandate (binding offer)
3. ✓ Credentials Provider created PaymentMandate (payment authorization)

Your donation has been processed securely through our verifiable credential system.

======================================================================
PAYMENTMANDATE CREATED:
======================================================================
  Payment Mandate ID: payment_3b4c5d6e7f8a
  Linked to Cart: cart_test123
  User Consent: True
  Amount: USD 50.00
  Merchant: Room to Read
  Agent Present: True
======================================================================

======================================================================
PAYMENT RESULT:
======================================================================
  Transaction ID: txn_a3f7b2c8d9e1f4a2
  Status: completed
  Amount: USD 50.00
  Merchant: Room to Read
  Simulation: True
======================================================================

第 9 步:测试完整的三智能体流水线

现在,我们来测试一下这三个智能体协同工作的情况!

👉 运行完整流水线测试:

python scripts/test_full_pipeline.py

预期输出:

======================================================================
THREE-AGENT PIPELINE TEST (AP2 CREDENTIAL CHAIN)
======================================================================

[1/3] SHOPPING AGENT - Finding charity and creating IntentMandate...
----------------------------------------------------------------------
✓ IntentMandate created
  - Intent ID: intent_774799058_1730927536
  - Description: Donate $75.00 to Room to Read
  - Merchant: Room to Read
  - Amount: $75.0
  - Expires: 2025-11-07T16:32:16Z

[2/3] MERCHANT AGENT - Reading IntentMandate and creating CartMandate...
----------------------------------------------------------------------
✓ CartMandate created
  - ID: cart_3b4c5d6e7f8a
  - Expires: 2025-11-07T15:47:16Z
  - Signature: SIG_a3f7b2c8d9e1f4a2

[3/3] CREDENTIALS PROVIDER - Creating PaymentMandate and processing...
----------------------------------------------------------------------
NOTE: In the web UI, this would show a confirmation dialog
      For this test, consent is automatically granted
✓ Payment processed (SIMULATED)
  - Transaction ID: txn_a3f7b2c8d9e1f4a2
  - Amount: $75.0
  - Status: completed

======================================================================
COMPLETE AP2 CREDENTIAL CHAIN
======================================================================

✓ Credential 1: IntentMandate (User's Intent)
  - Intent ID: intent_774799058_1730927536
  - Description: Donate $75.00 to Room to Read
  - Expiry: 2025-11-07T16:32:16Z

✓ Credential 2: CartMandate (Merchant's Offer)
  - Cart ID: cart_3b4c5d6e7f8a
  - Cart Expiry: 2025-11-07T15:47:16Z
  - Merchant Signature: SIG_a3f7b2c8d9e1f4a2

✓ Credential 3: PaymentMandate (Payment Execution)
  - Payment Mandate ID: payment_3b4c5d6e7f8a
  - Linked to Cart: cart_3b4c5d6e7f8a
  - Agent Present: True

✓ Transaction Result:
  - Transaction ID: txn_a3f7b2c8d9e1f4a2
  - Simulation: True

======================================================================
✅ COMPLETE PIPELINE TEST PASSED
======================================================================

这就是完整的 AP2 凭证链的运作方式!

每个智能体:

  1. 从状态中读取凭据
  2. 使用 Pydantic 模型验证(结构 + 到期检查)
  3. 使用 AP2 模型创建下一个凭证
  4. 为下一个代理写入状态

您刚刚构建的内容

您已成功完成 AP2 三智能体凭证链,并使用 Pydantic 模型和付款模拟进行了正确的结构验证。

掌握的关键概念

✅ PaymentMandate(AP2 凭证 #3):

  • 使用官方 AP2 Pydantic 模型创建
  • 授权执行付款的最终凭证
  • 通过 payment_details_id 关联到 CartMandate
  • 记录用户同意情况和时间戳
  • 包含从 CartMandate 中提取的付款金额
  • 包含用于人机协同的 agent_present 标志
  • 模型验证可确保符合规范

✅ 从 CartMandate 读取:

  • 使用 CartMandate.model_validate() 验证结构
  • 类型安全的属性访问:cart_model.contents.payment_request.details.total.amount
  • 了解 AP2 封装容器与 W3C 标准分离
  • 安全地从模型中提取 merchant_name、amount、currency
  • Pydantic 会自动捕获结构错误

✅ 购物车失效验证:

  • 接受经过验证的 CartMandate Pydantic 模型
  • 从 cart.contents.cart_expiry 读取(属性访问)
  • 防止处理过期购物车的安全功能
  • 时长(15 分钟)短于意图(1 小时)

✅ 支付模拟:

  • 真实付款处理方的教学模拟
  • 生成交易 ID
  • 在 state 中记录 payment_result
  • 明确标记为模拟(simulation: True 标志)

✅ 完整的 AP2 链(包含模型):

  • 三个智能体、三个凭证、三个 Pydantic 验证
  • 每个智能体都使用模型验证前一个凭证的结构
  • 每个凭证都与上一个凭证相关联,以便进行审核跟踪记录
  • 基于状态的交接可保持角色分离
  • 整个链条中的类型安全

✅ 模型驱动开发:

  • 通过 model_validate() 进行输入验证
  • 使用嵌套模型进行类型安全构建
  • 通过 model_dump(mode='json') 自动序列化
  • 从一开始就采用可用于生产用途的模式

后续步骤

在下一个单元中,我们将构建编排器智能体,用于协调这三个专业智能体。

您已使用 AP2 Pydantic 模型构建了三个强大的专业智能体。现在,我们来构建一个“指挥家”,将这些组件协调起来,打造顺畅的捐款体验。

我们来构建编排器,看看整个系统的实际运行情况。

7. 编排 - 整合所有内容

顺序流水线

从专家到顺畅体验

在之前的单元中,您构建了三个专用智能体:

  • 导购智能体:查找慈善机构,创建 IntentMandate
  • Merchant Agent:根据 IntentMandate 创建 CartMandate
  • 凭证提供方:创建 PaymentMandate,处理付款

这些智能体自然分为两个阶段:

  • 第 1 阶段(购物):通过多轮对话查找并选择慈善机构
  • 第 2 阶段(处理):原子化执行优惠创建和付款

但目前,您必须手动协调这些阶段。

这正是 ADK 编排模式的优势所在。

AP2 原则:编排强制执行信任边界

为什么编排对安全至关重要

编排不仅是为了方便,更是为了通过架构强制执行信任边界。

不使用编排:

# User could accidentally skip steps or reorder them
shopping_agent.run("Find charity")
# Oops, forgot to create CartMandate!
credentials_provider.run("Process payment")  # No offer to validate!

使用编排:

# Pipeline enforces correct order
donation_processing_pipeline = SequentialAgent(
    sub_agents=[
        merchant_agent,      # Must run first
        credentials_provider # Must run second
    ]
)
# Steps ALWAYS run in order, no skipping allowed

顺序流水线可保证:

  • ✅ IntentMandate 创建时间早于 CartMandate
  • ✅ CartMandate created before payment processing
  • ✅ 每个智能体都在其独立的环境中运行
  • ✅ 状态在凭证链中向前流动

我们的使命:构建完整的系统

我们将构建两个层:

第 1 层:处理流水线 (SequentialAgent)

  • 将商家与凭证关联在一起
  • 选择慈善机构后,系统会自动按顺序运行
  • 原子化执行优惠和付款

第 2 层:根编排器(面向用户的智能体)

  • 性格友善
  • 委托 shopping_agent 选择慈善机构
  • 在 IntentMandate 创建后委托给处理流水线
  • 处理对话和阶段转换

这种双层方法符合自然流程:

  • 购物阶段:多轮对话(用户浏览、提问、决定)
  • 处理阶段:原子执行(优惠 → 支付)

我们来构建这两个模型。

第 1 步:导入编排组件

首先,我们来设置编排文件,并导入必要的库。

👉 开放

charity_advisor/agent.py

我们先从导入开始:

👉 查找:

# MODULE_7_STEP_1_IMPORT_COMPONENTS

👉 将该行替换为:

from google.adk.agents import Agent, SequentialAgent
from charity_advisor.shopping_agent.agent import shopping_agent
from charity_advisor.merchant_agent.agent import merchant_agent
from charity_advisor.credentials_provider.agent import credentials_provider

第 2 步:创建处理流水线

现在,我们来创建以原子方式运行优惠创建和付款处理的流水线。

👉 查找:

# MODULE_7_STEP_2_CREATE_SEQUENTIAL_PIPELINE

👉 将这两行代码替换为:

# Create the donation processing pipeline
# This runs Merchant → Credentials in sequence AFTER charity is selected
donation_processing_pipeline = SequentialAgent(
    name="DonationProcessingPipeline",
    description="Creates signed offer and processes payment after charity is selected",
    sub_agents=[
        merchant_agent,
        credentials_provider
    ]
)

第 3A 步:创建根智能体设置

现在,我们来创建面向用户的代理,用于协调这两个阶段。我们将分三个部分来构建:设置 (3A)、指令 (3B) 和子智能体 (3C)。

👉 查找:

# MODULE_7_STEP_3A_CREATE_ROOT_AGENT_SETUP

👉 将该行替换为:

# Create the root orchestrator agent
# This is what users interact with directly
root_agent = Agent(
    name="CharityAdvisor",
    model="gemini-2.5-pro",
    description="A friendly charity giving assistant that helps users donate to verified organizations.",
    # MODULE_7_STEP_3B_WRITE_ROOT_AGENT_INSTRUCTION

第 3B 步:编写根智能体指令

现在,我们来添加一条指令,用于指导慈善顾问在两个阶段的行为。

👉 查找:

# MODULE_7_STEP_3B_WRITE_ROOT_AGENT_INSTRUCTION

👉 将该行替换为:

    instruction="""You are a helpful and friendly charity giving advisor.

Your workflow has TWO distinct phases:

PHASE 1: CHARITY SELECTION (delegate to shopping_agent)
When a user expresses interest in donating:
1. Delegate to shopping_agent immediately
2. The shopping_agent will:
   - Search for charities matching their cause
   - Present verified options with ratings
   - Engage in conversation (user may ask questions, change their mind)
   - Wait for user to select a specific charity and amount
   - Create an IntentMandate when user decides
3. Wait for shopping_agent to complete

You'll know Phase 1 is complete when shopping_agent's response includes:
- "IntentMandate created" or "Intent ID: intent_xxx" 
- Charity name and donation amount

PHASE 2: PAYMENT PROCESSING (delegate to DonationProcessingPipeline)
After shopping_agent completes:
1. Acknowledge the user's selection naturally:
   "Perfect! Let me process your $X donation to [Charity]..."
2. Delegate to DonationProcessingPipeline
3. The pipeline will automatically:
   - Create signed cart offer (MerchantAgent)
   - Get consent and process payment (CredentialsProvider)
4. After pipeline completes, summarize the transaction

CRITICAL RULES:
- Phase 1 may take multiple conversation turns (this is normal)
- Only proceed to Phase 2 after IntentMandate exists
- Don't rush the user during charity selection
- Don't ask user to "proceed" between phases - transition automatically

EXAMPLE FLOW:
User: "I want to donate to education"
You: [delegate to shopping_agent]
Shopping: "Here are 3 education charities..." [waits]
User: "Tell me more about the first one"
Shopping: "Room to Read focuses on..." [waits]
User: "Great, I'll donate $50 to Room to Read"
Shopping: "IntentMandate created (ID: intent_123)..."
You: "Perfect! Processing your $50 donation to Room to Read..." [delegate to DonationProcessingPipeline]
Pipeline: [creates offer, gets consent, processes payment]
You: "Done! Your donation was processed successfully. Transaction ID: txn_456"

Your personality:
- Warm and encouraging
- Patient during charity selection
- Clear about educational nature
- Smooth transitions between phases""",
# MODULE_7_STEP_3C_ADD_ROOT_AGENT_SUBAGENTS

第 3C 步:添加子代理

最后,我们向慈善顾问授予对导购智能体和处理流水线的访问权限,然后关闭智能体定义。

👉 查找:

# MODULE_7_STEP_3C_ADD_ROOT_AGENT_SUBAGENTS

👉 将该行替换为:

    sub_agents=[
        shopping_agent,
        donation_processing_pipeline
    ]
)

第 4 步:验证整个系统

我们来确认一下编排是否已正确连接。

👉 您的完整

charity_advisor/agent.py

现在应如下所示:

"""
Main orchestration: The donation processing pipeline and root orchestrator agent.
"""

from google.adk.agents import Agent, SequentialAgent
from charity_advisor.shopping_agent.agent import shopping_agent
from charity_advisor.merchant_agent.agent import merchant_agent
from charity_advisor.credentials_provider.agent import credentials_provider

# Create the donation processing pipeline
# This runs Merchant → Credentials in sequence AFTER charity is selected
donation_processing_pipeline = SequentialAgent(
    name="DonationProcessingPipeline",
    description="Creates signed offer and processes payment after charity is selected",
    sub_agents=[
        merchant_agent,
        credentials_provider
    ]
)

# Create the root orchestrator agent
# This is what users interact with directly
root_agent = Agent(
    name="CharityAdvisor",
    model="gemini-2.5-flash",
    description="A friendly charity giving assistant that helps users donate to verified organizations.",
    instruction="""You are a helpful and friendly charity giving advisor.

Your workflow has TWO distinct phases:

PHASE 1: CHARITY SELECTION (delegate to shopping_agent)
When a user expresses interest in donating:
1. Delegate to shopping_agent immediately
2. The shopping_agent will:
   - Search for charities matching their cause
   - Present verified options with ratings
   - Engage in conversation (user may ask questions, change their mind)
   - Wait for user to select a specific charity and amount
   - Create an IntentMandate when user decides
3. Wait for shopping_agent to complete

You'll know Phase 1 is complete when shopping_agent's response includes:
- "IntentMandate created" or "Intent ID: intent_xxx" 
- Charity name and donation amount

PHASE 2: PAYMENT PROCESSING (delegate to DonationProcessingPipeline)
After shopping_agent completes:
1. Acknowledge the user's selection naturally:
   "Perfect! Let me process your $X donation to [Charity]..."
2. Delegate to DonationProcessingPipeline
3. The pipeline will automatically:
   - Create signed cart offer (MerchantAgent)
   - Get consent and process payment (CredentialsProvider)
4. After pipeline completes, summarize the transaction

CRITICAL RULES:
- Phase 1 may take multiple conversation turns (this is normal)
- Only proceed to Phase 2 after IntentMandate exists
- Don't rush the user during charity selection
- Don't ask user to "proceed" between phases - transition automatically

EXAMPLE FLOW:
User: "I want to donate to education"
You: [delegate to shopping_agent]
Shopping: "Here are 3 education charities..." [waits]
User: "Tell me more about the first one"
Shopping: "Room to Read focuses on..." [waits]
User: "Great, I'll donate $50 to Room to Read"
Shopping: "IntentMandate created (ID: intent_123)..."
You: "Perfect! Processing your $50 donation to Room to Read..." [delegate to DonationProcessingPipeline]
Pipeline: [creates offer, gets consent, processes payment]
You: "Done! Your donation was processed successfully. Transaction ID: txn_456"

Your personality:
- Warm and encouraging
- Patient during charity selection
- Clear about educational nature
- Smooth transitions between phases""",
    sub_agents=[
        shopping_agent,
        donation_processing_pipeline
    ]
)

第 5 步:使用验证回调进行强化(可选,可跳至第 7 步)

callbacks

SequentialAgent 可保证执行顺序,但如果出现以下情况,该怎么办:

  • 导购智能体静默失败(IntentMandate 始终未创建)
  • 购物和商家之间经过了一个小时(意向过期)
  • 状态损坏或被清除
  • 有人试图绕过 Google 购物,直接致电商家

回调可强制执行架构规则 - 它们会在智能体开始 LLM 调用之前验证前提条件。这就是纵深防御:工具在执行期间进行验证,回调在执行之前进行验证。

我们来为 Merchant 和 Credentials Provider 代理添加验证回调。

第 5A 步:添加商家验证 - 导入回调类型

首先,我们来添加回调所需的导入。

👉 开放

charity_advisor/merchant_agent/agent.py

在文件顶部,在现有导入之后添加:

from typing import Optional
from datetime import datetime, timezone
from google.adk.agents.callback_context import CallbackContext
from google.genai.types import Content, Part
import logging

logger = logging.getLogger(__name__)

第 5B 步:构建 intent 验证函数

现在,我们来创建一个回调函数,用于在 Merchant Agent 运行之前验证 IntentMandate。

👉 In

charity_advisor/merchant_agent/agent.py

,请在 之前添加此函数

merchant_agent = Agent(...)

定义:

def validate_intent_before_merchant(
    callback_context: CallbackContext,
) -> Optional[Content]:
    """
    Validates IntentMandate exists and hasn't expired before Merchant runs.
    
    This callback enforces that the Shopping Agent completed successfully
    before the Merchant Agent attempts to create a CartMandate.
    
    Returns:
        None: Allow Merchant Agent to proceed normally
        Content: Skip Merchant Agent and return error to user
    """
    state = callback_context.state
    
    # Check credential exists
    if "intent_mandate" not in state:
        logger.error("❌ IntentMandate missing - Shopping Agent may have failed")
        return Content(parts=[Part(text=(
            "Error: Cannot create cart. User intent was not properly recorded. "
            "Please restart the donation process."
        ))])
    
    intent_mandate = state["intent_mandate"]
    
    # Validate expiry (critical security check)
    try:
        expiry_time = datetime.fromisoformat(
            intent_mandate["intent_expiry"].replace('Z', '+00:00')
        )
        now = datetime.now(timezone.utc)
        
        if expiry_time < now:
            logger.error(f"❌ IntentMandate expired at {intent_mandate['intent_expiry']}")
            return Content(parts=[Part(text=(
                "Error: Your donation intent has expired. "
                "Please select a charity again to restart."
            ))])
        
        time_remaining = expiry_time - now
        logger.info(f"✓ IntentMandate validated. Expires in {time_remaining.total_seconds():.0f}s")
        
    except (KeyError, ValueError) as e:
        logger.error(f"❌ Invalid IntentMandate structure: {e}")
        return Content(parts=[Part(text=(
            "Error: Invalid intent data. Please restart the donation."
        ))])
    
    # All checks passed - allow Merchant Agent to proceed
    logger.info(f"✓ Prerequisites met for Merchant Agent: {intent_mandate['intent_id']}")
    return None

第 5C 步:将回调附加到商家代理

现在,我们将回调连接到智能体。

👉 In

charity_advisor/merchant_agent/agent.py

,修改

merchant_agent = Agent(...)

定义:

在智能体定义中找到以下行:

merchant_agent = Agent(
    name="MerchantAgent",
    model="gemini-2.5-flash",
    description="Creates formal, signed CartMandates for charity donations following W3C PaymentRequest standards.",

在 后面添加以下代码行

description

line:

    before_agent_callback=validate_intent_before_merchant,

您的智能体定义现在应如下所示:

merchant_agent = Agent(
    name="MerchantAgent",
    model="gemini-2.5-flash",
    description="Creates formal, signed CartMandates for charity donations following W3C PaymentRequest standards.",
    before_agent_callback=validate_intent_before_merchant,
    tools=[
        FunctionTool(func=create_cart_mandate)
    ],
    instruction="""..."""
)

第 6 步:添加凭证提供方验证(可选,跳至第 7 步)

同样的模式 - 我们来为付款步骤添加验证。

第 6A 步:导入回调类型

👉 开放

charity_advisor/credentials_provider/agent.py

在文件顶部,在现有导入之后添加:

from typing import Optional
from datetime import datetime, timezone
from google.adk.agents.callback_context import CallbackContext
from google.genai.types import Content, Part
import logging

logger = logging.getLogger(__name__)

第 6B 步:构建购物车验证函数

👉 In

charity_advisor/credentials_provider/agent.py

,请在 之前添加此函数

credentials_provider = Agent(...)

定义:

def validate_cart_before_payment(
    callback_context: CallbackContext,
) -> Optional[Content]:
    """
    Validates CartMandate exists and hasn't expired before payment processing.
    
    This callback enforces that the Merchant Agent completed successfully
    before the Credentials Provider attempts to process payment.
    
    Returns:
        None: Allow Credentials Provider to proceed
        Content: Skip payment processing and return error
    """
    state = callback_context.state
    
    # Check credential exists
    if "cart_mandate" not in state:
        logger.error("❌ CartMandate missing - Merchant Agent may have failed")
        return Content(parts=[Part(text=(
            "Error: Cannot process payment. Cart was not properly created. "
            "Please restart the donation process."
        ))])
    
    cart_mandate = state["cart_mandate"]
    
    # Validate AP2 structure
    if "contents" not in cart_mandate:
        logger.error("❌ CartMandate missing AP2 contents wrapper")
        return Content(parts=[Part(text=(
            "Error: Invalid cart structure. Please restart."
        ))])
    
    # Validate expiry
    try:
        contents = cart_mandate["contents"]
        expiry_time = datetime.fromisoformat(
            contents["cart_expiry"].replace('Z', '+00:00')
        )
        now = datetime.now(timezone.utc)
        
        if expiry_time < now:
            logger.error(f"❌ CartMandate expired at {contents['cart_expiry']}")
            return Content(parts=[Part(text=(
                "Error: Your cart has expired (15 minute limit). "
                "Please restart the donation to get a fresh offer."
            ))])
        
        time_remaining = expiry_time - now
        logger.info(f"✓ CartMandate validated. Expires in {time_remaining.total_seconds():.0f}s")
        
    except (KeyError, ValueError) as e:
        logger.error(f"❌ Invalid CartMandate structure: {e}")
        return Content(parts=[Part(text=(
            "Error: Invalid cart data. Please restart the donation."
        ))])
    
    # All checks passed - allow payment processing
    logger.info(f"✓ Prerequisites met for Credentials Provider: {contents['id']}")
    return None

第 6C 步:将回调附加到凭证提供程序

👉 In

charity_advisor/credentials_provider/agent.py

,修改

credentials_provider = Agent(...)

定义:

在智能体定义中找到以下行:

credentials_provider = Agent(
    name="CredentialsProvider",
    model="gemini-2.5-flash",
    description="Securely processes payments by creating PaymentMandates and executing transactions with user consent.",

在 后面添加以下代码行

description

line:

    before_agent_callback=validate_cart_before_payment,

您的智能体定义现在应如下所示:

credentials_provider = Agent(
    name="CredentialsProvider",
    model="gemini-2.5-flash",
    description="Securely processes payments by creating PaymentMandates and executing transactions with user consent.",
    before_agent_callback=validate_cart_before_payment,
    tools=[
        FunctionTool(func=create_payment_mandate)
    ],
    instruction="""..."""
)

第 7 步:使用 ADK Web 界面进行测试

现在,让我们在启用验证回调的情况下测试完整的加固系统。

👉 在 Cloud Shell 终端中,运行以下命令:

adk web

您应该会看到如下所示的输出:

+-----------------------------------------------------------------------------+
| ADK Web Server started                                                      |
|                                                                             |
| For local testing, access at http://localhost:8000.                         |
+-----------------------------------------------------------------------------+

INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)

👉 接下来,如需从浏览器访问 ADK Web 界面,请执行以下操作:

在 Cloud Shell 工具栏(通常位于右上角)中,点击网页预览图标(形似眼睛或带箭头的正方形),然后选择更改端口。在弹出式窗口中,将端口设置为 8000,然后点击“更改并预览”。然后,Cloud Shell 会打开一个新的浏览器标签页,其中显示 ADK Web 界面。

webpreview

👉 从下拉菜单中选择您的智能体:

在 ADK 网页界面中,您会在顶部看到一个下拉菜单。从列表中选择 charity_advisor。

agent-select

您将看到 ADK 网页界面,其中包含:

  • “对话”面板:左侧,用于对话
  • “跟踪记录”面板:右侧,用于可观测性(我们将在第 9 单元中使用此面板)

测试 1:完整捐赠流程(正常情况)

👉 在对话界面中,输入:

I want to donate to an education charity

观看完整流程:

adk web shopping agent

ADK 网页捐款处理流水线

具体情况(在右侧的跟踪面板中可见):

1. Advisor 委托给 ShoppingAgent:

  • ShoppingAgent 搜索教育慈善机构
  • 显示 3 个经过验证的选项及详细信息

2. 您与 ShoppingAgent 互动(可能需要多轮对话):

User: "Tell me more about Room to Read"
Shopping: [explains mission and impact]
User: "I'll donate $50 to Room to Read"

3. ShoppingAgent 创建 IntentMandate:

  • 创建并签署 intent
  • 返回确认信息和 intent ID

4. Advisor 转换为处理阶段:

太好了!正在处理您向 Room to Read 捐赠的 50 美元…

5. DonationProcessingPipeline 激活:

  • 商家回调验证 IntentMandate(✓ 通过) ← 新增!
  • 商家代理创建 CartMandate 并签名
  • Credentials callback validates CartMandate (✓ passed) ← 新增!
  • 凭证提供程序准备付款

6. 付款处理:

  • 凭证提供方创建 PaymentMandate
  • 模拟付款处理
  • 退货交易 ID

7. Advisor 总结:

太好了!您的捐款已成功处理!🎉

详细信息:

  • 金额:50.00 美元
  • 慈善机构:Room to Read(EIN:77-0479905)
  • 交易 ID:txn_a3f7b2c8d9e1f4a2

测试 2:验证回调是否能捕获失败(可选高级测试)

想看看回调在捕获错误时的实际效果吗?您需要手动破坏状态(高级调试),但在生产环境中,回调会捕获:

  • 导购智能体工具失败 → 商家回调屏蔽:“错误:无法创建购物车…”
  • 2 小时后 → 商家回调屏蔽:“错误:意图已过期…”
  • 购物车过期 → 凭证回调块:“错误:购物车已过期(15 分钟限制)…”

现在,这些极端情况会通过验证回调在架构上强制执行。

您刚刚构建的内容

您已成功将三个专用智能体编排成一个无缝、可靠的系统,并完成了架构验证。

后续步骤

您现已完成构建可信赖智能体的核心技术部分:

您已在本地构建了一个强制执行凭证链的完整可信系统。现在,我们通过生产部署让真实用户能够访问该应用,并启用责任跟踪,为第 9 单元做好准备。

让我们将强化后的智能体部署到 Google Cloud。

8. 部署

横幅

现在,您已成功构建一个值得信赖的捐赠系统,其中包含三个在本地运行的专用智能体:

但它只能在您的开发机器上运行。为了让此系统对真实用户有用,并捕获证明可信度的问责跟踪记录,您需要将其部署到生产环境。

本单元将引导您将智能体部署到 Google Cloud,并从第一天起就启用可观测性。您在部署期间使用的 --trace_to_cloud 标志可让您在第 9 单元中实现问责跟踪。

了解部署选项

ADK 支持多个部署目标。每种方法在复杂性、会话管理、扩缩和费用方面都有不同的特点:

因素

本地 (adk web)

Agent Engine

Cloud Run

复杂性

最小

低

中

会话持久性

仅保存在内存中(重启后数据丢失)

Vertex AI 托管(自动)

Cloud SQL (PostgreSQL) 或内存

基础架构

无(仅限开发机器)

全代管式

容器 + 可选数据库

冷启动

不适用

100-500 毫秒

100-2000 毫秒

扩缩

单一实例

自动

自动(至零)

费用模型

免费(本地计算)

基于计算

基于请求 + 免费层级

界面支持

是(内置)

否(仅限 API)

是(通过 --with_ui 标志)

可观测性设置

本地跟踪记录查看器

使用--trace_to_cloud自动

需要 --trace_to_cloud 标志

适用场景

开发和测试

生产智能体

生产智能体

建议:对于这个值得信赖的捐赠系统,我们建议您将 Agent Engine 作为主要生产部署,因为它具有以下优势:

  • 全托管式基础架构(无需管理容器)
  • 通过 VertexAiSessionService 实现内置会话持久性
  • 自动扩缩,无冷启动
  • 简化部署(无需具备 Docker 相关知识)
  • 开箱即用的 Cloud Trace 集成

其他选项:Google Kubernetes Engine (GKE)

对于需要 Kubernetes 级控制、自定义网络或多服务编排的高级用户,可以使用 GKE 部署。此选项可提供最大的灵活性,但需要更多运维专业知识(集群管理、清单、服务账号)。

本 Codelab 不涉及 GKE 部署,但 ADK GKE 部署指南中对此进行了完整介绍。

前提条件

1. Google Cloud 项目设置

您需要一个启用了结算功能的 Google Cloud 项目。如果您没有,请执行以下操作:

  1. 创建项目:Google Cloud 控制台
  2. 启用结算功能:启用结算功能
  3. 记下您的项目 ID(而非项目名称或编号)

2. 重新进行身份验证(可选)

向 Google Cloud 进行身份验证:

gcloud auth application-default login
gcloud config set project YOUR_PROJECT_ID

将 YOUR_PROJECT_ID 替换为您的实际 Google Cloud 项目 ID。

验证您的身份验证:

gcloud config get-value project
# Should output: YOUR_PROJECT_ID

3. 环境变量

使用以下命令自动填充 .env 文件:

# Get your current Project ID
PROJECT_ID=$(gcloud config get-value project)
STAGING_BUCKET_VALUE="gs://${PROJECT_ID}-staging"
ENV_FILE=".env"

# Check if STAGING_BUCKET is already set in the .env file
if grep -q "^STAGING_BUCKET=" "${ENV_FILE}"; then
  # If it exists, replace the line
  # The sed command finds the line starting with STAGING_BUCKET= and replaces the entire line.
  # Using | as a delimiter to avoid issues with slashes in the bucket name.
  sed -i "s|^STAGING_BUCKET=.*|STAGING_BUCKET=${STAGING_BUCKET_VALUE}|" "${ENV_FILE}"
  echo "Updated STAGING_BUCKET in ${ENV_FILE}"
else
  # If it doesn't exist, add it to the end of the file
  echo "STAGING_BUCKET=${STAGING_BUCKET_VALUE}" >> "${ENV_FILE}"
  echo "Added STAGING_BUCKET to ${ENV_FILE}"
fi

# Verify it was added or updated correctly
echo "Current STAGING_BUCKET setting:"
grep "^STAGING_BUCKET=" "${ENV_FILE}"

您应该会看到:

STAGING_BUCKET=gs://your-actual-project-id-staging

重要说明:

  • 将 YOUR_PROJECT_ID 替换为您的实际项目 ID(或使用上述命令)
  • 对于 GOOGLE_CLOUD_LOCATION,请使用受支持的国家/地区
  • 如果暂存存储桶不存在,则在您运行部署脚本时,系统会自动创建该存储桶

4. 启用必需的 API

部署过程需要启用多个 Google Cloud API。运行以下命令以启用这些 API:

gcloud services enable \
    aiplatform.googleapis.com \
    storage.googleapis.com \
    cloudbuild.googleapis.com \
    cloudtrace.googleapis.com \
    compute.googleapis.com

此命令会启用:

  • AI Platform API - 适用于 Agent Engine 和 Vertex AI 模型
  • Cloud Storage API - 适用于暂存存储桶
  • Cloud Build API - 用于容器构建 (Cloud Run)
  • Cloud Trace API - 用于可观测性和问责跟踪
  • Compute Engine API - 用于服务账号管理

第 1 步:了解部署基础架构

您的项目包含一个统一的部署脚本 (deploy.sh),该脚本可处理所有部署模式。

👉 查看部署脚本(可选):

cat deploy.sh

该脚本提供三种部署模式:

  • ./deploy.sh local - 在本地运行,使用内存中存储
  • ./deploy.sh agent-engine - 部署到 Vertex AI Agent Engine(推荐)
  • ./deploy.sh cloud-run - 部署到 Cloud Run(可选界面)

底层工作原理:

对于 Agent Engine 部署,脚本会执行以下操作:

adk deploy agent_engine \
  --project=$GOOGLE_CLOUD_PROJECT \
  --region=$GOOGLE_CLOUD_LOCATION \
  --staging_bucket=$STAGING_BUCKET \
  --display_name="Charity Advisor" \
  --trace_to_cloud \
  charity_advisor

对于 Cloud Run 部署,它会执行:

adk deploy cloud_run \
  --project=$GOOGLE_CLOUD_PROJECT \
  --region=$GOOGLE_CLOUD_LOCATION \
  --service_name="charity-advisor" \
  --app_name="charity_advisor" \
  --with_ui \
  --trace_to_cloud \
  charity_advisor

--trace_to_cloud 标志对于这两种部署类型都至关重要,它可启用 Cloud Trace 集成,以便您在第 9 单元中探索问责跟踪。

第 2 步:准备智能体引擎封装容器

Agent Engine 需要一个特定的入口点,用于为托管式运行时封装智能体。系统已为您创建此文件。

👉 审核

charity_advisor/agent_engine_app.py

:

"""Agent Engine application wrapper.

This file prepares the Charity Advisor agent for deployment to Vertex AI Agent Engine.
"""

from vertexai import agent_engines
from .agent import root_agent

# Wrap the agent in an AdkApp object for Agent Engine deployment
app = agent_engines.AdkApp(
    agent=root_agent,
    enable_tracing=True,  # Enables Cloud Trace integration automatically
)

为什么需要此文件:

  • Agent Engine 要求将智能体封装在 AdkApp 对象中
  • enable_tracing=True 参数会自动启用 Cloud Trace 集成
  • ADK CLI 在部署期间会引用此封装容器
  • 它会配置 VertexAiSessionService 以实现会话自动持久化

Agent Engine 是推荐的生产部署,可用于构建值得信赖的捐赠系统,因为它提供了具有内置会话持久性的全托管式基础设施。

运行 Deployment

在项目根目录中:

chmod +x deploy.sh
./deploy.sh agent-engine

部署阶段

观察脚本执行以下阶段:

Phase 1: API Enablement
  ✓ aiplatform.googleapis.com
  ✓ storage.googleapis.com
  ✓ cloudbuild.googleapis.com
  ✓ cloudtrace.googleapis.com
  ✓ compute.googleapis.com

Phase 2: IAM Setup
  ✓ Getting project number
  ✓ Granting Storage Object Admin
  ✓ Granting Vertex AI User
  ✓ Granting Cloud Trace Agent

Phase 3: Staging Bucket
  ✓ Creating gs://your-project-id-staging (if needed)
  ✓ Setting permissions

Phase 4: Validation
  ✓ Checking agent.py exists
  ✓ Verifying root_agent defined
  ✓ Checking agent_engine_app.py exists
  ✓ Validating requirements.txt

Phase 5: Build & Deploy
  ✓ Packaging agent code
  ✓ Uploading to staging bucket
  ✓ Creating Agent Engine instance
  ✓ Configuring session persistence
  ✓ Setting up Cloud Trace integration
  ✓ Running health checks

此过程需要 5-10 分钟,因为它会打包代理并将其部署到 Vertex AI 基础设施。

保存 Agent Engine ID

成功部署后:

✅ Agent Engine created successfully!

   Agent Engine ID: 7917477678498709504
   Resource Name: projects/123456789/locations/us-central1/reasoningEngines/7917477678498709504
   Endpoint: https://us-central1-aiplatform.googleapis.com/v1/...

   ⚠️  IMPORTANT: Save the Agent Engine ID from the output above
   Add it to your .env file as:
   AGENT_ENGINE_ID=7917477678498709504

   This ID is required for:
   - Testing the deployed agent
   - Updating the deployment later
   - Accessing logs and traces

立即更新 .env 文件:

echo "AGENT_ENGINE_ID=7917477678498709504" >> .env

部署的内容

您的 Agent Engine 部署现在包含:

✅ 所有三个智能体(购物、商家、凭证)均在托管式运行时中运行
✅ 完整的凭证链逻辑(Intent → Cart → Payment 授权)
✅ 用户同意机制,具有确认工作流
✅ 自动会话持久化,通过 VertexAiSessionService 实现
✅ 自动扩缩基础设施,由 Google 管理
✅ Cloud Trace 集成,实现完整的可观测性

第 4 步:测试已部署的智能体

更新环境

验证您的 .env 是否包含 Agent Engine ID:

AGENT_ENGINE_ID=7917477678498709504  # From deployment output
GOOGLE_CLOUD_PROJECT=your-project-id
GOOGLE_CLOUD_LOCATION=us-central1
STAGING_BUCKET=gs://your-project-id-staging

运行测试脚本

您的项目包含一个专门用于 Agent Engine 部署的测试脚本。

👉 运行测试:

python scripts/test_deployed_agent.py

预期输出

Testing Agent Engine deployment...
Project: your-project-id
Location: us-central1
Agent Engine ID: 7917477678498709504
Endpoint: https://us-central1-aiplatform.googleapis.com/v1/...

Creating session...
✓ Session created: 4857885913439920384

Sending donation query...
✓ Response received:
  Event 1: I'll help you donate $50 to a children's education charity...
  Event 2: Here are some highly-rated children's education charities...
  Event 3: Which charity would you like to support?...

✅ Test completed successfully!

Session ID: 4857885913439920384

This donation generated a trace in Cloud Trace.
View it in Module 9: Observability

To view traces:
https://console.cloud.google.com/traces/list?project=your-project-id

验证核对清单

测试后,请验证:

✅ 代理会回答查询
✅ 所有三个代理会按顺序执行(购物 → 商家 → 凭证)
✅ 意见征求机制会激活(请求确认)
✅ 会话会在请求之间保持
✅ 没有身份验证错误
✅ 没有连接超时

如果您遇到错误:

  • 检查环境变量是否设置正确
  • 验证 API 是否已启用:gcloud services list --enabled
  • 在 Vertex AI 控制台中查看 Agent Engine 日志
  • 验证 agent_engine_app.py 文件是否存在于 charity_advisor 文件夹中

第 5 步:部署到 Cloud Run(可选)

虽然我们建议使用 Agent Engine 来简化生产部署,但 Cloud Run 可提供更多控制选项,并支持 ADK Web 界面。此部分为可选。

何时使用 Cloud Run

如果您需要以下功能,请选择 Cloud Run:

  • 用于用户互动的 ADK 网页界面
  • 完全控制容器环境
  • 自定义数据库配置
  • 与现有 Cloud Run 服务集成

运行 Deployment

chmod +x deploy.sh
./deploy.sh cloud-run

不同之处:

该脚本将自动执行以下操作:

  • 使用代理代码构建 Docker 容器
  • 创建 Cloud SQL PostgreSQL 数据库(如果需要)
  • 配置数据库连接
  • 在启用 ADK 网页界面的情况下进行部署

由于 Cloud SQL 预配,部署需要 10-15 分钟。

会话管理:

  • 使用 DatabaseSessionService,而不要使用 VertexAiSessionService
  • 需要 .env 中的数据库凭据(或自动生成的凭据)
  • 状态会保留在 PostgreSQL 数据库中

界面支持:

  • Web 界面网址:https://charity-advisor-xyz.a.run.app

测试 Cloud Run 部署

如果您使用 --with_ui 部署到 Cloud Run,则可以直接在浏览器中进行测试:

  1. 前往您的服务网址(在部署输出中提供)
  2. 您会看到 ADK 网页界面。从下拉菜单中选择您的代理。
  3. 开始测试捐赠:
   I want to donate $50 to a children's education charity
  1. 观察执行流程:
    • ShoppingAgent 找到慈善机构并保存您的意图
    • MerchantAgent 创建购物车授权书
    • CredentialsProvider 创建支付授权并请求确认
    • 您确认后,系统会处理付款
  2. 验证响应是否包含:
    • 慈善机构推荐
    • 确认请求
    • 获得批准后显示的成功消息

问题排查

常见问题

问题:ERROR: GOOGLE_CLOUD_PROJECT is not set

解决方案:确保 .env 文件包含正确的项目 ID:

GOOGLE_CLOUD_PROJECT=your-actual-project-id

问题:未自动创建暂存存储桶

解决方案:脚本应自动创建存储桶。如果没有,请手动创建:

gsutil mb -p $GOOGLE_CLOUD_PROJECT -l $GOOGLE_CLOUD_LOCATION $STAGING_BUCKET

摘要

您已成功:

✅ 了解了 deploy.sh 提供的部署基础设施
✅ 检查了 Agent Engine 封装容器配置
✅ 将可信捐赠系统部署到了 Agent Engine(推荐)
✅ 启用了 Cloud Trace 与 --trace_to_cloud 的集成
✅ 验证了智能体可访问且正常运行
✅ 为第 9 单元中的问责跟踪奠定了基础

在下一个单元中,您将看到此标志的具体作用:让您能够全面了解每项捐赠、每个征求意见时刻以及凭证链的每个步骤。

9. 可观测性

横幅

图表跟踪

在第 1 单元中,您了解了一个根本性问题:当 AI 智能体处理资金时,您如何证明发生了什么?

用户可能会声称:

  • “我从未选择过该慈善机构!”
  • “我没有授权那笔付款!”
  • “系统在未经我同意的情况下向我收取了费用!”

在传统的黑盒 AI 系统中,您无法证明并非如此。但您值得信赖的捐赠系统却与众不同。在第 8 单元中,您在部署时使用了 --trace_to_cloud 标志,这意味着现在每次捐赠都会在 Cloud Trace 中创建完整的、防篡改的审核跟踪记录。

本单元将教您如何读取这些跟踪记录并将其用作证据。您将学会:

  • 浏览 Cloud Trace Explorer 以查找生产跟踪记录
  • 阅读瀑布视图以了解执行流程
  • 查找凭证链(Intent → Cart → Payment mandates)
  • 通过时间戳证明找到用户同意时刻
  • 使用跟踪记录解决争议
  • 导出跟踪记录以用于合规性和审核

这就是可信系统与能力强大但不够透明的系统之间的区别:能够以法证级的精确度证明所发生的事情。

了解跟踪记录和 span

在 Cloud Trace 中查看跟踪记录之前,您需要了解所查看的内容。

什么是 Trace?

跟踪记录是智能体处理单个请求的完整时间轴。它会捕获从用户发送查询到最终回答交付的整个过程。

每个跟踪记录都会显示:

  • 请求的总时长
  • 已执行的所有操作
  • 操作之间的关系(父子关系)
  • 每项操作的开始时间和结束时间
  • 成功或失败状态

对于慈善代理:一个跟踪记录 = 一个完整的捐款流程,从“我想捐款”到“付款成功”。

什么是 Span?

span 表示跟踪记录中的单个工作单元。您可以将 span 视为跟踪记录的组成要素。

捐赠系统中的常见 span 类型:

Span 类型

代表对象

示例

agent_run

智能体的执行

ShoppingAgent.run、MerchantAgent.run

call_llm

向语言模型发出的请求

gemini-2.5-flash 项慈善机构选择请求

execute_tool

工具函数执行

find_charities、create_payment_mandate

state_read

正在读取会话记忆

正在从状态中检索 intent_mandate

state_write

写入会话内存

在状态中存储 cart_mandate

每个 span 都包含:

  • 名称:此操作代表什么
  • 耗时(开始时间 → 结束时间)
  • 属性:元数据,例如工具输入、模型回答、词元数量
  • 状态:成功 (OK) 或错误 (ERROR)
  • 父子关系:哪些操作触发了哪些操作

Span 如何形成 Trace

Span 相互嵌套以显示因果关系:

Root Span: CharityAdvisor.run (entire request)
  └─ Child: DonationPipeline.run (sequential workflow)
      ├─ Child: ShoppingAgent.run
      │   ├─ Grandchild: call_llm (Gemini processes charity search)
      │   ├─ Grandchild: execute_tool (find_charities)
      │   └─ Grandchild: execute_tool (save_user_choice)
      ├─ Child: MerchantAgent.run
      │   ├─ Grandchild: call_llm (Gemini generates cart)
      │   └─ Grandchild: execute_tool (create_cart_mandate)
      └─ Child: CredentialsProvider.run
          ├─ Grandchild: call_llm (Gemini processes payment)
          └─ Grandchild: execute_tool (create_payment_mandate) [CONSENT!]

此层次结构会显示具体发生了什么以及发生的顺序。您可以看到,支付授权是在购物车授权之后创建的,而购物车授权是在用户选择慈善机构之后创建的。

第 1 步:访问 Cloud Trace Explorer

现在,我们来查看已部署智能体的实际跟踪记录。

  1. 打开 Google Cloud 控制台:console.cloud.google.com
  2. 从顶部的下拉菜单中选择您的项目(如果您一直在该项目中工作,则应该已预先选中)
  3. 前往 Cloud Trace Explorer:

您看到的内容

Trace Explorer 会显示项目中的所有跟踪记录:

列

显示的数据

请求

HTTP 方法和端点(适用于 API 请求)

开始时间

请求开始的时间

延迟时间

请求的总时长

Span

跟踪记录中的操作数量

每行代表向已部署的智能体发出的一个完整请求。

生成测试跟踪记录(如果需要)

如果您尚未看到任何跟踪记录,则列表可能为空,原因如下:

  • 尚未向您部署的智能体发出任何请求
  • 跟踪记录在请求后需要 1-2 分钟才会显示

生成测试跟踪记录:

如果您通过界面部署到 Cloud Run,请访问您的服务网址,然后在浏览器中完成捐款。

如果您部署到了 Agent Engine,请运行第 8 单元中的测试脚本:

python scripts/test_deployed_agent.py

等待 1-2 分钟,然后刷新 Cloud Trace 探索器页面。现在,您应该会看到跟踪记录。

过滤跟踪记录

使用顶部的过滤选项查找特定跟踪记录:

  • 时间范围:根据需要从“过去一小时”更改为“过去 24 小时”
  • 最短延迟时间/最长延迟时间:过滤出速度较慢的请求
  • 请求过滤条件:按特定操作(例如“DonationPipeline”)搜索

在本单元中,请重点关注时长较长(>5 秒)的跟踪记录,因为这些跟踪记录代表三个智能体全部执行的完整捐赠流程。

第 2 步:检查完整的捐赠流程

点击列表中的任意跟踪记录,即可打开瀑布视图。您将在此处花费大部分时间来分析代理行为。

了解瀑布视图

瀑布视图是一个甘特图,显示了完整的执行时间轴:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              Timeline (horizontal = time) →
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

invocation                           ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 8.2s
  agent_run: CharityAdvisor          ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 8.1s
    agent_run: DonationPipeline      ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 7.9s
      agent_run: ShoppingAgent       ▓▓▓▓▓▓ 2.1s
        call_llm: gemini-2.5-flash   ▓▓▓▓ 1.2s
        execute_tool: find_charities ▓▓ 0.5s
        execute_tool: save_user_choice ▓ 0.3s
      agent_run: MerchantAgent       ▓▓▓ 1.8s
        call_llm: gemini-2.5-flash   ▓▓ 0.9s
        execute_tool: create_cart_mandate ▓ 0.7s
      agent_run: CredentialsProvider ▓▓▓▓▓▓▓▓ 4.0s
        call_llm: gemini-2.5-flash   ▓▓ 0.8s
        execute_tool: create_payment_mandate ▓▓▓▓▓ 3.0s [CONSENT]

解读图表

每个条形代表一个 span:

  • 水平位置:问题开始时间
  • 时长:所用时间
  • 缩进:显示父子关系
  • 颜色:通常情况下,蓝色表示正常,红色表示错误

此示例跟踪记录的主要观察结果:

✅ 总时长:8.2 秒
✅ 依序执行:ShoppingAgent 在 MerchantAgent 启动之前完成
✅ MerchantAgent 已完成

before

CredentialsProvider 已启动
✅ 同意是最耗时的操作:create_payment_mandate 耗时 3.0 秒(因为它在等待用户确认)
✅ LLM 调用可见:每个智能体都发出了一次 Gemini 请求
✅ 工具调用已捕获:所有六个工具均已成功执行

此可视化图表会立即显示时间花在何处以及操作执行的顺序。

点击 span 可查看详细信息

点击 invocation span(顶部的根 span)。在右侧面板中,您会看到详细属性:

{
  "http.method": "POST",
  "http.status_code": 200,
  "http.url": "https://charity-advisor-xyz.a.run.app/api/run",
  "user_id": "test_user_123",
  "session_id": "4857885913439920384",
  "trace_id": "a1b2c3d4e5f6...",
  "span_id": "1234567890abcdef"
}

这些属性提供有关整个请求的上下文。

第 3 步:查找凭证链

您的可信系统会使用凭证链在每个步骤中证明授权:

IntentMandate (User chose charity)
    ↓
CartMandate (Merchant created cart, signed IntentMandate)
    ↓
PaymentMandate (Payment provider created payment, signed CartMandate)

让我们在跟踪记录中找到每项授权。

查找 IntentMandate

点击 execute_tool: save_user_choice span(位于 ShoppingAgent 下)。

在“属性”面板中,您会看到:

{
  "tool.name": "save_user_choice",
  "tool.input.charity_name": "Save the Children",
  "tool.input.amount": 50,
  "tool.output.status": "success",
  "tool.output.intent_mandate": {
    "charity_name": "Save the Children",
    "amount": 50,
    "timestamp": "2024-11-08T15:30:12.345Z",
    "signature": "a3f7b9c1d2e4..."
  }
}

这证明了:

  • ✅ 用户选择了“Save the Children”
  • ✅ 金额为 50 美元
  • ✅ 记录选择的时间:15:30:12 UTC
  • ✅ 生成了签名(在生产环境中,这将是加密签名)

IntentMandate 现在处于会话状态,可供后续智能体使用。

查找 CartMandate

点击 execute_tool: create_cart_mandate span(位于 MerchantAgent 下)。

在属性面板中:

{
  "tool.name": "create_cart_mandate",
  "tool.input.intent_mandate": {
    "charity_name": "Save the Children",
    "amount": 50,
    "signature": "a3f7b9c1d2e4..."
  },
  "tool.output.status": "success",
  "tool.output.cart_mandate": {
    "cart_id": "cart_7893",
    "intent_signature": "a3f7b9c1d2e4...",
    "cart_signature": "e8f2a9b3c7d1...",
    "timestamp": "2024-11-08T15:30:14.789Z"
  }
}

这证明了:

  • ✅ MerchantAgent 收到 IntentMandate(输入显示了这一点)
  • ✅ 已创建购物车,ID 为“cart_7893”
  • ✅ 购物车签名引用 IntentMandate 签名(链式链接!)
  • ✅ 创建时间:世界协调时间 (UTC) 15:30:14(意图产生后 2.4 秒)

CartMandate 现在引用 IntentMandate,从而形成链。

查找 PaymentMandate

点击 execute_tool: create_payment_mandate span(位于 CredentialsProvider 下)。

在属性面板中:

{
  "tool.name": "create_payment_mandate",
  "tool.input.cart_mandate": {
    "cart_id": "cart_7893",
    "intent_signature": "a3f7b9c1d2e4...",
    "cart_signature": "e8f2a9b3c7d1..."
  },
  "tool.confirmation_required": true,
  "tool.confirmation_timestamp": "2024-11-08T15:30:17.891Z",
  "tool.user_response": "CONFIRMED",
  "tool.wait_duration_ms": 29168,
  "tool.output.status": "success",
  "tool.output.payment_mandate": {
    "payment_id": "pay_9821",
    "cart_signature": "e8f2a9b3c7d1...",
    "payment_signature": "b4c9e2a7f8d3...",
    "timestamp": "2024-11-08T15:30:47.059Z"
  }
}

这证明了完整的链条:

  • ✅ CredentialsProvider 收到 CartMandate(输入显示了该信息)
  • ✅ 付款引用 CartMandate 签名(链式链接!)
  • ✅ 需要确认 (confirmation_required: true)
  • ✅ 用户于世界协调时间 (UTC) 15:30:17 确认
  • ✅ 系统等待了 29.2 秒,用户才做出决定
  • ✅ 确认后创建了付款(时间戳:15:30:47)

直观呈现链

跟踪记录证明凭证链已正确执行:

15:30:12 UTC → IntentMandate created (signature: a3f7...)
                  ↓
15:30:14 UTC → CartMandate created (references: a3f7...)
                  ↓
15:30:17 UTC → User consent requested
                  ↓
15:30:47 UTC → PaymentMandate created (references: e8f2...)

每个授权都会引用前一个授权的签名。这是防篡改的 - 您可以通过检查签名是否匹配来验证链。

第 4 步:分析性能和瓶颈

Cloud Trace 不仅能证明发生了什么,还能显示时间花在了哪里,以便您进行优化。

识别关键路径

在瀑布视图中,查找垂直堆栈中最长的 span。这些就是您的性能瓶颈。

从我们的示例跟踪记录中:

Total: 8.2 seconds

Breakdown:
  - ShoppingAgent:         2.1s (26%)
  - MerchantAgent:         1.8s (22%)
  - CredentialsProvider:   4.0s (49%)  ← Bottleneck
  - Other overhead:        0.3s (3%)

重要数据分析:CredentialsProvider 占总时间的 49%。为什么?

深入分析 CredentialsProvider span:

CredentialsProvider: 4.0s
  - call_llm:              0.8s (20%)
  - create_payment_mandate: 3.0s (75%)  ← User consent wait
  - Other:                 0.2s (5%)

3.0 秒的延迟是预期内的,也是合理的,这是用户在确认之前进行思考的时间。这并非性能问题,而是用户深思熟虑后同意的结果。

跟踪 LLM 费用

点击任意 call_llm span 即可查看 token 使用情况:

{
  "llm.model": "gemini-2.5-flash",
  "llm.usage.prompt_tokens": 487,
  "llm.usage.completion_tokens": 156,
  "llm.usage.total_tokens": 643,
  "llm.response_time_ms": 1243
}

用途:

  • 跟踪每个请求的费用(token 数量 × 模型价格)
  • 识别不必要的冗长提示
  • 比较模型性能(Flash 与 Pro)
  • 针对延迟时间与质量进行优化

计算示例:

Gemini 2.5 Flash pricing (as of Nov 2024):
  Input:  $0.075 per 1M tokens
  Output: $0.30 per 1M tokens

This request:
  Input:  487 tokens × $0.075 / 1M = $0.000037
  Output: 156 tokens × $0.30 / 1M  = $0.000047
  Total:                            = $0.000084 (~$0.00008)

For 10,000 donations/month:
  10,000 × 3 agents × $0.00008 = $2.40/month in LLM costs

这种精细的可见性有助于您根据数据做出模型选择决策。

跨跟踪记录进行比较

过滤多个跟踪记录并比较时长:

Trace 1: 8.2s  (with consent wait: 3.0s)
Trace 2: 12.5s (with consent wait: 7.8s)  ← User took longer
Trace 3: 5.1s  (with consent wait: 0.2s)  ← User clicked fast
Trace 4: 6.3s  (with consent wait: 1.5s)

数据洞见:大多数差异来自用户决策时间,而非系统性能。核心智能体执行时间(不含用户同意环节)稳定在 5 秒左右。

这表明系统运行可靠。

对于生产系统,请设置提醒,以便在用户投诉之前发现问题。

针对高错误率触发提醒

在超过 5% 的跟踪记录包含错误时创建提醒:

  1. 前往 Cloud Monitoring
  2. 依次点击“提醒”->“创建政策”
  3. 配置:
    Resource: Cloud Trace Span
    Metric: Span error count
    Condition: Rate > 5% over 5 minutes
    Notification: Email your-team@example.com
    

高延迟提醒

创建当 p95 延迟时间超过 15 秒时的提醒:

Resource: Cloud Trace
Metric: Span duration (95th percentile)
Condition: > 15000ms for 5 minutes
Notification: PagerDuty

这有助于在性能下降影响用户体验之前发现问题。

如果任何付款处理未经确认,则创建提醒:

Resource: Cloud Trace Span
Filter: tool.name="create_payment_mandate" AND tool.confirmation_required!=true
Condition: Any match
Notification: Critical alert to security team

这是一个安全违规检测器 - 如果它触发,则表示您的意见征求机制存在严重问题。

您学到的内容

通过 Cloud Trace,您现在了解了如何:

✅ 浏览 Cloud Trace Explorer 以查找生产跟踪记录
✅ 阅读瀑布视图以查看完整的执行流程
✅ 通过 IntentMandate → CartMandate → PaymentMandate 跟踪凭证链 ✅ 使用跟踪记录作为证据来解决争议
✅ 分析性能以找出瓶颈
✅ 精细地跟踪 LLM 费用

带来的改变

对比两个系统处理同一“我从未授权过此操作!”投诉的情况:

不具备可观测性的系统

User: "I never authorized that $50 donation!"
You:  "Our logs show the transaction completed successfully."
User: "But I didn't approve it!"
You:  "The system requires confirmation before processing."
User: "I never saw any confirmation!"
You:  "..." [no way to prove what happened]

Result: Refund issued, trust lost, user never returns.

使用 Cloud Trace 的系统

User: "I never authorized that $50 donation!"
You:  "Let me pull up the trace from your session..."
      [Shows waterfall with consent span]
You:  "Here's the evidence:
       - 15:30:17 UTC: System asked for confirmation
       - Message shown: 'You are about to donate $50...'
       - 15:30:47 UTC: You clicked 'CONFIRM'
       - Wait time: 29.2 seconds
       
       The system waited almost 30 seconds for your decision.
       Here's the exact timestamp of your confirmation."
       
User: "Oh... I remember now. My mistake. Sorry!"

Result: Trust preserved, no refund needed, user continues using service.

这就是责任追踪的强大之处。您从“请相信我们”转变为“让我们向您展示到底发生了什么”。

后续步骤

您现已完成构建可信赖智能体的核心技术部分:

✅ 模块 1-6:设计了可信赖的架构(角色、凭据、意见征求)
✅ 模块 7:编排了复杂的工作流 (SequentialAgent)
✅ 模块 8:在启用可观测性的情况下进行了部署
✅ 模块 9:学习了如何读取和使用问责跟踪记录

您构建的架构(角色分离、凭证链、意见征求机制、完整可观测性)可直接转移到处理真实资金、真实数据和真实后果的生产系统。

10. 您的未来旅程

您已构建的内容

在研讨会开始时,您提出了一个问题:“如何构建真正值得信赖、可以处理资金的 AI 智能体?”

现在您已经有了答案。

您的起点(模块 3):

simple_agent = Agent(
    model="gemini-2.5-flash",
    instruction="Find charities and donate",
    tools=[google_search]
)

当前位置(模块 10):

  • ✅ 三个专业智能体,角色分工明确
  • ✅ 三个可验证凭证(意向 → 购物车 → 支付授权)
  • ✅ 完整的凭证链,每一步都有到期验证
  • ✅ 具有时间戳证明的明确意见征求机制
  • ✅ 部署到 Agent Engine 的生产环境,并具备可观测性
  • ✅ Cloud Trace 中完整的问责跟踪记录
  • ✅ 解决争议的取证证据

研讨会与生产环境:差距

您的系统展示了正确的架构和模式,但使用了教学简化,必须升级才能用于真实资金和真实用户。

以下是简化内容和生产环境要求的具体说明:

组件

研讨会实施

投产要求

签名

SHA-256 哈希 (SIG_abc123) 演示

使用 PKI 或 JWT 搭配私钥的真实加密签名

付款处理

模拟退货(simulation: True 标志)

与真实支付 API(Stripe、PayPal、Square)集成

用户身份验证

隐式信任(无需登录)

OAuth 2.0、WebAuthn 或会话管理

Secret Manager

.env 文件中的环境变量

Google Secret Manager 或 Cloud KMS(带加密功能)

慈善机构数据库

包含 9 个慈善机构的模拟 JSON 文件

实时 API 集成(IRS 免税组织搜索、Charity Navigator API)

错误处理

包含错误消息的基本 try-catch

采用指数退避算法、断路器、死信队列的重试逻辑

测试

通过脚本进行手动验证

包含 CI/CD 的全面单元/集成/E2E 测试套件

会话持久性

内存中(本地)或自动(Agent Engine)

具有备份和灾难恢复功能的生产数据库

速率限制

无(教育环境)

每位用户的速率限制、基于 IP 的节流、滥用行为检测

您已掌握的关键架构模式

您在本研讨会中学习的模式是生产模式。不要怀疑他们。

角色分离(AP2 原则 #1)

每个智能体只有一项明确的工作,并且只能看到其所需的信息。如果某个代理遭到入侵,攻击者无法访问其他代理的数据。这样可以限制影响范围。

使用此模式的生产系统:付款处理、文档工作流、审批链、具有验证关卡的多步骤表单。

可验证的凭证(AP2 原则 2)

每个凭证都有过期时间,会引用上一个凭证,并且需要先进行验证才能进入下一步。这会创建防篡改的审核链。

生产价值:完整证明事件发生的时间、顺序和内容。对于争议解决和监管合规至关重要。

用户批准操作的时间戳证明。无法提出异议。

生产环境值:金融交易的法律要求。同时保护用户和公司。

顺序编排(ADK 模式)

强制执行正确的执行顺序。防止跳过步骤。保证每个智能体都能看到前一个智能体的输出。

生产价值:非常适合用户期望立即获得结果的人机协同系统。此模式适用于捐款流程、结账流程和审批链。

全面的可观测性 (OpenTelemetry + Cloud Trace)

自动捕获每个决策、工具调用、同意时刻和凭证交接。

生产环境价值:为争议提供取证证据。性能优化数据。合规性审核跟踪记录。精准调试生产环境中的问题。

可供持续学习的资源

ADK 文档:

AP2 及相关标准:

Google Cloud 服务:

清理资源

为避免持续产生费用,请删除您的部署:

Agent Engine:按照 Agent Engine 文档中的步骤操作

Cloud Run(如果已部署):

gcloud run services delete charity-advisor \
    --region=$GOOGLE_CLOUD_LOCATION

存储桶:

gsutil -m rm -r gs://$GOOGLE_CLOUD_PROJECT-staging
gsutil -m rm -r gs://$GOOGLE_CLOUD_PROJECT-artifacts

您的旅程仍在继续

您从一个简单的问题开始,逐步构建了完整的答案。您已掌握构建可靠 AI 智能体的基础模式。这些模式适用于 AI 智能体处理敏感操作的任何领域,例如金融交易、医疗保健决策、法律文件、供应链运营。

原则是相通的。信任模型有效。

现在,去构建值得信赖的应用吧!❤️

横幅