使用 Google ADK 和 AP2 建構值得信賴的慈善機構代理

1. 建立信任,激發慷慨

橫幅

靈光乍現

手機震動。你看到一則新聞報導,內容提到一項成功的識字計畫,幫助資源匱乏社區的兒童學習閱讀。你強烈渴望貢獻一己之力。您開啟瀏覽器,搜尋「兒童識字計畫捐款」。

google 搜尋

系統會顯示數百筆結果。

你點選第一個連結,網站看起來很專業。你向下捲動到財務資料,「行政費用:28%。」你停下腳步,你每捐出 1 美元,只有 72 美分會實際用於資助計畫。這樣好嗎?不確定。

您嘗試另一家機構。你從未聽過。他們是否合法?你快速搜尋了一下,結果越陷越深。你找到兩年前的 Reddit 討論串,其中一位使用者聲稱:「這是詐騙,我的捐款根本沒送到任何地方。」另一位則熱情地為他們辯護:「他們在現場做的是實事!」這種不確定性令人不知所措。

30 分鐘後,你深陷在各種相互矛盾的評論、效率評分和 IRS 記錄中,卻還是沒有捐款。原本慷慨解囊的熱情,卻被繁瑣的調查過程澆熄。這個分頁會開啟幾天,提醒你當初的美意,直到你最後關閉為止。

這不是個人失敗,而是系統故障

這種體驗不分國界。雖然許多人想捐款,但過程中充滿阻礙,導致他們猶豫不決:

  • ❌ 研究阻力:每個慈善機構都需要自行調查。
  • ❌ 信任驗證:難以區分高效組織與低效組織,甚至可能遇到詐騙。
  • ❌ 選擇困難:選項過多會導致決策疲勞。
  • ❌ 失去動力:隨著物流負擔增加,捐贈的情感動力也會減弱。

這種摩擦會造成驚人的實際成本。美國的個人捐款金額相當龐大,根據 Giving USA 2024 的資料,光是 2023 年,個人捐款金額就高達約 $3, 740 億美元。然而,研究顯示,捐款障礙 (包括搜尋成本、心理摩擦和時間限制) 會大幅減少慈善事業獲得的捐款金額。一項涉及數百萬名捐款者的研究發現,即使線上捐款流程中只有一小部分不順暢,也會阻礙人們完成慈善捐款。

這代表有數十億美元的捐款,未能送達需要幫助的對象。

願景

想像一下不同的體驗。不必花 30 分鐘研究,只要說:

「我想捐 $50 美元給兒童識字計畫。請幫我找一家評價高、效率佳且經過驗證的慈善機構。」

幾秒鐘後,您就會收到令人安心的回覆:

慈善團體結果資訊卡

這正是 AI 捐贈代理的價值所在。不過,要實現這個願景,我們必須解決一項根本挑戰:當自主 AI 代理處理金錢時,信任不是可有可無,而是整個基礎。

  • 如何證明使用者授權的內容?
  • 如果發生錯誤,誰該負責?
  • 如何讓捐款人、慈善機構和付款網路放心參與?

今日任務

在本工作坊中,您將結合兩項強大技術,建構可靠的代理:

Google Agent Development Kit (ADK)

Agent Payments 通訊協定 (AP2)

角色

建構正式環境等級 AI 代理的工廠

架構藍圖:打造值得信賴的 AI 交易

這項工具的作用

• 多代理自動化調度管理架構
• 內建安全防護功能,例如工具確認
• 可用於正式環境的觀測能力和追蹤功能
• 簡單的 Python 介面,可處理複雜的代理行為

• 角色型安全邊界
• 可驗證的數位憑證 (授權)
• 同意聲明的加密編譯證明
• 完整的稽核追蹤記錄,可確保責任歸屬

瞭解詳情

ADK 說明文件

AP2 通訊協定

建構項目

架構

完成本工作坊後,您將建立:

✅ 多代理系統,具備專門角色:

  • 尋找通過驗證慈善機構的購物代理
  • 建立具約束力捐贈方案的商家代理
  • 安全處理付款的憑證供應商
  • 協調整個流程的自動化調度管理工具

三種可驗證憑證:

  • IntentMandate:「幫我找教育慈善機構」
  • CartMandate:「$50 to Room to Read, signed by merchant」
  • PaymentMandate:「透過模擬付款處理」

✅ 層層把關的安全防護:

  • 角色型信任邊界
  • 使用者明確同意

✅ 完整的稽核追蹤記錄:

  • 每項決策皆可追溯
  • 記錄每筆同意聲明
  • 顯示所有轉交對話

🔒 重要事項:這是安全的學習環境

準備好建立信任感了嗎?

在下一個單元中,我們將設定開發環境,並建構第一個 AI 代理。您很快就會發現,為什麼簡單的代理不可靠,並在研討會的其餘時間學習如何修正這個問題。

首先,我們來瞭解問題。

2. 準備工作區

打造值得信賴的代理

建構 AI Giving Agent 前,必須先準備乾淨、一致且設定正確的開發環境。本單元是確保所有必要工具和服務都已就緒的重要步驟。

順利完成這項設定後,您就能在後續單元中,全心投入建構代理邏輯,不必擔心設定問題。

存取 Cloud Shell

首先,我們要開啟 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:Agent Development Kit 框架
  • 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 代理

首先,來看看第一個代理的範本。其中包含基本結構和預留位置,我們會在後續步驟中完成。

👉 開啟檔案

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 通訊協定的第一項原則:角色型架構,開始解決這些問題。

在編寫任何程式碼之前,我們先來瞭解這項原則的重要性。

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"]
    }

Step 4:新增 Display Formatting Helper

建構代理之前,我們先新增一個輔助函式,將慈善機構資料格式化,方便使用者查看。

👉 捲動畫面,找出以下項目:

# 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:

意圖詳細資料:

  • 意圖 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 傳回成功訊息,其中包含意圖詳細資料
  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 可呼叫的工具
  • 仰賴 docstring 和類型提示,讓 LLM 理解
  • 自動處理叫用
  • 工具可組合性:小型專用工具 > 單一大型工具

✅ 給服務專員的指示:

  • 逐步工作流程指引
  • 明確界線 (「請勿…」)
  • 避免錯誤的參數規格
  • 技術定義 (什麼是 IntentMandate)
  • 極端案例處理 (遇到…時該說什麼)

後續步驟

在下一個單元中,我們將建構商家代理來接收 IntentMandate,並建立第二個可驗證憑證:CartMandate。

購物代理已建立 IntentMandate,擷取使用者的意圖和到期時間。現在,我們需要一個代理來讀取該憑證、驗證憑證是否過期,並建立正式、簽署的報價,內容為:「我,商家,將遵守此價格並交付這些商品。」

接著建構商家代理,並查看第二個 AP2 憑證的實際運作情形。

5. 建構商家代理 - 繫結商品和購物車委任

橫幅

從探索到承諾

在上一單元,您建構了購物代理,這個專家代理會尋找經過驗證的慈善機構,並建立 IntentMandate 來擷取使用者意圖。現在我們需要一個代理來接收 IntentMandate,並建立正式、具約束力的報價。

這時 AP2 的第二項重要原則就派上用場:透過 CartMandate 驗證憑證。

AP2 原則:CartMandate 和具約束力的報價

為什麼需要商家角色

在單元 4 中,購物代理建立了 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"
}

但這只是使用者意圖。我們必須先取得下列資訊,才能處理任何付款:

  • 付款系統可解讀的正式優惠結構
  • 商家會遵守這個價格的證明
  • 具約束力的承諾,交易期間不得更改
  • 驗證意圖是否過期

這就是 Merchant Agent 的工作。

什麼是 CartMandate?

CartMandate 是 AP2 對「數位購物車」的稱呼,可做為具約束力的報價。這項 API 是根據 W3C PaymentRequest 標準建構而成,也就是說:

  • 全球付款處理方都認可這種格式
  • 其中包含所有交易明細,並以標準化方式呈現
  • 可透過加密簽署證明真實性

這就像承包商提供的書面報價:

  • ❌ 口頭:「好,我可以做這份工作,費用大約五十美元」
  • ✅ 書面報價單:分項費用、總金額、簽名、日期

書面報價具有約束力。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 (內容) - 購買項目:

  • method_data:接受的付款方式
  • details: Items and total
  • 選項:運送、付款人資訊規定

3. merchant_authorization - 加密編譯簽章

商家簽名:承諾證明

商家簽章至關重要。這項認證可證明:

  • 這項優惠來自授權商家
  • 商家承諾會遵守這個確切價格
  • 優惠建立後未經竄改

在實際工作環境中,這會是使用 PKI (公用金鑰基礎架構) 或 JWT (JSON Web Token) 的加密編譯簽章。在教育研討會中,我們會使用 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

Merchant Agent 會:

  1. 從狀態讀取 IntentMandate (購物代理寫入的內容)
  2. 驗證意圖是否尚未過期
  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
    }

Step 4: Build the Merchant Agent - Import Components

接著,我們要建立使用這項工具的代理。

👉 開啟

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."""
)

✅ 檢查點:您現在擁有完整的 Merchant Agent,並使用 Pydantic 模型正確建立 AP2 CartMandate。

步驟 8:測試 Merchant Agent

現在,我們來確認代理是否正確建立 CartMandates (含簽名),並驗證到期日。

測試設定:執行測試指令碼

👉 在 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 中,您建構了 Merchant Agent,這個專用代理會讀取 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:專屬 ID
  • payment_details_id:連結回 CartMandate
  • user_consent:使用者是否核准
  • amount:付款金額 (從 CartMandate 擷取)

2. agent_present:是否為人工介入迴路流程

3. timestamp:建立授權的時間

我們的任務:建構憑證提供者

Credentials Provider 會執行下列操作:

  1. 從狀態讀取 CartMandate (Merchant Agent 寫入的內容)
  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

現在,我們要新增邏輯,使用 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:測試 Credentials Provider

現在,我們來確認代理是否正確處理付款,並完成憑證鏈結。

👉 在 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
  • 在狀態中記錄 payment_result
  • 清楚標示為模擬 (simulation: True 標記)

✅ 使用模型完成 AP2 Chain:

  • 三個代理、三個憑證、三個 Pydantic 驗證
  • 每個代理都會使用模型驗證先前憑證的結構
  • 每個憑證都會連結至上一個憑證,以便追蹤稽核記錄
  • 根據狀態交接,維持角色區隔
  • 整個鏈結的類型安全

模型導向開發:

  • 透過 model_validate() 驗證輸入內容
  • 使用巢狀模型建構類型安全
  • 透過 model_dump(mode='json') 自動序列化
  • 一開始就採用可用於正式環境的模式

後續步驟

在下一個單元中,我們將建構自動調度管理代理,協調所有三個專員代理。

您已使用 AP2 Pydantic 模型,建構三個強大的專家代理。接著,我們來建構指揮者,將這些元素整合為流暢的捐款體驗。

我們來建構 Orchestrator,看看整個系統如何運作。

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
  • ✅ 每個代理都在獨立的環境中執行
  • ✅ 狀態會透過憑證鏈向前傳遞

我們的使命:打造完整系統

我們將建構兩個層:

第 1 層:處理管道 (SequentialAgent)

  • 將 Merchant → Credentials 連結在一起
  • 選取慈善機構後,系統會自動依序執行
  • 不可分割地執行報價和付款

第 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)

回呼

SequentialAgent 可保證執行順序,但如果:

  • 購物代理失敗,但未顯示錯誤訊息 (從未建立 IntentMandate)
  • 購物和商家之間相隔一小時 (意圖過期)
  • 狀態損毀或清除
  • 有人試圖直接致電商家,而非透過購物分頁

回呼可強化架構,在代理啟動 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:建構意圖驗證函式

現在,我們來建立回呼函式,在 Merchant Agent 執行前驗證 IntentMandate。

👉

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:將回呼附加至商家服務專員

現在,請將回呼連結至代理。

👉

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

行:

    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:建構購物車驗證函式

👉

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:將回呼附加至憑證提供者

👉

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

行:

    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 網頁 UI 測試

現在,我們來測試完整的強化系統,並啟用驗證回呼。

👉 在 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 網頁 UI:

在 Cloud Shell 工具列 (通常位於右上方) 點選「網頁預覽」圖示 (外觀為眼睛或帶有箭頭的正方形),然後選取「變更通訊埠」。在彈出式視窗中,將通訊埠設為 8000,然後點選「變更並預覽」。Cloud Shell 隨即會開啟新的瀏覽器分頁,顯示 ADK 網頁 UI。

webpreview

👉 從下拉式選單選取代理:

在 ADK 網頁 UI 中,您會在頂端看到下拉式選單。從清單中選取「charity_advisor」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:

  • 建立及簽署意圖
  • 傳回確認訊息和意圖 ID

4. 顧問進入處理階段:

太棒了!正在處理你捐給 Room to Read 的 $50 美元...

5. DonationProcessingPipeline 啟用:

  • 商家回呼驗證 IntentMandate (✓ 通過) ← 新增!
  • 商家代理建立 CartMandate 並簽名
  • Credentials callback validates CartMandate (✓ passed) ← NEW!
  • 憑證提供者準備付款

6. 付款處理:

  • 憑證提供者建立 PaymentMandate
  • 模擬付款處理
  • 退貨交易 ID

7. Advisor 摘要:

太棒了!捐款已成功處理!🎉

詳細資料:

  • 金額:$50.00 美元
  • 慈善機構:Room to Read (EIN:77-0479905)
  • 交易 ID:txn_a3f7b2c8d9e1f4a2

測試 2:驗證回呼是否能偵測到失敗 (選用進階測試)

想看看回呼如何捕捉錯誤嗎?您必須手動破壞狀態 (進階偵錯),但在正式環境中,回呼會擷取:

  • 購物代理工具失敗 → 商家回呼封鎖:「錯誤:無法建立購物車...」
  • 2 小時後 → 商家回呼封鎖:「錯誤:意圖已過期...」
  • 購物車到期 → 憑證回呼封鎖:「錯誤:購物車已到期 (15 分鐘限制)...」

現在,驗證回呼會在架構上強制執行這些極端案例。

您剛才建構的內容

您已成功將三個專門代理,整合成一個順暢、可靠且經過架構驗證的系統。

後續步驟

您已完成建構可靠代理的核心技術:

您已在本機建立完整的可信任系統,強制執行憑證鏈結。現在,讓我們透過正式版部署作業,讓實際使用者可以存取,並啟用責任追蹤,以便進行單元 9。

將強化後的代理部署至 Google Cloud。

8. Deployment

橫幅

您已完成可靠的捐款系統,並有三個專門的代理在本機運作:

但只能在開發機器上執行。如要讓這個系統對實際使用者發揮作用,並擷取可證明可靠性的問責追蹤記錄,您必須將系統部署至正式環境。

本單元將逐步說明如何將代理部署至 Google Cloud,並從一開始就啟用觀測能力。部署期間使用的 --trace_to_cloud 旗標,可讓您在單元 9 中建立責任追蹤記錄。

瞭解部署選項

ADK 支援多個部署目標。每種方法在複雜度、工作階段管理、擴充和成本方面各有不同特性:

因素

當地 (adk web)

Agent Engine

Cloud Run

複雜度

最低

低

中

工作階段資料保留設定

僅限記憶體內 (重新啟動時會遺失)

Vertex AI 代管 (自動)

Cloud SQL (PostgreSQL) 或記憶體內

基礎架構

無 (僅限開發機器)

全代管

容器 + 選用資料庫

冷啟動

不適用

100 至 500 毫秒

100-2000 毫秒

擴充

單一執行個體

自動

自動 (歸零)

費用模型

免費 (本機運算)

以運算為基礎

以要求為依據 + 免費方案

UI 支援

是 (內建)

否 (僅限 API)

是 (透過 --with_ui 旗標)

觀測能力設定

本機追蹤記錄檢視工具

自動 (--trace_to_cloud)

需要 --trace_to_cloud 旗標

適用情境

開發和測試

正式環境代理

正式環境代理

建議:為打造值得信賴的捐款系統,建議您使用 Agent Engine 做為主要正式環境部署,因為它提供:

  • 全代管基礎架構 (不需管理容器)
  • 透過 VertexAiSessionService 內建工作階段持續性
  • 自動調度資源,無須冷啟動
  • 簡化部署作業 (不必掌握 Docker 知識)
  • 立即可用的 Cloud Trace 整合功能

其他選項:Google Kubernetes Engine (GKE)

如果進階使用者需要 Kubernetes 層級的控制權、自訂網路或多服務自動化調度管理,可以選擇 GKE 部署。這個選項提供最大的彈性,但需要更多營運專業知識 (叢集管理工具、資訊清單、服務帳戶)。

本程式碼實驗室不會介紹 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 請使用支援的地區
  • 執行部署指令碼時,如果暫存 bucket 不存在,系統會自動建立

4. 啟用必要的 API

部署程序需要啟用多個 Google Cloud 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:用於暫存 bucket
  • 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 (可選用 UI)

運作方式:

如果是 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 Wrapper

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 是建議的正式環境部署方式,可為可靠的捐款系統提供全代管基礎架構,並內建工作階段持續性。

執行部署作業

從專案根目錄:

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

這項程序會將代理封裝並部署至 Vertex AI 基礎架構,需要 5 到 10 分鐘。

儲存代理引擎 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 部署作業現在包含:

✅ 所有三個代理 (購物、商家、憑證) 都在代管執行階段中執行
✅ 完整的憑證鏈邏輯 (意圖 → 購物車 → 付款委託書)
✅ 使用者同意聲明機制和確認工作流程
✅ 透過 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 記錄
  • 確認 charity_advisor 資料夾中有 agent_engine_app.py 檔案

步驟 5:部署至 Cloud Run (選用)

雖然建議使用 Agent Engine 簡化正式環境部署作業,但 Cloud Run 提供更多控制選項,並支援 ADK 網頁 UI。這個部分為選用。

Cloud Run 的使用時機

如有下列需求,請選擇 Cloud Run:

  • 用於使用者互動的 ADK 網頁 UI
  • 完整控管容器環境
  • 自訂資料庫設定
  • 與現有 Cloud Run 服務整合

執行部署作業

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

不同之處:

指令碼會自動執行下列動作:

  • 使用代理程式碼建構 Docker 容器
  • 建立 Cloud SQL PostgreSQL 資料庫 (如有需要)
  • 設定資料庫連線
  • 部署時啟用 ADK 網頁 UI

由於 Cloud SQL 佈建作業,部署作業需要 10 到 15 分鐘。

工作階段管理:

  • 使用 DatabaseSessionService,而非 VertexAiSessionService
  • 需要 .env 中的資料庫憑證 (或自動生成)
  • 狀態會保存在 PostgreSQL 資料庫中

使用者介面支援:

  • 網頁 UI 網址: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

問題:系統未自動建立暫存 bucket

解決方案:指令碼應會自動建立 bucket。如果沒有,請手動建立:

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 尋找正式版追蹤記錄
  • 查看瀑布檢視畫面,瞭解執行流程
  • 找出憑證鏈 (意圖 → 購物車 → 付款委託書)
  • 找出同意時刻和時間戳記證明
  • 使用追蹤記錄解決爭議
  • 匯出追蹤記錄,用於法規遵循和稽核

這正是可信賴系統與功能強大但不透明系統的區別:能夠以精確的鑑識方式證明發生的事件。

瞭解追蹤記錄和 Span

在 Cloud 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 如何形成追蹤記錄

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 分鐘內顯示

產生測試追蹤記錄:

如果您透過 UI 部署至 Cloud Run,請前往服務網址,在瀏覽器中完成捐款。

如果您已部署至 Agent Engine,請執行單元 8 的測試指令碼:

python scripts/test_deployed_agent.py

等待 1 到 2 分鐘,然後重新整理 Cloud Trace Explorer 頁面。現在應該會看到追蹤記錄。

篩選追蹤記錄

使用頂端的篩選器選項,找出特定追蹤記錄:

  • 時間範圍:視需要將「過去 1 小時」變更為「過去 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 時距 (頂端的根時距)。右側面板會顯示詳細屬性:

{
  "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 跨距 (位於 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 記錄選擇
  • ✅ 產生簽章 (在實際工作環境中,這會是加密簽章)

IntentMandate 現在處於工作階段狀態,可供後續代理使用。

尋找 CartMandate

按一下「MerchantAgent」下方的 execute_tool: create_cart_mandate span。

在屬性面板中:

{
  "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 簽章 (鏈結!)
  • ✅ 建立時間:15:30:14 UTC (意圖產生後 2.4 秒)

CartMandate 現在會參照 IntentMandate,形成鏈結。

尋找 PaymentMandate

按一下 execute_tool: create_payment_mandate 跨度 (位於 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)
  • ✅ 使用者於世界標準時間 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 跨度:

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 範圍,即可查看權杖用量:

{
  "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
}

這項功能可用來:

  • 追蹤每項要求的費用 (詞元數 × 模型定價)
  • 找出不必要的冗長提示
  • 比較模型效能 (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
    

高延遲警告

建立快訊,在第 95 個百分位數的延遲時間超過 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 檔案

Live API 整合 (IRS 免稅機構搜尋、Charity Navigator API)

錯誤處理

基本 try-catch 與錯誤訊息

採用指數輪詢、斷路器、無效信件佇列的重試邏輯

測試

透過指令碼手動驗證

具備 CI/CD 的全方位單元/整合/E2E 測試套件

工作階段資料保留設定

記憶體內 (本機) 或自動 (Agent Engine)

具備備份和災難復原功能的正式資料庫

Rate Limiting

無 (教育環境)

每位使用者的頻率限制、以 IP 為基礎的節流、濫用偵測

您已掌握的重要架構模式

您在本工作坊學到的模式適用於正式環境。請勿懷疑。

角色區隔 (AP2 原則 #1)

每個代理只有一項明確工作,且只能看到所需資訊。如果某個代理遭到入侵,攻擊者也無法存取其他代理的資料。這可限制影響範圍。

使用這項功能的正式環境系統:付款處理、文件工作流程、核准鏈、含驗證閘的多步驟表單。

可驗證憑證 (AP2 原則 2)

每個憑證都有到期時間、參照前一個憑證,且必須先通過驗證才能進行下一步。這會建立防竄改的稽核鏈。

製作價值:完整證明事件發生的時間和順序。這對爭議解決和法規遵循至關重要。

使用者核准動作的時間戳記證明。無法提出爭議。

Production value:金融交易的法律要求。保護使用者和公司。

依序自動化調度管理 (ADK 模式)

強制執行正確的執行順序。防止略過步驟。確保每個代理都能看到前一個代理的輸出內容。

製作價值:非常適合使用者期望立即獲得結果的人機迴圈系統。這種模式適用於捐款流程、結帳程序和核准鏈。

完整觀測能力 (OpenTelemetry + Cloud Trace)

自動擷取每項決策、工具呼叫、同意時刻和憑證交接。

製作價值:爭議的鑑識證據。效能最佳化資料。法規遵循稽核追蹤記錄。精準偵錯正式環境問題。

持續學習的資源

ADK 說明文件:

AP2 和相關標準:

Google Cloud 服務:

清除資源

如要避免持續產生費用,請刪除部署作業:

Agent Engine:按照 Agent Engine 說明文件中的步驟操作

Cloud Run (如已部署):

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

Storage bucket:

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

繼續旅程

您從簡單的問題著手,逐步建構出完整的答案。您已掌握建構可靠 AI 代理的基礎模式。這些模式適用於 AI 代理處理機密作業的任何領域,包括金融交易、醫療決策、法律文件、供應鏈營運。

原則是相通的。信任模型確實有效。

現在就開始打造值得信賴的產品吧!❤️

橫幅