1. 信頼を築いて寛大さを引き出す

インスピレーションの瞬間
スマートフォンが振動します。十分な支援を受けていないコミュニティの子どもたちが読み書きを学べるように支援する、成功した識字プログラムに関するニュース記事を見ました。貢献したいという強い衝動に駆られます。ブラウザを開き、「子供の識字プログラムへの寄付」を検索します。

数百件の結果が表示されます。
最初のリンクをクリックします。ウェブサイトがプロフェッショナルな印象を与える。下にスクロールして財務状況を確認します。「管理費用: 28%」一時停止します。寄付した 1 ドルのうち、実際にプログラムの資金となるのは 72 セントだけです。これは良いことでしょうか?よくわからない。
別の組織を試します。聞いたことがない。それらは正当なものですか?簡単な検索で、迷宮に迷い込んでしまいます。2 年前の Reddit のスレッドで、あるユーザーが「これは詐欺だ。私の寄付はどこにも届いていない」と主張しているのを見つけました。もう一人は「彼らは現場で実際に活動しているんだ!」と熱心に擁護しています。曖昧さは麻痺を招きます。
30 分後、あなたは矛盾するレビュー、効率評価、IRS の記録の迷路に迷い込み、まだ寄付していません。最初の寛大な気持ちは、調査の煩わしさに取って代わられてしまいました。タブは数日間開いたままになり、良い意図を思い出させる小さなリマインダーとして機能し、最終的に閉じられます。
これは個人の失敗ではなく、システムの失敗です
このエクスペリエンスは普遍的なものです。寄付したいという気持ちはあっても、そのプロセスにはためらいや疑問を生じさせるハードルが数多く存在します。
- ❌ リサーチの負担: 慈善団体ごとに調査が必要。
- ❌ 信頼性の検証: 非常に効果的な組織と、非効率な組織や、あからさまな詐欺を区別することは困難です。
- ❌ 分析麻痺: 選択肢が多すぎると、決断疲れにつながります。
- ❌ 勢いの喪失: 寄付したいという感情的な動機は、手続き上の負担が増えるにつれて薄れていきます。
この摩擦は、現実の世界で驚くほどのコストを発生させています。米国における個人寄付は膨大で、Giving USA 2024 によると、2023 年だけでも個人寄付者は約 3, 740 億ドルを寄付しています。しかし、調査によると、検索コスト、心理的な摩擦、時間的な制約など、寄付を阻む要因により、慈善活動に届く金額が大幅に減少しています。数百万人の寄付者を対象とした調査によると、オンラインでの寄付プロセスにわずかな摩擦があるだけでも、人々は慈善活動の意図を果たすことができなくなります。
これは、数十億ドルもの寄付金が、必要としている活動に届いていないことを意味します。
The Vision
別のエクスペリエンスを想像してみてください。30 分かけて調査する代わりに、次のように言うだけです。
「子ども向けの識字プログラムに 50 ドル寄付したい。評価が高く、効率的で、信頼できる慈善団体を探して。」
数秒で、信頼できる回答が得られます。
これが AI 寄付エージェントの可能性です。しかし、このビジョンを実現するには、根本的な課題を解決する必要があります。自律型 AI エージェントがお金を扱う場合、信頼はオプションではなく、すべての基盤となります。
- ユーザーが承認した内容を証明するにはどうすればよいですか?
- ミスが発生した場合、誰が責任を負うのか。
- 寄付者、慈善団体、決済ネットワークが安心して参加できるようにするにはどうすればよいでしょうか。
今日のミッション
このワークショップでは、2 つの強力なテクノロジーを組み合わせて、信頼できるエージェントを構築します。
Google の Agent Development Kit(ADK) | Agent Payments Protocol(AP2) | |
職務 | 本番環境グレードの AI エージェントを構築するためのファクトリ | AI トランザクションの信頼性に関するアーキテクチャ ブループリント |
提供される機能 | • マルチエージェント オーケストレーション用のフレームワーク | • ロールベースのセキュリティ境界 |
詳細 |
作成するアプリケーションの概要
このワークショップを修了すると、次のものが作成されます。
✅ 特殊なロールを持つマルチエージェント システム:
- 認定された慈善団体を見つけるショッピング エージェント
- 拘束力のある寄付オファーを作成する販売者エージェント
- 支払いを安全に処理する認証情報プロバイダ
- フロー全体を調整するオーケストレーター
✅ 3 種類の検証可能な認証情報:
- IntentMandate: 「教育関連の慈善団体を探して」
- CartMandate: 「Room to Read に 50 ドル、販売者の署名入り」
- PaymentMandate: 「模擬決済で処理する」
✅ すべてのレイヤでセキュリティを確保:
- ロールベースの信頼境界
- ユーザーの明示的な同意
✅ 完全な監査証跡:
- すべての意思決定を追跡可能
- すべての同意が記録される
- すべての引き継ぎを可視化
🔒 重要: これは安全な学習環境です
信頼を築く準備はできていますか?
次のモジュールでは、開発環境を設定し、最初の AI エージェントを構築します。シンプルなエージェントが信頼できない理由をすぐに理解し、ワークショップの残りの時間でその修正方法を学びます。
まずは、問題を直接理解することから始めましょう。
2. ワークスペースの準備
信頼できるエージェントの基盤
AI 寄付エージェントを構築する前に、クリーンで一貫性があり、正しく構成された開発環境を準備する必要があります。このモジュールは、必要なツールとサービスがすべて揃っていることを確認するための重要なステップです。
この設定を正常に完了すると、構成の問題を心配することなく、今後のモジュールでエージェント ロジックを構築するというエキサイティングな作業に完全に集中できます。
Cloud Shell にアクセスする
まず、Cloud Shell を開きます。これは、Google Cloud SDK やその他の重要なツールがプリインストールされたブラウザベースのターミナルです。
Google Cloud コンソールの上部にある [Cloud Shell をアクティブにする] をクリックします(右上にあるナビゲーション バーのターミナル アイコンです)。

Google Cloud プロジェクト ID を確認する
- Google Cloud コンソール(https://console.cloud.google.com)を開きます。
- ページ上部のプロジェクト プルダウンから、このワークショップで使用するプロジェクトを選択します。
- プロジェクト 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: スターター エージェントを調べる
まず、最初のエージェントのテンプレートを見てみましょう。このファイルには、次のステップで完成させるプレースホルダを含む基本的な構造が含まれています。
👉 ファイルを開く
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
👉 この 1 行を次のコードに置き換えます。
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="""""",
👉 この 2 行を次のように置き換えます。
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=[]
👉 この 2 行を次のように置き換えます。
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: 実行に関する問題
では、重要な 2 つ目のテストに移りましょう。[user]: プロンプトで、寄付を完了してみます。
Okay, please donate $50 to Room to Read for me.
エージェントは、制限を認めて謝罪します。
寄付をご希望とのこと、大変嬉しく思います。ただし、私はリサーチ アシスタントであり、金融取引や支払いの処理を行うことはできません。寄付を行うには、Room to Read の公式ウェブサイトに直接アクセスする必要があります。
これは、2 つ目の、同様に重要な「なるほど!」の瞬間です。
エージェントは、適切な慈善団体を見つけることができないだけでなく、寄付のアクションを実行することもまだできません。
👉 押す
Ctrl+C
] を押して終了します。
2 つのギャップの可視化
学習した内容
このモジュールでは、最初の AI エージェントを構築して装備しました。その過程で、信頼できるシステムを構築するうえでの 2 つの根本的な課題が明らかになりました。
習得した主なコンセプト
✅ エージェント クラス:
- ADK の主要な構成要素
- LLM の推論(脳)とツール(手)を組み合わせる
- モデル、指示、ツールで構成
✅ フォルダベースの構造:
- 各エージェントは独自のフォルダに格納される
- ADK は
agent_folder/agent.pyを探します adk run agent_folderで実行する
✅ ツールリスト:
- エージェント機能を定義する
- LLM がツールを使用するタイミングと方法を決定する
- さまざまなアクションに対応する複数のツールを含めることができる
✅ 指示プロンプト:
- 職務記述書のようにエージェントの動作をガイドする
- ロール、トリガー、アクション、出力形式を指定する
- 信頼性の高いツール使用に不可欠
✅ 信頼の問題:
- 検出のギャップ: 未審査のソース、品質のばらつき
- 実行ギャップ: 安全な機能、同意、監査証跡がない
次のステップ
次のモジュールでは、AP2 のロールベースのアーキテクチャを実装して、ソリューションの構築を開始します。
最初のエージェントを構築して、ロールの分離を実際に見てみましょう。
4. ショッピング エージェントの構築 - ロールベースの検出

信頼の基盤: ロールの分離
最後のモジュールでは、シンプルな汎用エージェントが 2 つの面で失敗することを確認しました。信頼できる検出を提供できず、安全なトランザクションを実行できないという点です。ここからは、Agent Payments Protocol の最初の原則であるロールベースのアーキテクチャを実装して、これらの問題を解決していきます。
コードを記述する前に、この原則が重要である理由を理解しましょう。
AP2 の原則: ロールの分離
「何でもできる」エージェントの問題
たとえば、1 人の人物をファイナンシャル アドバイザー、会計士、投資ブローカーとして雇ったとします。便利ですか?はい。安全ですか?一切ありません。次のような特徴があります。
- 投資目標(アドバイザーの役割)
- アカウントへのアクセス(会計担当者のロール)
- 資金を移動する権限(ブローカーの役割)
このユーザーが侵害された場合、またはミスを犯した場合、すべてが危険にさらされます。
AP2 のソリューション: 1 つのエージェント、1 つのジョブ
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...
このようにして、コラボレーションを可能にしながら信頼境界を維持しています。
最初のエージェント: ショッピング エージェント
ショッピング エージェントの役割はシンプルで、次のことに重点を置いています。
find_charitiesツールを使用して、信頼できるデータベースにクエリを実行する- お客様にオプションを提示する
save_user_choiceツールを使用して IntentMandate を作成し、状態に保存します。- 次のエージェント(販売者)に引き継ぐ
以上です。支払いの処理やカートの作成は不要で、商品の検索と引き継ぎのみを行います。
ステップごとに作成していきましょう。
ステップ 1: 入力検証ヘルパーを追加する
本番環境ツールを構築する際、入力検証は重要です。チャリティ データを状態に保存する前に検証するヘルパー関数を作成しましょう。
👉 開く
charity_advisor/tools/charity_tools.py
上部に find_charities 関数(すでに完成済み)が表示されます。下にスクロールして、次の項目を確認します。
# MODULE_4_STEP_1_ADD_VALIDATION_HELPER
👉 この 1 行を次のコードに置き換えます。
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 の 3 つの検証可能な認証情報の 1 つです。
👉 同じファイルで、次の行を見つけます。
# MODULE_4_STEP_2_ADD_INTENTMANDATE_CREATION_HELPER
👉 この 1 行を次のコードに置き換えます。
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
👉 この 1 行を次のコードに置き換えます。
# Validate inputs before creating IntentMandate
is_valid, error_message = _validate_charity_data(charity_name, charity_ein, amount)
if not is_valid:
logger.error(f"Validation failed: {error_message}")
return {"status": "error", "message": error_message}
# Create AP2 IntentMandate using our updated helper function
intent_mandate = _create_intent_mandate(charity_name, charity_ein, amount)
# Write the IntentMandate to shared state for the next agent
tool_context.state["intent_mandate"] = intent_mandate
logger.info(f"Successfully created IntentMandate and saved to state")
logger.info(f"Intent ID: {intent_mandate['intent_id']}")
logger.info(f"Intent expires: {intent_mandate['intent_expiry']}")
# Return success confirmation
return {
"status": "success",
"message": f"Created IntentMandate: ${amount:.2f} donation to {charity_name} (EIN: {charity_ein})",
"intent_id": intent_mandate["intent_id"],
"expiry": intent_mandate["intent_expiry"]
}
ステップ 4: Display Formatting Helper を追加する
エージェントを構築する前に、慈善団体のデータをユーザー フレンドリーな形式で表示するヘルパーをもう 1 つ追加しましょう。
👉 スクロールして以下を探します。
# MODULE_4_STEP_4_ADD_FORMATTING_HELPER
👉 この 1 行を次のコードに置き換えます。
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
👉 この 1 行を次のコードに置き換えます。
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="""""",
👉 この 2 行を次のように置き換えます。
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
👉 この 2 行を次のように置き換えます。
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 のシンプルなエージェントと比較してみてください。モジュール 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 は、寄付の意図をキャプチャし、取引が安全に処理されるようにするための制約を含んでいます。正式な提案を作成して寄付を完了するため、この情報を安全な決済代行業者に転送します。
舞台裏で、いくつかの処理が行われました。
_validate_charity_data()が入力を確認しました_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"
})
- ツールは IntentMandate のみを共有状態に書き込みました。
state["intent_mandate"] = intent_mandate_dict
- インテントの詳細を含む成功メッセージが LLM に返されました
- LLM が最終的なユーザー メッセージを作成した
この IntentMandate は、販売者エージェント(モジュール 5)が取得できるようになりました。販売者は、IntentMandate から慈善団体の名前と金額を抽出し、期限切れになっていないことを確認します。
テスト 3: 実際の検証
検証ヘルパーが不正な入力をキャッチすることを確認しましょう。
👉 タイプ:
I'll donate -$25 to Room to Read.
エージェントは、無効な金額を検出する必要があります。
「Donation amount must be positive, got: $-25.0」という問題が発生しました。
正の寄付金額を指定してください。IntentMandate を作成します。
これは、防御的プログラミングの実例です。_validate_charity_data ヘルパーにより、無効なデータがシステムに入力され、不正な形式の IntentMandate が作成されるのを防ぐことができました。
テスト 4: 信頼境界を確認する
👉 エージェントに支払いの処理を依頼してみましょう。
Now process my credit card payment.
エージェントは、役割の境界を尊重して、このリクエストを拒否する必要があります。
お支払いを処理する権限は、私の役割には含まれておりません。私の仕事は、あなたが認証済みの慈善団体を見つけ、寄付の意向を反映した IntentMandate を作成するのを手伝うことです。
お客様の IntentMandate はすでに作成され、Google の安全な決済代行業者に渡されています。販売者エージェントが正式なオファー(CartMandate)を作成し、認証情報プロバイダがユーザーの明示的な同意を得て実際の支払いを処理します。
これが信頼境界の実際の動作です。エージェントは、支払いデータを処理する権限がないことを認識しており、その指示により、ユーザーにこのことを説明すると同時に、IntentMandate のコンセプトについても説明するよう明示的に指示されています。
👉 報道
Ctrl+C
] を押して終了します。
作成した内容
AP2 Pydantic モデルを使用して適切な IntentMandate を作成し、AP2 のアーキテクチャの最初の部分を実装できました。
習得した主なコンセプト
✅ ロールベースのアーキテクチャ:
- 各エージェントには、明確に定義されたジョブが 1 つあります。
- エージェントは直接アクセスではなく、共有状態を介して通信する
- 信頼境界により、侵害の影響を制限
✅ IntentMandate(AP2 認証情報 #1):
- 検証用の公式 AP2 Pydantic モデルを使用して作成
- ユーザー インテントを構造化してキャプチャ
- セキュリティの有効期限が含まれる(リプレイ攻撃を防止)
- 制約(販売者、払い戻し可能性、確認)を指定します。
- 人間向けの自然言語による説明
- エージェントが機械で読み取り可能
- 辞書に変換する前に検証されたモデル
✅ 共有メモリとしての状態:
tool_context.stateは、すべてのエージェントがアクセスできる「メモ帳」です。- 状態への書き込み = 検証可能な認証情報の利用を可能にする
- 状態からの読み取り = 認証情報の使用と検証
- ダウンストリーム エージェントは、認証情報から必要な情報を抽出します。
✅ FunctionTool:
- Python 関数を LLM で呼び出し可能なツールに変換する
- LLM の理解のために docstring と型ヒントに依存する
- 呼び出しを自動的に処理する
- ツールのコンポーザビリティ: 小さな特化型ツール > モノリシックなツール
✅ エージェントへの指示:
- ワークフローのステップごとのガイダンス
- 明確な境界(「~しないでください」)
- エラーを防止するためのパラメータ仕様
- 技術的な定義(IntentMandate とは)
- エッジケースへの対応(...の場合の対応方法)
次のステップ
次のモジュールでは、販売者エージェントを構築して IntentMandate を受信し、2 つ目の検証可能な認証情報である CartMandate を作成します。
ショッピング エージェントは、ユーザーの意図を有効期限付きでキャプチャする IntentMandate を作成しました。次に、その認証情報を読み取り、有効期限が切れていないことを確認して、「販売者である私は、この価格を尊重し、これらの商品を配送します」という正式な署名付きオファーを作成するエージェントが必要です。
Merchant Agent を構築して、2 つ目の AP2 認証情報の動作を確認しましょう。
5. 販売者エージェントの構築 - 拘束力のあるオファーと CartMandate

発見からコミットメントまで
前のモジュールでは、ショッピング エージェントを構築しました。これは、検証済みの慈善団体を見つけて、ユーザーの意図をキャプチャする IntentMandate を作成するスペシャリストです。次に、その IntentMandate を受け取り、正式な拘束力のあるオファーを作成するエージェントが必要です。
ここで、AP2 の 2 つ目の重要な原則である 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 の用語で、拘束力のあるオファーとして機能する「デジタル ショッピング カート」を指します。W3C PaymentRequest 標準に従って構造化されています。つまり、次のようになります。
- 世界中の決済代行業者がこの形式を認識
- すべての取引明細が標準化された方法で含まれている
- 暗号署名により信頼性を証明できる
請負業者からの書面による見積もりを考えてみましょう。
- ❌ 口頭: 「はい、その作業は 50 ドルほどで承ります」
- ✅ 書面による見積もり: 項目別の費用、合計、署名、日付
書面による見積もりには拘束力があります。CartMandate はこれに相当するデジタル版です。
CartMandate の構造
AP2 の CartMandate には、特定のネスト構造があります。
cart_mandate = {
"contents": { # ← AP2 wrapper
"id": "cart_xyz123",
"cart_expiry": "2024-11-07T15:47:16Z",
"merchant_name": "Room to Read",
"user_cart_confirmation_required": False,
"payment_request": { # ← W3C PaymentRequest nested inside
"method_data": [...],
"details": {...},
"options": {...}
}
},
"merchant_authorization": "SIG_a3f7b2c8" # ← Merchant signature
}
3 つの主要コンポーネント:
1. contents - 以下を含むカートラッパー:
- カート ID と有効期限
- 販売者名
- W3C PaymentRequest
2. payment_request(contents 内)- 購入対象:
- method_data: 利用できるお支払いタイプ
- details: 商品と合計
- オプション: 配送、支払人の情報の要件
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]}"
Google の使命: Merchant Agent を構築する
販売者エージェントは次のことを行います。
- 状態から IntentMandate を読み取る(ショッピング エージェントが書き込んだ内容)
- インテントの有効期限が切れていないことを確認する
- 慈善団体の名前、金額、その他の詳細を抽出する
- AP2 Pydantic モデルを使用して、W3C 準拠の PaymentRequest 構造を作成する
- 有効期限付きの AP2 の CartMandate でラップする
- シミュレートされた販売者署名を追加する
- CartMandate を Credentials Provider の状態に書き込む(次のモジュール)
ステップごとに作成していきましょう。
ステップ 1: 有効期限検証ヘルパーを追加する
まず、販売者関連のツールファイルを設定し、IntentMandate の有効期限を検証するヘルパーを追加しましょう。
👉 開く
charity_advisor/tools/merchant_tools.py
有効期限の検証を追加しましょう。
👉 検索:
# MODULE_5_STEP_1_ADD_EXPIRY_VALIDATION_HELPER
👉 この 1 行を次のコードに置き換えます。
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: Signature Generation Helper を追加する
次に、シミュレートされた販売者の署名を生成するヘルパーを作成しましょう。
👉 検索:
# MODULE_5_STEP_2_ADD_SIGNATURE_HELPER
👉 この 1 行を次のコードに置き換えます。
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: ツール署名を作成して設定する
では、メインツールの構築を始めましょう。4 つのサブステップに分けて、段階的に作成します。まず、関数のシグネチャと初期設定です。
👉 検索:
# MODULE_5_STEP_3A_CREATE_TOOL_SIGNATURE
👉 この 1 行を次のコードに置き換えます。
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 行を次のコードに置き換えます。
# 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
👉 この 1 行を次のコードに置き換えます。
# 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
👉 この 1 行を次のコードに置き換えます。
# 6. Generate signature from the validated Pydantic model
signature = _generate_merchant_signature(cart_contents_model)
# 7. Create the final CartMandate model, now including the signature
cart_mandate_model = CartMandate(
contents=cart_contents_model,
merchant_authorization=signature
)
# 8. Convert the final model to a dictionary for state storage and add the custom timestamp
cart_mandate_dict = cart_mandate_model.model_dump(mode='json')
cart_mandate_dict["timestamp"] = timestamp.isoformat()
# 9. Write the final dictionary to state
tool_context.state["cart_mandate"] = cart_mandate_dict
logger.info(f"CartMandate created successfully: {cart_id}")
return {
"status": "success",
"message": f"Created signed CartMandate {cart_id} for ${amount:.2f} donation to {charity_name}",
"cart_id": cart_id,
"cart_expiry": cart_expiry.isoformat(),
"signature": signature
}
ステップ 4: Merchant Agent を構築する - コンポーネントをインポートする
次に、このツールを使用するエージェントを作成しましょう。
👉 開く
charity_advisor/merchant_agent/agent.py
プレースホルダ マーカーを含むテンプレートが表示されます。まず、必要なものをインポートします。
👉 検索:
# MODULE_5_STEP_4_IMPORT_COMPONENTS
👉 この 1 行を次のコードに置き換えます。
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.merchant_tools import create_cart_mandate
ステップ 5: Merchant Agent の指示を記述する
次に、エージェントにツールをいつ、どのように使用するかを指示する指示を作成します。
👉 検索:
# MODULE_5_STEP_5_WRITE_INSTRUCTION
instruction="""""",
👉 この 2 行を次のように置き換えます。
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: Merchant Agent にツールを追加する
👉 検索:
# MODULE_5_STEP_6_ADD_TOOLS
tools=[],
👉 この 2 行を次のように置き換えます。
tools=[
FunctionTool(func=create_cart_mandate)
],
ステップ 7: Complete Merchant Agent を確認する
すべてが正しく配線されているか確認しましょう。
👉 完全な
charity_advisor/merchant_agent/agent.py
は次のようになります。
"""
Merchant Agent - Creates W3C-compliant CartMandates with merchant signatures.
This agent acts as our "Contract Creator."
"""
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.merchant_tools import create_cart_mandate
merchant_agent = Agent(
name="MerchantAgent",
model="gemini-2.5-flash",
description="Creates formal, signed CartMandates for charity donations following W3C PaymentRequest standards.",
tools=[
FunctionTool(func=create_cart_mandate)
],
instruction="""You are a merchant specialist responsible for creating formal, signed offers (CartMandates).
Your workflow:
1. Read the IntentMandate from shared state.
The IntentMandate was created by the Shopping Agent and contains:
- merchants: List of merchant names
- amount: Donation amount
- charity_ein: Tax ID
- intent_expiry: When the intent expires
2. Use the create_cart_mandate tool to create a W3C PaymentRequest-compliant CartMandate.
This tool will:
- Validate the IntentMandate hasn't expired (CRITICAL security check)
- Extract the charity name and amount from the IntentMandate
- Create a structured offer with payment methods, transaction details, and merchant info
- Generate a merchant signature to prove authenticity
- Save the CartMandate to state for the payment processor
3. After creating the CartMandate, inform the user:
- That you've created a formal, signed offer
- The cart ID
- When the cart expires (15 minutes)
- That you're passing it to the secure payment processor
IMPORTANT BOUNDARIES:
- Your ONLY job is creating signed CartMandates from valid IntentMandates
- You do NOT process payments
- You do NOT see the user's payment methods or credentials
- You do NOT interact with payment networks
- You MUST validate that the IntentMandate hasn't expired before creating a cart
- After calling create_cart_mandate, your work is done
WHAT IS A CARTMANDATE:
A CartMandate is a binding commitment that says:
"I, the merchant, commit to accepting $X for this charity donation, and I prove it with my signature."
This commitment is structured using the W3C PaymentRequest standard and includes:
- Payment methods accepted (card, bank transfer)
- Transaction details (amount, charity name)
- Cart expiry (15 minutes from creation)
- Merchant signature (proof of commitment)
This is the second of three verifiable credentials in our secure payment system."""
)
✅ チェックポイント: Pydantic モデルを使用して適切な AP2 CartMandate を作成する、完全な販売者エージェントが完成しました。
ステップ 8: Merchant Agent をテストする
次に、エージェントが署名付きの CartMandate を正しく作成し、有効期限を検証することを確認しましょう。
テストのセットアップ: テスト スクリプトを実行する
👉 Cloud Shell ターミナルで、次のコマンドを実行します。
python scripts/test_merchant.py
想定される出力:
======================================================================
MERCHANT AGENT TEST
======================================================================
Simulated IntentMandate from Shopping Agent:
charity: Room to Read
amount: $50.00
expiry: 2024-11-07T16:32:16Z
----------------------------------------------------------------------
Merchant Agent Response:
----------------------------------------------------------------------
Perfect! I've received your IntentMandate and created a formal, signed offer (CartMandate) for your donation.
**CartMandate Details:**
- **Cart ID**: cart_3b4c5d6e7f8a
- **Donation Amount**: $50.00 to Room to Read
- **Payment Methods Accepted**: Credit/debit cards (Visa, Mastercard, Amex) or bank transfer
- **Cart Expires**: 2024-11-07T15:47:16Z (in 15 minutes)
- **Merchant Signature**: SIG_a3f7b2c8d9e1f4a2
This signed CartMandate proves my commitment to accept this donation amount. I'm now passing this to the secure payment processor to complete your transaction.
======================================================================
CARTMANDATE CREATED:
======================================================================
ID: cart_3b4c5d6e7f8a
Amount: 50.00
Merchant: Room to Read
Expires: 2024-11-07T15:47:16Z
Signature: SIG_a3f7b2c8d9e1f4a2
======================================================================
テスト 2: W3C 準拠を確認する
CartMandate 構造が AP2 と W3C PaymentRequest の両方の標準に完全に準拠していることを確認しましょう。
👉 検証スクリプトを実行する:
python scripts/validate_cartmandate.py
想定される出力:
======================================================================
AP2 & W3C PAYMENTREQUEST VALIDATION
======================================================================
✅ CartMandate is AP2 and W3C PaymentRequest compliant
Structure validation passed:
✓ AP2 'contents' wrapper present
✓ AP2 'merchant_authorization' signature present
✓ cart_expiry present
✓ payment_request nested inside contents
✓ method_data present and valid
✓ details.total.amount present with currency and value
✓ All required W3C PaymentRequest fields present
======================================================================
作成した内容
Pydantic モデルを使用して、適切な構造、有効期限の検証、販売者の署名を含む AP2 の CartMandate を実装できました。
習得した主なコンセプト
✅ CartMandate(AP2 認証情報 #2):
- 公式の AP2 Pydantic モデルを使用して作成
- コンテンツ ラッパーを含む AP2 構造
- W3C PaymentRequest がネストされている
- カートの有効期限(インテントより短い)
- 拘束力のあるコミットメントに対する販売者の署名
- モデルの検証により仕様への準拠を保証
✅ 有効期限の確認:
- 状態から IntentMandate を読み取る
IntentMandate.model_validate()で構造を検証しています- ISO 8601 タイムスタンプの解析
- 現在の時刻との比較
- 古い処理を防止するセキュリティ機能
✅ 販売者の署名:
- 信頼性とコミットメントを証明する
- 検証済みの Pydantic モデルから生成
- 正規表現に
model_dump(mode='json')を使用します。 - 教育用に SHA-256 でシミュレート
- 本番環境では PKI / JWT を使用
- 辞書ではなく、コンテンツ モデルに署名します。
✅ W3C PaymentRequest:
- AP2 の PaymentRequest Pydantic モデルを使用して構築
- 支払いデータの業界標準
- AP2 構造内にネスト
- method_data、details、options が含まれます。
- 相互運用性を実現
モデルを使用した認証情報チェーン:
- ショッピング → IntentMandate(検証済み)
- 販売者が IntentMandate → CartMandate を読み取る(両方のモデルが検証済み)
- 認証情報プロバイダが CartMandate → PaymentMandate を読み取る
- 各ステップで、Pydantic を使用して前の認証情報を検証します。
✅ モデル駆動型開発:
model_validate()による入力検証- タイプセーフな構築
model_dump()による自動シリアル化- プロダクション レディなパターン
次のステップ
次のモジュールでは、支払いを安全に処理するための認証情報プロバイダを構築します。
販売者エージェントは、AP2 モデルを使用して、有効期限付きの拘束力のあるオファーを作成しました。次に、その CartMandate を読み取り、ユーザーの同意を得て、支払いを実行するエージェントが必要です。
認証情報プロバイダを構築し、AP2 認証情報チェーンを完成させましょう。
6. 認証情報プロバイダの構築 - 安全な支払い実行

拘束力のある提案から支払い実行まで
モジュール 5 では、IntentMandate を読み取り、有効期限が切れていないことを検証して、販売者の署名付きのバインディング CartMandate を作成するスペシャリストである Merchant Agent を構築しました。次に、その CartMandate を受け取って実際の支払いを行うエージェントが必要です。
ここで、AP2 の 3 つ目にして最後の原則である、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 チェーンの 3 番目、かつ最後の検証可能な認証情報です。
3 つの認証情報は、契約締結プロセスのようなものと考えてください。
- IntentMandate: 「これの購入に興味がある」(意向表明書)
- CartMandate: 「販売者である私は、この価格で販売することを提案します」(書面による見積もり)
- PaymentMandate: 「お支払い方法への請求を承認します」(署名済みの契約)
3 つの認証情報がすべて揃って初めて、支払いを実行できます。
PaymentMandate の構造
AP2 の PaymentMandate には、特定の構造があります。
payment_mandate = {
"payment_mandate_contents": { # ← AP2 wrapper
"payment_mandate_id": "payment_xyz123",
"payment_details_id": "cart_abc123", # Links to CartMandate
"user_consent": True,
"consent_timestamp": "2025-11-07T15:48:00Z",
"amount": {
"currency": "USD",
"value": "50.00"
},
"merchant_name": "Room to Read"
},
"agent_present": True, # Human-in-the-loop flow
"timestamp": "2025-11-07T15:48:00Z"
}
主要コンポーネント:
1. payment_mandate_contents - 以下を含む承認ラッパー:
- payment_mandate_id: 固有識別子
- payment_details_id: CartMandate にリンク
- user_consent: ユーザーが承認したかどうか
- amount: 支払い金額(CartMandate から抽出)
2. agent_present - これが人間参加型のフローかどうか
3. timestamp - 承認が作成された日時
Google のミッション: 認証情報プロバイダを構築する
認証情報プロバイダは次の処理を行います。
- 状態から CartMandate を読み取る(Merchant Agent が書き込んだもの)
- AP2 Pydantic モデルを使用して、カートの有効期限が切れていないことを確認する
- ネストされた構造から支払い情報を抽出する
- AP2 モデルを使用してユーザーの同意を得て PaymentMandate を作成する
- 決済処理をシミュレートする(本番環境では、実際の決済 API を呼び出す)
- PaymentMandate と支払い結果を状態に書き込む
ステップごとに作成していきましょう。
ステップ 1: カート有効期限検証ヘルパーを追加する
まず、CartMandate が期限切れになっていないことを検証するヘルパーを作成しましょう。これは、モジュール 5 で IntentMandate の期限切れを検証したのと同じ方法です。
👉 開く
charity_advisor/tools/payment_tools.py
有効期限の検証を追加しましょう。
👉 検索:
# MODULE_6_STEP_1_ADD_CART_EXPIRY_VALIDATION_HELPER
👉 この 1 行を次のコードに置き換えます。
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 作成ヘルパーを追加する
次に、公式の AP2 Pydantic モデルを使用して PaymentMandate 構造を構築するヘルパーを作成しましょう。
👉 検索:
# MODULE_6_STEP_2_ADD_PAYMENT_MANDATE_CREATION_HELPER
👉 この 1 行を次のコードに置き換えます。
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
👉 この 1 行を次のコードに置き換えます。
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 行を次のコードに置き換えます。
# 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
👉 この 1 行を次のコードに置き換えます。
# 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
👉 この 1 行を次のコードに置き換えます。
# 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
👉 この 1 行を次のコードに置き換えます。
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="""""",
👉 この 2 行を次のように置き換えます。
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=[],
👉 この 2 行を次のように置き換えます。
tools=[
FunctionTool(func=create_payment_mandate)
],
ステップ 7: Complete Credentials Provider を確認する
すべてが正しく配線されているか確認しましょう。
👉 完全な
charity_advisor/credentials_provider/agent.py
は次のようになります。
"""
Credentials Provider Agent - Handles payment processing with user consent.
This agent acts as our "Payment Processor."
"""
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.payment_tools import create_payment_mandate
credentials_provider = Agent(
name="CredentialsProvider",
model="gemini-2.5-flash",
description="Securely processes payments by creating PaymentMandates and executing transactions with user consent.",
tools=[
FunctionTool(func=create_payment_mandate)
],
instruction="""You are a payment specialist responsible for securely processing payments with user consent.
Your workflow:
1. Read the CartMandate from shared state.
The CartMandate was created by the Merchant Agent and has this structure:
- contents: AP2 wrapper containing:
- id: Cart identifier
- cart_expiry: When the cart expires
- merchant_name: Who is receiving payment
- payment_request: W3C PaymentRequest with transaction details
- merchant_authorization: Merchant's signature
2. Extract payment details from the nested structure:
- Navigate: cart_mandate["contents"]["payment_request"]["details"]["total"]["amount"]
- This gives you the currency and value
3. **IMPORTANT - Two-Turn Conversational Confirmation Pattern:**
Before calling create_payment_mandate, you MUST:
- Present the payment details clearly to the user
- Ask explicitly: "I'm ready to process a payment of $X to [Charity Name]. Do you want to proceed with this donation?"
- WAIT for the user's explicit confirmation (e.g., "yes", "proceed", "confirm")
- ONLY call create_payment_mandate AFTER receiving explicit confirmation
- If user says "no" or "cancel", DO NOT call the tool
4. After user confirms, use the create_payment_mandate tool to:
- Validate the CartMandate hasn't expired (CRITICAL security check)
- Create a PaymentMandate (the third AP2 credential)
- Simulate payment processing
- Record the transaction result
5. After processing, inform the user:
- That payment was processed successfully (this is a simulation)
- The transaction ID
- The amount and merchant
- That this completes the three-agent AP2 credential chain
IMPORTANT BOUNDARIES:
- Your ONLY job is creating PaymentMandates and processing payments
- You do NOT discover charities (that's Shopping Agent's job)
- You do NOT create offers (that's Merchant Agent's job)
- You MUST validate that the CartMandate hasn't expired before processing
- You MUST get explicit user confirmation before calling create_payment_mandate
- In production, this consent mechanism would be even more robust
WHAT IS A PAYMENTMANDATE:
A PaymentMandate is the final credential that authorizes payment execution. It:
- Links to the CartMandate (proving the merchant's offer)
- Records user consent
- Contains payment details extracted from the CartMandate
- Enables the actual payment transaction
This is the third and final verifiable credential in our secure payment system.
THE COMPLETE AP2 CREDENTIAL CHAIN:
1. Shopping Agent creates IntentMandate (user's intent)
2. Merchant Agent reads IntentMandate, creates CartMandate (merchant's binding offer)
3. You read CartMandate, get user confirmation, create PaymentMandate (authorized payment execution)
Each credential:
- Has an expiry time (security feature)
- Links to the previous credential
- Is validated before the next step
- Creates an auditable chain of trust"""
)
✅ チェックポイント: AP2 Pydantic モデルを使用して、適切な CartMandate の読み取りと PaymentMandate の作成を行う完全な認証情報プロバイダが完成しました。
ステップ 8: 認証情報プロバイダをテストする
次に、エージェントが支払いを正しく処理し、認証情報チェーンを完了することを確認しましょう。
👉 Cloud Shell ターミナルで、次のコマンドを実行します。
python scripts/test_credentials_provider.py
想定される出力:
======================================================================
CREDENTIALS PROVIDER TEST (MOCK - NO CONFIRMATION)
======================================================================
Simulated CartMandate from Merchant Agent:
- Cart ID: cart_test123
- Merchant: Room to Read
- Amount: $50.00
- Expires: 2025-11-07T15:47:16Z
- Signature: SIG_test_signature
Calling Credentials Provider to process payment...
======================================================================
INFO:charity_advisor.tools.payment_tools:Tool called: Creating PaymentMandate and processing payment
INFO:charity_advisor.tools.payment_tools:CartMandate valid. Expires in 900 seconds
INFO:charity_advisor.tools.payment_tools:Payment processed successfully: txn_a3f7b2c8d9e1f4a2
======================================================================
CREDENTIALS PROVIDER RESPONSE:
======================================================================
I've successfully processed your payment. Here are the details:
**Payment Completed** (Simulated)
- Transaction ID: txn_a3f7b2c8d9e1f4a2
- Amount: USD 50.00
- Merchant: Room to Read
- Status: Completed
This completes the three-agent AP2 credential chain:
1. ✓ Shopping Agent created IntentMandate (your intent)
2. ✓ Merchant Agent created CartMandate (binding offer)
3. ✓ Credentials Provider created PaymentMandate (payment authorization)
Your donation has been processed securely through our verifiable credential system.
======================================================================
PAYMENTMANDATE CREATED:
======================================================================
Payment Mandate ID: payment_3b4c5d6e7f8a
Linked to Cart: cart_test123
User Consent: True
Amount: USD 50.00
Merchant: Room to Read
Agent Present: True
======================================================================
======================================================================
PAYMENT RESULT:
======================================================================
Transaction ID: txn_a3f7b2c8d9e1f4a2
Status: completed
Amount: USD 50.00
Merchant: Room to Read
Simulation: True
======================================================================
ステップ 9: 3 つのエージェントからなるパイプライン全体をテストする
3 つのエージェントが連携して動作することをテストしてみましょう。
👉 パイプライン全体のテストを実行する:
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 認証情報チェーンの全体像です。
各エージェント:
- 状態から認証情報を読み取ります
- Pydantic モデルを使用して検証する(構造と有効期限のチェック)
- AP2 モデルを使用して次の認証情報を作成します。
- 次のエージェントの状態に書き込む
作成した内容
Pydantic モデルと支払いシミュレーションを使用して、適切な構造検証を行う AP2 3 エージェント認証情報チェーンを正常に完了しました。
習得した主なコンセプト
✅ 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 は構造エラーを自動的にキャッチする
✅ カートの有効期限の検証:
- 検証済みの
CartMandatePydantic モデルを受け入れます。 cart.contents.cart_expiryからの読み取り(属性アクセス)- 古いカートの処理を防ぐセキュリティ機能
- インテント(1 時間)よりも短い時間(15 分)
✅ お支払いのシミュレーション:
- 実際の決済代行業者の教育用モック
- トランザクション ID を生成する
- payment_result を状態に記録します。
- シミュレーションであることが明確に示されている(simulation: True フラグ)
✅ モデルを使用した AP2 チェーンを完了する:
- 3 つのエージェント、3 つの認証情報、3 つの Pydantic 検証
- 各エージェントは、モデルを使用して以前の認証情報の構造を検証します。
- 各認証情報は監査証跡のために前の認証情報にリンク
- 状態ベースのハンドオフによりロールの分離を維持
- チェーン全体の型安全性
✅ モデル駆動型開発:
model_validate()による入力検証- ネストされたモデルを使用したタイプセーフな構築
model_dump(mode='json')による自動シリアル化- 最初からプロダクション レディなパターン
次のステップ
次のモジュールでは、3 つのスペシャリスト エージェントをすべて調整するオーケストレーター エージェントを構築します。
AP2 Pydantic モデルを使用して、3 つの強力なスペシャリスト エージェントを構築しました。次に、これらをシームレスな寄付エクスペリエンスにオーケストレートするコンダクターを構築しましょう。
オーケストレーターを構築して、システム全体が動作する様子を見てみましょう。
7. オーケストレーション - すべてをまとめる
スペシャリストからシームレスなエクスペリエンスへ
これまでのモジュールで、次の 3 つの専門エージェントを構築しました。
- ショッピング エージェント: チャリティを検索し、IntentMandate を作成します。
- Merchant Agent: IntentMandate から CartMandate を作成します。
- 認証情報プロバイダ: PaymentMandate を作成し、支払いを処理します。
これらのエージェントは、自然に次の 2 つのフェーズに分類されます。
- フェーズ 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 が作成されている
- ✅ 各エージェントは分離されたコンテキストで実行される
- ✅ 状態は認証情報チェーンを介して前方に流れる
Google の使命: 完全なシステムを構築する
2 つのレイヤを構築します。
レイヤ 1: 処理パイプライン(SequentialAgent)
- Merchant と Credentials を結び付ける
- 慈善団体が選択されると、自動的に順番に実行されます。
- オファーと支払いの原子的な実行
レイヤ 2: ルート オーケストレーター(ユーザー向けエージェント)
- 親しみやすい性格
- 慈善団体の選択を shopping_agent に委任します
- IntentMandate の作成後に処理パイプラインに委任する
- 会話とフェーズの移行を処理する
この 2 層アプローチは、次のような自然な流れに沿っています。
- ショッピング フェーズ: マルチターン会話(ユーザーが閲覧、質問、決定)
- 処理フェーズ: アトミックな実行(オファー → 支払い)
両方を作成しましょう。
ステップ 1: オーケストレーション コンポーネントをインポートする
まず、必要なインポートを含むオーケストレーション ファイルを設定しましょう。
👉 開く
charity_advisor/agent.py
まず、インポートから始めましょう。
👉 検索:
# MODULE_7_STEP_1_IMPORT_COMPONENTS
👉 この 1 行を次のコードに置き換えます。
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
👉 この 2 行を次のように置き換えます。
# 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)の 3 つの部分で構成されます。
👉 検索:
# MODULE_7_STEP_3A_CREATE_ROOT_AGENT_SETUP
👉 この 1 行を次のコードに置き換えます。
# 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
👉 この 1 行を次のコードに置き換えます。
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
👉 この 1 行を次のコードに置き換えます。
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 が作成されない)
- ショッピングと販売者の間で 1 時間が経過した(インテントの有効期限が切れた)
- 状態が破損またはクリアされる
- ユーザーがショッピングを介さずに販売者に直接電話をかけようとしている
コールバックはアーキテクチャの適用を強化します。エージェントが 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 が表示されます。

👉 プルダウンからエージェントを選択する:
ADK ウェブ UI の上部にプルダウン メニューが表示されます。リストから [charity_advisor] を選択します。

ADK ウェブ インターフェースに次の項目が表示されます。
- チャットパネル: 左側。会話用
- トレースパネル: 右側、オブザーバビリティ用(モジュール 9 で使用)
テスト 1: 寄付フローを完了する(通常ケース)
👉 チャット インターフェースで、次のように入力します。
I want to donate to an education charity
フロー全体を実際に確認する


何が起きているか(右側のトレースパネルに表示されます):
1. アドバイザーが 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 を検証する(✓ 合格) ← NEW!
- 販売者エージェントが署名付きの CartMandate を作成する
- 認証情報のコールバックが CartMandate を検証する(✓ 合格) ← NEW!
- 認証情報プロバイダが支払いを準備する
6. 決済処理:
- 認証情報プロバイダが PaymentMandate を作成する
- 決済処理をシミュレートする
- 返品取引 ID
7. アドバイザーが要約する:
これで終了です。寄付の手続きが完了しました。🎉
詳細:
- 金額: $50.00
- 慈善団体: Room to Read(EIN: 77-0479905)
- 取引 ID: txn_a3f7b2c8d9e1f4a2
テスト 2: コールバックがエラーをキャッチすることを確認する(オプションの詳細テスト)
コールバックがエラーをキャッチする様子を確認するには、状態を手動で破損させる必要があります(高度なデバッグ)。ただし、本番環境では、コールバックが以下をキャッチします。
- ショッピング エージェント ツールが失敗する → 販売者のコールバック ブロック: 「エラー: カートを作成できません...」
- 2 時間経過 → 販売者のコールバックがブロックされる: 「エラー: インテントの有効期限が切れています...」
- カートの有効期限が切れた → 認証情報のコールバックがブロックされる: 「エラー: カートの有効期限が切れました(15 分制限)...」
これらのエッジケースは、検証コールバックによってアーキテクチャ的に適用されるようになりました。
作成した内容
3 つの専門エージェントを、アーキテクチャ検証を備えたシームレスで信頼性の高いシステムにオーケストレートしました。
次のステップ
これで、信頼できるエージェントを構築するための技術的なコアが完成しました。
これで、認証情報チェーンをローカルで適用する、信頼性の高い完全なシステムが構築されました。次に、本番環境へのデプロイを通じて実際のユーザーがアクセスできるようにし、モジュール 9 を可能にする説明責任の追跡を有効にします。
強化されたエージェントを Google Cloud にデプロイしましょう。
8. デプロイ

これで、ローカルで動作する 3 つの専用エージェントを備えた、信頼できる寄付システムが完成しました。
ただし、これは開発マシンでのみ実行されます。このシステムを実際のユーザーにとって有用なものにし、信頼性を証明する説明責任の証跡を収集するには、本番環境にデプロイする必要があります。
このモジュールでは、初日からオブザーバビリティを有効にしてエージェントを Google Cloud にデプロイする方法について説明します。デプロイ時に使用する --trace_to_cloud フラグは、モジュール 9 で説明した説明責任の追跡を可能にするものです。
デプロイ オプションについて
ADK は複数のデプロイ ターゲットをサポートしています。それぞれ、複雑さ、セッション管理、スケーリング、費用に関する特性が異なります。
要素 | ローカル( | Agent Engine | Cloud Run |
複雑さ | 最小 | 低 | 中 |
セッションの永続性 | インメモリのみ(再起動すると失われる) | Vertex AI マネージド(自動) | Cloud SQL(PostgreSQL)またはインメモリ |
インフラストラクチャ | なし(開発マシンのみ) | フルマネージド | コンテナ + オプションのデータベース |
コールド スタート | なし | 100 ~ 500 ミリ秒 | 100 ~ 2,000 ミリ秒 |
スケーリング | 単一インスタンス | 自動 | 自動(ゼロまで) |
費用モデル | 無料(ローカル コンピューティング) | コンピューティング ベース | リクエスト ベース + 無料枠 |
UI サポート | あり(組み込み済み) | いいえ(API のみ) | はい( |
オブザーバビリティの設定 | ローカル トレース ビューア |
|
|
最適な用途 | 開発とテスト | 本番環境エージェント | 本番環境エージェント |
推奨事項: この信頼できる寄付システムでは、次の理由から、本番環境のプライマリ デプロイとして Agent Engine をおすすめします。
- フルマネージド インフラストラクチャ(管理対象のコンテナなし)
VertexAiSessionServiceによる組み込みのセッションの永続性- コールド スタートなしの自動スケーリング
- デプロイの簡素化(Docker の知識は不要)
- Cloud Trace の統合がすぐに利用可能
追加オプション: Google Kubernetes Engine(GKE)
Kubernetes レベルの制御、カスタム ネットワーキング、マルチサービス オーケストレーションが必要な上級ユーザーは、GKE デプロイを使用できます。このオプションは柔軟性が最も高いものの、より多くの運用上の専門知識(クラスタ管理、マニフェスト、サービス アカウント)が必要です。
GKE のデプロイについては、この Codelab では説明しませんが、ADK GKE デプロイガイドに詳しく記載されています。
前提条件
1. Google Cloud プロジェクトのセットアップ
課金が有効になっている Google Cloud プロジェクトが必要です。お持ちでない場合は、
- プロジェクトを作成する: Google Cloud コンソール
- 課金を有効にする: 課金を有効にする
- プロジェクト ID(プロジェクト名やプロジェクト番号ではない)をメモします。
2. 再認証(省略可)
Google Cloud で認証する
gcloud auth application-default login
gcloud config set project YOUR_PROJECT_ID
YOUR_PROJECT_ID は、実際の Google Cloud プロジェクト ID に置き換えます。
認証を確認します。
gcloud config get-value project
# Should output: YOUR_PROJECT_ID
3. 環境変数
次のコマンドを使用して、.env ファイルを自動入力します。
# Get your current Project ID
PROJECT_ID=$(gcloud config get-value project)
STAGING_BUCKET_VALUE="gs://${PROJECT_ID}-staging"
ENV_FILE=".env"
# Check if STAGING_BUCKET is already set in the .env file
if grep -q "^STAGING_BUCKET=" "${ENV_FILE}"; then
# If it exists, replace the line
# The sed command finds the line starting with STAGING_BUCKET= and replaces the entire line.
# Using | as a delimiter to avoid issues with slashes in the bucket name.
sed -i "s|^STAGING_BUCKET=.*|STAGING_BUCKET=${STAGING_BUCKET_VALUE}|" "${ENV_FILE}"
echo "Updated STAGING_BUCKET in ${ENV_FILE}"
else
# If it doesn't exist, add it to the end of the file
echo "STAGING_BUCKET=${STAGING_BUCKET_VALUE}" >> "${ENV_FILE}"
echo "Added STAGING_BUCKET to ${ENV_FILE}"
fi
# Verify it was added or updated correctly
echo "Current STAGING_BUCKET setting:"
grep "^STAGING_BUCKET=" "${ENV_FILE}"
以下のように表示されます。
STAGING_BUCKET=gs://your-actual-project-id-staging
注意事項:
YOUR_PROJECT_IDは、実際のプロジェクト ID に置き換えます(または上記のコマンドを使用します)。GOOGLE_CLOUD_LOCATIONには、サポート対象の地域を使用します。- デプロイ スクリプトを実行したときにステージング バケットが存在しない場合は、自動的に作成されます。
4. 必要な API の有効化
デプロイ プロセスでは、いくつかの Google Cloud APIs を有効にする必要があります。次のコマンドを実行して有効にします。
gcloud services enable \
aiplatform.googleapis.com \
storage.googleapis.com \
cloudbuild.googleapis.com \
cloudtrace.googleapis.com \
compute.googleapis.com
このコマンドにより、次のものが有効になります。
- AI Platform API - Agent Engine と Vertex AI モデル用
- Cloud Storage API - ステージング バケット用
- Cloud Build API - コンテナのビルド用(Cloud Run)
- Cloud Trace API - オブザーバビリティと説明責任のトレイル
- Compute Engine API - サービス アカウント管理用
ステップ 1: デプロイ インフラストラクチャを理解する
プロジェクトには、すべてのデプロイモードを処理する統合デプロイ スクリプト(deploy.sh)が含まれています。
👉 デプロイ スクリプトを確認する(省略可):
cat deploy.sh
このスクリプトには、次の 3 つのデプロイモードがあります。
./deploy.sh local- メモリ内ストレージを使用してローカルで実行する./deploy.sh agent-engine- Vertex AI Agent Engine にデプロイする(推奨)./deploy.sh cloud-run- オプションの UI を使用して Cloud Run にデプロイする
仕組み:
Agent Engine のデプロイの場合、スクリプトは次の処理を実行します。
adk deploy agent_engine \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
--staging_bucket=$STAGING_BUCKET \
--display_name="Charity Advisor" \
--trace_to_cloud \
charity_advisor
Cloud Run のデプロイの場合、次のコマンドを実行します。
adk deploy cloud_run \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
--service_name="charity-advisor" \
--app_name="charity_advisor" \
--with_ui \
--trace_to_cloud \
charity_advisor
--trace_to_cloud フラグは、どちらのデプロイタイプでも重要です。このフラグにより、モジュール 9 で説明する説明責任トレイルの Cloud Trace 統合が有効になります。
ステップ 2: Agent Engine ラッパーを準備する
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を構成します。
ステップ 3: Agent Engine にデプロイする(推奨)
Agent Engine は、組み込みのセッション永続性を備えたフルマネージド インフラストラクチャを提供するため、信頼できる寄付システムに推奨される本番環境デプロイです。
Deployment を実行する
プロジェクトのルートから、次のコマンドを実行します。
chmod +x deploy.sh
./deploy.sh agent-engine
デプロイ フェーズ
スクリプトが次のフェーズを実行するのを確認します。
Phase 1: API Enablement
✓ aiplatform.googleapis.com
✓ storage.googleapis.com
✓ cloudbuild.googleapis.com
✓ cloudtrace.googleapis.com
✓ compute.googleapis.com
Phase 2: IAM Setup
✓ Getting project number
✓ Granting Storage Object Admin
✓ Granting Vertex AI User
✓ Granting Cloud Trace Agent
Phase 3: Staging Bucket
✓ Creating gs://your-project-id-staging (if needed)
✓ Setting permissions
Phase 4: Validation
✓ Checking agent.py exists
✓ Verifying root_agent defined
✓ Checking agent_engine_app.py exists
✓ Validating requirements.txt
Phase 5: Build & Deploy
✓ Packaging agent code
✓ Uploading to staging bucket
✓ Creating Agent Engine instance
✓ Configuring session persistence
✓ Setting up Cloud Trace integration
✓ Running health checks
このプロセスでは、エージェントをパッケージ化して Vertex AI インフラストラクチャにデプロイするため、5 ~ 10 分かかります。
Agent Engine ID を保存する
デプロイが成功すると、次のようになります。
✅ Agent Engine created successfully!
Agent Engine ID: 7917477678498709504
Resource Name: projects/123456789/locations/us-central1/reasoningEngines/7917477678498709504
Endpoint: https://us-central1-aiplatform.googleapis.com/v1/...
⚠️ IMPORTANT: Save the Agent Engine ID from the output above
Add it to your .env file as:
AGENT_ENGINE_ID=7917477678498709504
This ID is required for:
- Testing the deployed agent
- Updating the deployment later
- Accessing logs and traces
.env ファイルをすぐに更新してください。
echo "AGENT_ENGINE_ID=7917477678498709504" >> .env
デプロイされたもの
Agent Engine のデプロイに次の機能が追加されました。
✅ 3 つのエージェントすべて(ショッピング、販売者、認証情報)がマネージド ランタイムで実行されている
✅ 完全な認証情報チェーン ロジック(Intent → Cart → Payment mandates)
✅ 確認ワークフローを備えたユーザーの同意メカニズム
✅ 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
確認チェックリスト
テスト後、以下を確認します。
✅ エージェントがクエリに応答する
✅ 3 つのエージェントすべてが順番に実行される(ショッピング → 販売者 → 認証情報)
✅ 同意メカニズムが有効になる(確認がリクエストされる)
✅ セッションがリクエスト間で維持される
✅ 認証エラーが発生しない
✅ 接続タイムアウトが発生しない
エラーが発生した場合:
- 環境変数が正しく設定されていることを確認する
- API が有効になっていることを確認する:
gcloud services list --enabled - Vertex AI コンソールで Agent Engine のログを確認する
agent_engine_app.pyファイルがcharity_advisorフォルダに存在することを確認します。
ステップ 5: Cloud Run にデプロイする(省略可)
本番環境へのデプロイを効率化するには Agent Engine が推奨されますが、Cloud Run はより詳細な制御が可能で、ADK ウェブ UI をサポートしています。このセクションは省略可能です。
Cloud Run を使用するタイミング
次のような場合は、Cloud Run を選択します。
- ユーザー操作用の ADK ウェブ UI
- コンテナ環境を完全に制御
- カスタム データベース構成
- 既存の Cloud Run サービスとの統合
Deployment を実行する
chmod +x deploy.sh
./deploy.sh cloud-run
相違点:
このスクリプトによって、次の処理が自動的に行われます。
- エージェント コードを使用して Docker コンテナをビルドする
- Cloud SQL PostgreSQL データベースを作成する(必要な場合)
- データベース接続を構成する
- ADK ウェブ UI を有効にしてデプロイする
Cloud SQL のプロビジョニングにより、デプロイには 10 ~ 15 分かかります。
セッション管理:
VertexAiSessionServiceではなくDatabaseSessionServiceを使用する.envのデータベース認証情報(または自動生成された認証情報)が必要です。- 状態は PostgreSQL データベースに保持される
UI のサポート:
- ウェブ UI の利用可能場所:
https://charity-advisor-xyz.a.run.app
Cloud Run のデプロイをテストする
--with_ui を使用して Cloud Run にデプロイした場合は、ブラウザで直接テストできます。
- サービス URL に移動します(デプロイ出力に表示されます)。
- ADK ウェブ インターフェースが表示されます。プルダウンからエージェントを選択します。
- テスト寄付を開始する:
I want to donate $50 to a children's education charity
- 実行フローを確認します。
- ShoppingAgent が慈善団体を見つけて、ユーザーの意図を保存します
- MerchantAgent がカート委任を作成する
- CredentialsProvider が自動支払いの承認を作成し、確認をリクエストする
- 確認後、お支払いが処理されます
- レスポンスに次のものが含まれていることを確認します。
- 慈善団体のおすすめ
- 確認リクエスト
- 承認後の成功メッセージ
トラブルシューティング
一般的な問題
問題: ERROR: GOOGLE_CLOUD_PROJECT is not set
解決策: .env ファイルに正しいプロジェクト ID が含まれていることを確認します。
GOOGLE_CLOUD_PROJECT=your-actual-project-id
問題: ステージング バケットが自動的に作成されない
解決策: スクリプトでバケットが自動的に作成されるようにします。存在しない場合は、手動で作成します。
gsutil mb -p $GOOGLE_CLOUD_PROJECT -l $GOOGLE_CLOUD_LOCATION $STAGING_BUCKET
概要
次の操作が正常に完了しました。
✅ deploy.sh が提供するデプロイ インフラストラクチャを理解した
✅ Agent Engine ラッパーの構成を確認した
✅ 信頼できる寄付システムを Agent Engine にデプロイした(推奨)
✅ --trace_to_cloud との Cloud Trace 統合を有効にした
✅ エージェントがアクセス可能で機能していることを確認した
✅ モジュール 9 で説明責任トレイルの基盤を作成した
次のモジュールでは、このフラグによって何が実現されるのかを詳しく見ていきます。具体的には、すべての寄付、すべての同意の瞬間、認証情報チェーンのすべてのステップを完全に可視化できます。
9. オブザーバビリティ


モジュール 1 では、AI エージェントがお金を扱う際の根本的な問題、つまり何が起こったかをどのように証明するかについて学びました。
お客様から次のような申し立てを受けることがあります。
- 「その慈善団体を選んだ覚えはありません」
- 「この支払いを承認した覚えはありません。」
- 「同意していないのに請求された」
従来のブラックボックス AI システムでは、そうでないことを証明する方法はありません。しかし、信頼できる寄付システムは異なります。モジュール 8 では、--trace_to_cloud フラグを使用してデプロイしました。これは、すべての寄付が Cloud Trace で完全な改ざん防止監査証跡を作成することを意味します。
このモジュールでは、これらのトレースを読み取り、証拠として使用する方法を学びます。学習する内容:
- Cloud Trace エクスプローラに移動して本番環境のトレースを見つける
- ウォーターフォール ビューを読んで実行フローを理解する
- 認証情報チェーン(インテント → カート → 自動支払いの承認)を確認する
- タイムスタンプ証明で同意の瞬間を特定する
- トレースを使用して異議申し立てを解決する
- コンプライアンスと監査のためにトレースをエクスポートする
これこそが、信頼できるシステムと、能力は高いものの不透明なシステムを分けるものです。つまり、何が起こったかをフォレンジックの精度で証明できる能力です。
トレースとスパンについて
Cloud Trace でトレースを表示する前に、表示内容を理解する必要があります。
トレースとは
トレースは、エージェントが 1 つのリクエストを処理する完全なタイムラインです。ユーザーがクエリを送信してから最終的なレスポンスが返されるまでのすべてをキャプチャします。
各トレースには次の情報が表示されます。
- リクエストの合計時間
- 実行されたすべてのオペレーション
- オペレーションの相互関係(親子関係)
- 各オペレーションの開始時刻と終了時刻
- 成功または失敗のステータス
チャリティ エージェントの場合: 1 つのトレース = 「寄付したい」から「支払いが完了しました」までの 1 つの完全な寄付フロー。
スパンとは
スパンは、トレース内の単一の作業単位を表します。スパンは、トレースの構成要素と考えることができます。
寄付システムにおける一般的なスパンタイプ:
スパンタイプ | 意味内容 | 例 |
| エージェントの実行 |
|
| 言語モデルへのリクエスト |
|
| ツール関数の実行 |
|
| セッション メモリからの読み取り | 状態から |
| セッション メモリへの書き込み |
|
各スパンには次のものが含まれます。
- 名前: このオペレーションが表すもの
- 所要時間(開始時間 → 終了時間)
- 属性: ツールの入力、モデルのレスポンス、トークン数などのメタデータ
- ステータス: 成功(
OK)またはエラー(ERROR) - 親子関係: どのオペレーションがどのオペレーションをトリガーしたか
スパンがトレースを形成する仕組み
スパンは相互にネストされ、因果関係を示します。
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 にアクセスする
次に、デプロイされたエージェントからの実際のトレースを確認しましょう。
Cloud Trace に移動する
- Google Cloud コンソール(console.cloud.google.com)を開きます。
- 上部のプルダウンからプロジェクトを選択します(プロジェクトで作業していた場合は、あらかじめ選択されているはずです)。
- Cloud Trace エクスプローラに移動します。
- 左側のサイドバーで、[オブザーバビリティ] セクションまでスクロールします。
- [Trace] をクリックします。
- または、直接リンク(console.cloud.google.com/traces/list)を使用します。
表示される内容
Trace エクスプローラには、プロジェクトのすべてのトレースのリストが表示されます。
列 | 表示内容 |
リクエスト | HTTP メソッドとエンドポイント(API リクエストの場合) |
開始時間 | リクエストが開始された時刻 |
レイテンシ | リクエストの合計時間 |
スパン | トレース内のオペレーション数 |
各行は、デプロイされたエージェントに対する 1 つの完全なリクエストを表します。
テストトレースを生成する(必要な場合)
トレースがまだ表示されない場合は、次の理由によりリストが空になっている可能性があります。
- デプロイされたエージェントに対するリクエストはまだありません
- リクエスト後、トレースが表示されるまでに 1 ~ 2 分かかります
テストトレースを生成する:
UI を使用して Cloud Run にデプロイした場合は、サービス URL にアクセスして、ブラウザで寄付を完了します。
Agent Engine にデプロイした場合は、モジュール 8 のテスト スクリプトを実行します。
python scripts/test_deployed_agent.py
1 ~ 2 分待ってから、Cloud Trace エクスプローラのページを更新します。トレースが表示されます。
トレースをフィルタ
上部のフィルタ オプションを使用して、特定のトレースを検索します。
- 期間: 必要に応じて、[過去 1 時間] から [過去 24 時間] に変更します。
- 最小レイテンシ / 最大レイテンシ: 遅いリクエストをフィルタします。
- リクエスト フィルタ: 特定のオペレーション(「DonationPipeline」など)で検索します。
このモジュールでは、期間が長い(5 秒超)トレースに注目します。これは、3 つのエージェントすべてが実行される完全な寄付フローを表しているためです。
ステップ 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]
グラフの読み方
各バーはスパンを表します。
- 水平方向の位置: 開始時刻
- 長さ: 所要時間
- インデント: 親子関係を示します。
- 色: 通常は正常な場合は青、エラーの場合は赤
このトレース例から得られる主な観察結果は次のとおりです。
✅ 合計時間: 8.2 秒
✅ 順次実行: ShoppingAgent は MerchantAgent が開始する前に完了
✅ MerchantAgent が完了
before
CredentialsProvider started
✅ Consent was the longest operation: 3.0 seconds for create_payment_mandate (because it waited for user confirmation)
✅ LLM calls are visible: Each agent made one Gemini request
✅ Tool calls are captured: All six tools executed successfully
このビジュアルにより、どこに時間がかかっているか、どのような順序でオペレーションが実行されたかがすぐにわかります。
スパンをクリックして詳細を表示
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 UTC に記録されました
- ✅ 署名が生成された(本番環境では暗号化される)
IntentMandate がセッション状態になり、後続のエージェントで使用できるようになりました。
CartMandate を確認する
[execute_tool: create_cart_mandate] スパン(MerchantAgent の下)をクリックします。
属性パネルで、次の操作を行います。
{
"tool.name": "create_cart_mandate",
"tool.input.intent_mandate": {
"charity_name": "Save the Children",
"amount": 50,
"signature": "a3f7b9c1d2e4..."
},
"tool.output.status": "success",
"tool.output.cart_mandate": {
"cart_id": "cart_7893",
"intent_signature": "a3f7b9c1d2e4...",
"cart_signature": "e8f2a9b3c7d1...",
"timestamp": "2024-11-08T15:30:14.789Z"
}
}
これは次のことを証明しています。
- ✅ MerchantAgent が IntentMandate を受信した(入力に表示されている)
- ✅ ID「cart_7893」のカートが作成されました
- ✅ カートの署名が IntentMandate の署名を参照している(チェーンリンク)
- ✅ 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 UTC に確認済み
- ✅ システムはユーザーの決定を 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 は、何が起こったかを証明するだけでなく、どこで時間が費やされているかを示し、最適化を可能にします。
クリティカル パスを特定する
ウォーターフォール ビューで、垂直スタックの最長スパンを探します。これらはパフォーマンスのボトルネックを表しています。
トレースの例から、次のことがわかります。
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
}
この API は次の用途に使用できます。
- リクエストあたりの費用を追跡する(トークン × モデルの料金)
- 不必要に長いプロンプトを特定する
- モデルのパフォーマンスを比較する(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% 超にエラーが含まれている場合にアラートを作成します。
- Cloud Monitoring に移動します。
- [Alerting] → [Create Policy] をクリックします。
- 構成:
Resource: Cloud Trace Span Metric: Span error count Condition: Rate > 5% over 5 minutes Notification: Email your-team@example.com
高レイテンシに関するアラート
p95 レイテンシが 15 秒を超えた場合にアラートを作成します。
Resource: Cloud Trace
Metric: Span duration (95th percentile)
Condition: > 15000ms for 5 minutes
Notification: PagerDuty
これにより、ユーザー エクスペリエンスに影響が及ぶ前にパフォーマンスの低下を検出できます。
同意がない場合のアラート
確認なしで決済処理が行われた場合にアラートを作成します。
Resource: Cloud Trace Span
Filter: tool.name="create_payment_mandate" AND tool.confirmation_required!=true
Condition: Any match
Notification: Critical alert to security team
これは安全違反検出機能です。この機能が作動した場合、同意メカニズムに重大な問題があります。
学習した内容
Cloud Trace を使用して、次の方法を理解しました。
✅ Cloud Trace Explorer を操作して本番環境のトレースを見つける
✅ ウォーターフォール ビューを読み取って完全な実行フローを確認する
✅ IntentMandate → CartMandate → PaymentMandate の認証情報チェーンをトレースする ✅ 異議申し立ての解決にトレースを証拠として使用する
✅ パフォーマンスを分析してボトルネックを特定する
✅ LLM の費用を詳細に追跡する
これによる違い
「こんな取引は承認していない」という同じ苦情を処理する 2 つのシステムを比較してみましょう。
オブザーバビリティのないシステム
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):
- ✅ 役割が分かれた 3 つの専門エージェント
- ✅ 3 つの検証可能な認証情報(インテント → カート → 自動支払いの承認)
- ✅ 各ステップで有効期限の検証を行う完全な認証情報チェーン
- ✅ タイムスタンプ証明付きの明示的な同意メカニズム
- ✅ オブザーバビリティを備えた Agent Engine への本番環境デプロイ
- ✅ Cloud Trace での完全な説明責任の追跡
- ✅ 異議申し立ての解決のためのフォレンジック証拠
ワークショップと本番環境のギャップ
システムは正しいアーキテクチャとパターンを示していますが、教育用の簡素化を使用しているため、実際のお金と実際のユーザー向けにアップグレードする必要があります。
簡素化された内容と、本番環境で必要な内容は次のとおりです。
コンポーネント | ワークショップの実施 | 本番環境の要件 |
署名 | デモ用の SHA-256 ハッシュ( | PKI または秘密鍵を使用した JWT を使用した実際の暗号署名 |
決済処理 | シミュレートされた返品( | 実際の決済 API(Stripe、PayPal、Square)との統合 |
ユーザー認証 | 暗黙的な信頼(ログインは不要) | OAuth 2.0、WebAuthn、セッション管理 |
シークレット管理 |
| Google Secret Manager または Cloud KMS(暗号化あり) |
慈善団体データベース | 9 つの慈善団体を含むモック JSON ファイル | ライブ API 統合(IRS Tax Exempt Organization Search、Charity Navigator API) |
エラー処理 | エラー メッセージを含む基本的な try-catch | 指数バックオフ、回路ブレーカー、デッドレター キューを使用した再試行ロジック |
テスト | スクリプトによる手動検証 | CI / CD を使用した包括的な単体 / 統合 / E2E テストスイート |
セッションの永続性 | インメモリ(ローカル)または自動(Agent Engine) | バックアップと障害復旧を備えた本番環境データベース |
レート制限 | なし(教育環境) | ユーザーごとのレート制限、IP ベースのスロットリング、不正行為の検出 |
習得した主なアーキテクチャ パターン
このワークショップで学習したパターンは、本番環境のパターンです。疑わないでください。
ロールの分離(AP2 原則 1)
各エージェントには明確なジョブが 1 つあり、必要な情報のみを参照します。1 つのエージェントが侵害されても、攻撃者は他のエージェントのデータにアクセスできません。これにより、影響範囲を限定できます。
これを使用する本番環境システム: 決済処理、ドキュメント ワークフロー、承認チェーン、検証ゲート付きのマルチステップ フォーム。
検証可能な認証情報(AP2 原則 2)
各認証情報には有効期限があり、前の認証情報を参照します。また、次のステップに進む前に検証が必要です。これにより、改ざんを検知できる監査チェーンが作成されます。
プロダクション バリュー: 何が、いつ、どのような順序で起こったかを完全に証明します。異議申し立ての解決と規制遵守に不可欠。
明示的な同意(AP2 原則 3)
ユーザーがアクションを承認したことを示すタイムスタンプ。異議申し立てはできません。
プロダクション値: 金融トランザクションの法的要件。ユーザーと企業の両方を保護します。
シーケンシャル オーケストレーション(ADK パターン)
正しい実行順序を強制適用する。ステップをスキップできないようにします。各エージェントが前のエージェントの出力を確認できるようにします。
プロダクション バリュー: ユーザーが即時の結果を期待する人間参加型システムに最適です。これは、寄付フロー、購入手続き、承認チェーンに適したパターンです。
完全なオブザーバビリティ(OpenTelemetry + Cloud Trace)
すべての決定、ツール呼び出し、同意のタイミング、認証情報の引き渡しが自動的にキャプチャされます。
プロダクションの価値: 紛争のフォレンジック証拠。パフォーマンス最適化データ。コンプライアンス監査証跡。本番環境の問題を正確にデバッグします。
継続学習用の資料
ADK ドキュメント:
AP2 と関連基準:
Google Cloud サービス:
リソースをクリーンアップする
継続的な課金が発生しないようにするには、デプロイを削除します。
Agent Engine: Agent Engine のドキュメントの手順に沿って操作します。
Cloud Run(デプロイされている場合):
gcloud run services delete charity-advisor \
--region=$GOOGLE_CLOUD_LOCATION
ストレージ バケット:
gsutil -m rm -r gs://$GOOGLE_CLOUD_PROJECT-staging
gsutil -m rm -r gs://$GOOGLE_CLOUD_PROJECT-artifacts
取り組みの継続
簡単な質問から始めて、完全な回答を構築しました。信頼できる AI エージェントの基本パターンを習得しました。これらのパターンは、AI エージェントが機密性の高いオペレーション(金融取引、医療上の意思決定、法的文書、サプライ チェーン オペレーションなど)を処理するあらゆるドメインに適用できます。
原則は移行します。信頼モデルが機能している。
さあ、信頼できるものを作りましょう。❤️
