สร้างแชทบอทการกุศลที่เชื่อถือได้ด้วย Google ADK และ AP2

1. การสร้างความไว้วางใจเพื่อปลดล็อกความเอื้ออาทร

แบนเนอร์

ช่วงเวลาแห่งแรงบันดาลใจ

โทรศัพท์ของคุณสั่น คุณเห็นข่าวเกี่ยวกับโครงการส่งเสริมการอ่านออกเขียนได้ที่ประสบความสำเร็จในการช่วยให้เด็กๆ ในชุมชนด้อยโอกาสได้เรียนรู้การอ่าน คุณรู้สึกอยากมีส่วนร่วมอย่างมาก คุณเปิดเบราว์เซอร์และค้นหา "การบริจาคเพื่อโครงการส่งเสริมการอ่านออกเขียนได้ของเด็ก"

google search

ผลการค้นหาหลายร้อยรายการจะปรากฏขึ้น

คุณคลิกลิงก์แรก เว็บไซต์ดูเป็นมืออาชีพ คุณเลื่อนลงไปที่ข้อมูลทางการเงินของบริษัท "ค่าใช้จ่ายในการดูแลระบบ: 28%" คุณหยุดชั่วคราว เงินบริจาคทุกๆ 1 ดอลลาร์จะนำไปใช้สนับสนุนโครงการเพียง 72 เซนต์เท่านั้น แบบนั้นโอเคไหม คุณไม่แน่ใจ

คุณลองใช้องค์กรอื่น คุณไม่เคยได้ยินชื่อบริษัทนี้มาก่อน Are they legitimate? การค้นหาอย่างรวดเร็วจะนำคุณไปสู่ข้อมูลมากมาย คุณพบชุดข้อความใน Reddit จากเมื่อ 2 ปีก่อนซึ่งผู้ใช้รายหนึ่งอ้างว่า "นี่เป็นการหลอกลวง เงินบริจาคของฉันไม่เคยไปถึงไหนเลย" อีกคนหนึ่งปกป้องอย่างกระตือรือร้นว่า "พวกเขาลงพื้นที่ทำงานจริง" ความคลุมเครือนี้ทำให้เราทำอะไรไม่ได้เลย

30 นาทีต่อมา คุณก็ยังคงจมอยู่กับรีวิวที่ขัดแย้งกัน คะแนนประสิทธิภาพ และบันทึกของ IRS และยังไม่ได้บริจาคเงินเลย ความตั้งใจที่จะบริจาคในตอนแรกถูกแทนที่ด้วยความยุ่งยากในการค้นหาข้อมูล แท็บนั้นจะเปิดค้างไว้ 2-3 วันเพื่อช่วยเตือนความจำเล็กๆ น้อยๆ เกี่ยวกับความตั้งใจดี จนกว่าคุณจะปิดแท็บนั้นในที่สุด

นี่ไม่ใช่ความล้มเหลวส่วนบุคคล แต่เป็นความล้มเหลวของระบบ

ประสบการณ์นี้เป็นสากล ความต้องการที่จะบริจาคมีอยู่มากมาย แต่กระบวนการกลับเต็มไปด้วยอุปสรรคที่ทำให้เกิดความลังเลและข้อสงสัย ดังนี้

  • ❌ ความยุ่งยากในการค้นคว้า: องค์กรการกุศลแต่ละแห่งต้องมีการตรวจสอบของตนเอง
  • ❌ การยืนยันความน่าเชื่อถือ: การแยกแยะองค์กรที่มีประสิทธิภาพสูงออกจากองค์กรที่ไม่มีประสิทธิภาพหรือแม้แต่การหลอกลวงโดยตรงนั้นทำได้ยาก
  • ❌ ภาวะวิเคราะห์มากเกินไปจนตัดสินใจไม่ได้: ตัวเลือกที่มากเกินไปทำให้เกิดความเหนื่อยล้าจากการตัดสินใจ
  • ❌ สูญเสียแรงกระตุ้น: แรงกระตุ้นทางอารมณ์ที่จะให้ลดลงเมื่อภาระด้านการจัดการเพิ่มขึ้น

ความยุ่งยากนี้ทำให้เกิดต้นทุนที่สูงมากในชีวิตจริง การบริจาคจากบุคคลธรรมดาในสหรัฐอเมริกามีจำนวนมหาศาล โดยผู้บริจาคที่เป็นบุคคลธรรมดาได้บริจาคเงินประมาณ 3.74 แสนล้านดอลลาร์สหรัฐในปี 2023 เพียงปีเดียว ตามข้อมูลจาก Giving USA 2024 อย่างไรก็ตาม งานวิจัยแสดงให้เห็นว่าอุปสรรคในการบริจาค ซึ่งรวมถึงค่าใช้จ่ายในการค้นหา ความขัดแย้งทางจิตวิทยา และข้อจำกัดด้านเวลา ทำให้จำนวนเงินที่ไปถึงองค์กรการกุศลลดลงอย่างมาก การศึกษาที่เกี่ยวข้องกับผู้บริจาคหลายล้านคนพบว่าแม้แต่ความยุ่งยากเล็กน้อยในกระบวนการบริจาคออนไลน์ก็ทำให้ผู้คนไม่สามารถทำตามความตั้งใจในการกุศลได้

ซึ่งหมายความว่าเงินบริจาคหลายพันล้านดอลลาร์ที่ตั้งใจจะมอบให้ไม่เคยไปถึงโครงการที่ต้องการเงินเหล่านั้นเลย

วิสัยทัศน์

ลองนึกภาพประสบการณ์ที่แตกต่างออกไป แทนที่จะใช้เวลาค้นคว้าข้อมูล 30 นาที คุณก็แค่พูดว่า

"ฉันต้องการบริจาคเงิน 1,500 บาทให้แก่โครงการส่งเสริมการอ่านออกเขียนได้สำหรับเด็ก ช่วยหาองค์กรการกุศลที่ได้รับการยืนยัน มีประสิทธิภาพ และได้รับคะแนนสูงให้หน่อย"

และในไม่กี่วินาที คุณจะได้รับคำตอบที่ช่วยสร้างความมั่นใจ ดังนี้

การ์ดผลลัพธ์ขององค์กรการกุศล

นี่คือสิ่งที่ AI Giving Agent จะช่วยคุณได้ แต่หากต้องการทำให้วิสัยทัศน์นี้เป็นจริง เราต้องแก้ปัญหาพื้นฐานที่ว่า เมื่อ AI Agent ที่ทำงานอัตโนมัติจัดการเงิน ความไว้วางใจไม่ใช่ทางเลือก แต่เป็นรากฐานทั้งหมด

  • เราจะพิสูจน์สิ่งที่ผู้ใช้อนุญาตได้อย่างไร
  • ใครเป็นผู้รับผิดชอบหากเกิดข้อผิดพลาด
  • เราจะสร้างความมั่นใจให้ผู้บริจาค องค์กรการกุศล และเครือข่ายการชำระเงินเข้าร่วมได้อย่างไร

ภารกิจของคุณวันนี้

ในเวิร์กช็อปนี้ คุณจะสร้าง Agent ที่น่าเชื่อถือโดยการรวมเทคโนโลยีอันทรงพลัง 2 อย่างเข้าด้วยกัน ได้แก่

Google Agent Development Kit (ADK)

Agent Payments Protocol (AP2)

Role

โรงงานสำหรับสร้าง AI Agent ระดับการใช้งานจริง

พิมพ์เขียวทางสถาปัตยกรรมเพื่อความน่าเชื่อถือในธุรกรรม AI

สิ่งที่ได้รับ

• เฟรมเวิร์กสำหรับการจัดการ Multi-Agent
• ฟีเจอร์ความปลอดภัยในตัว เช่น การยืนยันเครื่องมือ
• ความสามารถในการสังเกตและการติดตามที่พร้อมใช้งานจริง
• อินเทอร์เฟซ Python ที่เรียบง่ายสำหรับพฤติกรรม Agent ที่ซับซ้อน

• ขอบเขตการรักษาความปลอดภัยตามบทบาท
• ข้อมูลเข้าสู่ระบบดิจิทัลที่ตรวจสอบได้ (ข้อบังคับ)
• หลักฐานการเข้ารหัสของความยินยอม
• บันทึกการตรวจสอบที่สมบูรณ์เพื่อความรับผิดชอบ

ดูข้อมูลเพิ่มเติม

เอกสารประกอบเกี่ยวกับ ADK

โปรโตคอล AP2

สิ่งที่คุณจะสร้าง

สถาปัตยกรรม

เมื่อสิ้นสุดเวิร์กช็อปนี้ คุณจะสร้างสิ่งต่อไปนี้ได้

✅ ระบบ Multi-Agent ที่มีบทบาทเฉพาะทาง ดังนี้

  • ตัวแทนการช็อปปิ้งที่ค้นหาองค์กรการกุศลที่ได้รับการยืนยัน
  • ตัวแทนผู้ขายที่สร้างข้อเสนอการบริจาคที่มีผลผูกพัน
  • ผู้ให้บริการข้อมูลเข้าสู่ระบบที่ประมวลผลการชำระเงินอย่างปลอดภัย
  • Orchestrator ที่ประสานงานทั้งโฟลว์

✅ ข้อมูลเข้าสู่ระบบที่ยืนยันได้ 3 ประเภท

  • IntentMandate: "หาองค์กรการกุศลด้านการศึกษาให้หน่อย"
  • CartMandate: "$50 to Room to Read, signed by merchant"
  • PaymentMandate: "ประมวลผลผ่านการชำระเงินจำลอง"

✅ ความปลอดภัยในทุกระดับชั้น:

  • ขอบเขตความน่าเชื่อถือตามบทบาท
  • ความยินยอมโดยชัดแจ้งของผู้ใช้

✅ บันทึกการตรวจสอบที่สมบูรณ์

  • ตรวจสอบย้อนกลับได้ทุกการตัดสินใจ
  • บันทึกความยินยอมทุกรายการ
  • แสดงการส่งต่อทั้งหมด

🔒 สำคัญ: นี่คือสภาพแวดล้อมการเรียนรู้ที่ปลอดภัย

พร้อมที่จะสร้างความไว้วางใจแล้วหรือยัง

ในโมดูลถัดไป เราจะตั้งค่าสภาพแวดล้อมในการพัฒนาซอฟต์แวร์และสร้าง AI Agent ตัวแรกของคุณ คุณจะค้นพบอย่างรวดเร็วว่าทำไม Agent แบบง่ายจึงไม่น่าเชื่อถือ จากนั้นใช้เวลาที่เหลือของเวิร์กช็อปเพื่อเรียนรู้วิธีแก้ไขปัญหานั้น

มาเริ่มด้วยการทำความเข้าใจปัญหาโดยตรงกัน

2. กำลังเตรียม Workspace ของคุณ

รากฐานสำหรับ Agent ที่น่าเชื่อถือ

ก่อนที่จะสร้าง AI Giving Agent ได้ เราต้องเตรียมสภาพแวดล้อมในการพัฒนาซอฟต์แวร์ที่สะอาด สอดคล้อง และกำหนดค่าอย่างถูกต้อง โมดูลนี้เป็นขั้นตอนที่มุ่งเน้นเพื่อให้แน่ใจว่ามีเครื่องมือและบริการที่จำเป็นทั้งหมดพร้อมใช้งาน

การตั้งค่านี้ให้เสร็จสมบูรณ์จะช่วยให้คุณมุ่งเน้นไปที่งานที่น่าตื่นเต้นในการสร้างตรรกะของ Agent ในโมดูลต่อๆ ไปได้อย่างเต็มที่ โดยไม่ต้องกังวลเกี่ยวกับปัญหาด้านการกำหนดค่า

เข้าถึง Cloud Shell

ก่อนอื่น เราจะเปิด Cloud Shell ซึ่งเป็นเทอร์มินัลบนเบราว์เซอร์ที่มี Google Cloud SDK และเครื่องมือสำคัญอื่นๆ ติดตั้งไว้ล่วงหน้า

คลิกเปิดใช้งาน Cloud Shell ที่ด้านบนของคอนโซล Google Cloud (ไอคอนเทอร์มินัลในแถบนำทางด้านขวาบน)

Cloud Shell

วิธีค้นหารหัสโปรเจ็กต์ Google Cloud

  • เปิดคอนโซล Google Cloud: https://console.cloud.google.com
  • เลือกโปรเจ็กต์ที่ต้องการใช้สำหรับเวิร์กช็อปนี้จากเมนูแบบเลื่อนลงของโปรเจ็กต์ที่ด้านบนของหน้า
  • รหัสโปรเจ็กต์จะแสดงในการ์ดข้อมูลโปรเจ็กต์บนแดชบอร์ด รหัสโปรเจ็กต์

เมื่อ Cloud Shell เปิดขึ้น ให้ยืนยันว่าคุณได้รับการตรวจสอบสิทธิ์แล้ว โดยทำดังนี้

# Check that you are logged in
gcloud auth list

คุณควรเห็นบัญชีของคุณแสดงเป็น (ACTIVE)

กำหนดค่าโปรเจ็กต์

ตอนนี้เรามาตั้งค่าโปรเจ็กต์ Google Cloud และเปิดใช้ API ที่จำเป็นกัน

ตั้งค่ารหัสโปรเจ็กต์

# 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 สำหรับการให้เหตุผลของ Agent
  • 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/ - ที่ที่เราจะสร้าง Agent และเครื่องมือ
  • scripts/ - สคริปต์ตัวช่วยสำหรับการทดสอบและการยืนยัน
  • deploy.sh - สคริปต์ตัวช่วยสำหรับการติดตั้งใช้งาน
  • setup.py - สคริปต์ตัวช่วยสำหรับการติดตั้งโมดูล
  • .env.template - ไฟล์ตัวแปรสภาพแวดล้อม

ตั้งค่าสภาพแวดล้อม Python

ตอนนี้เราจะสร้างสภาพแวดล้อม Python แยกต่างหากสำหรับโปรเจ็กต์ของเรา

สร้างและเปิดใช้งานสภาพแวดล้อมเสมือน

# Create the virtual environment
python3 -m venv venv

# Activate it
source venv/bin/activate

✅ การยืนยัน: ตอนนี้พรอมต์ควรแสดงคำนำหน้า (venv)

ติดตั้งทรัพยากร Dependency

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 แล้ว
  • ✅ เปิดใช้ API ที่จำเป็นแล้ว
  • ✅ ติดตั้งไลบรารี ADK และ AP2 แล้ว
  • ✅ โค้ดเทมเพลตพร้อมให้แก้ไข

ในโมดูลถัดไป คุณจะได้สร้าง AI Agent ตัวแรกด้วยโค้ดไม่กี่บรรทัด และค้นพบว่าทำไม Agent แบบง่ายๆ จึงไม่น่าเชื่อถือเมื่อต้องจัดการธุรกรรมทางการเงิน

3. Agent รายแรกของคุณและการค้นพบช่องว่างด้านความน่าเชื่อถือ

แบนเนอร์

จากไอเดียสู่การโต้ตอบ

ในโมดูลก่อนหน้า เราได้เตรียมสภาพแวดล้อมในการพัฒนาซอฟต์แวร์ไว้แล้ว ตอนนี้ก็ถึงเวลาเริ่มงานที่น่าตื่นเต้นแล้ว เราจะสร้างและเรียกใช้ Agent ตัวแรก มอบความสามารถแรกให้ และในระหว่างนั้น เราจะค้นพบความท้าทายพื้นฐานที่เราต้องแก้ไขเพื่อให้ Agent มีความน่าเชื่อถืออย่างแท้จริง

โมดูลนี้เป็นภาพ "ก่อน" ของคุณ ซึ่งเป็นช่วงเวลาที่เผยให้เห็นว่าทำไมการสร้าง Agent ที่น่าเชื่อถือจึงต้องทำมากกว่าแค่ให้ LLM เข้าถึงเครื่องมือ

ขั้นตอนที่ 1: ตรวจสอบ Starter Agent

ก่อนอื่น มาดูเทมเพลตสำหรับ Agent ตัวแรกกัน ซึ่งมีโครงสร้างพื้นฐานพร้อมตัวยึดตำแหน่งที่เราจะดำเนินการให้เสร็จสมบูรณ์ในขั้นตอนถัดไป

👉 เปิดไฟล์

charity_advisor/simple_agent/agent.py

ในเครื่องมือแก้ไข

คุณจะเห็นข้อมูลดังนี้

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

# MODULE_3_STEP_2_IMPORT_COMPONENTS


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

โปรดสังเกตว่าความคิดเห็นของตัวยึดตำแหน่งเป็นไปตามรูปแบบ MODULE_3_STEP_X_DESCRIPTION เราจะแทนที่เครื่องหมายเหล่านี้เพื่อสร้าง Agent ของเราอย่างต่อเนื่อง

ขั้นตอนที่ 2: นำเข้าคอมโพเนนต์ที่จำเป็น

ก่อนที่จะสร้างอินสแตนซ์คลาส Agent หรือใช้เครื่องมือ google_search ได้ เราต้องนำเข้าคลาสหรือเครื่องมือดังกล่าวลงในไฟล์

👉 ค้นหา

# MODULE_3_STEP_2_IMPORT_COMPONENTS

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ตอนนี้คลาส Agent และเครื่องมือ google_search พร้อมใช้งานในไฟล์ของเราแล้ว

ขั้นตอนที่ 3: เขียนคำสั่ง Agent

คำสั่งคือ "รายละเอียดงาน" ของ Agent ซึ่งจะบอก LLM ว่าควรใช้เครื่องมือเมื่อใดและอย่างไร มาเขียนคำสั่งที่แนะนำ Agent ให้ค้นหาข้อมูลการกุศลกัน

👉 ค้นหา

# 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: เพิ่มเครื่องมือค้นหา

Agent ที่ไม่มีเครื่องมือก็เป็นเพียงผู้สนทนาเท่านั้น มาเพิ่มความสามารถแรกให้ Agent กัน นั่นคือความสามารถในการค้นหาเว็บ

👉 ค้นหา

# MODULE_3_STEP_4_ADD_TOOLS
tools=[]

👉 แทนที่ 2 บรรทัดดังกล่าวด้วยโค้ดต่อไปนี้

tools=[google_search]

ขั้นตอนที่ 5: ยืนยันตัวแทนที่สมบูรณ์

มาตรวจสอบว่าอุปกรณ์ทั้งหมดอยู่ในตำแหน่งที่ถูกต้องก่อนที่จะทดสอบ

👉 Your complete

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: ทดสอบ Agent - เปิดเผยช่องว่างด้านความน่าเชื่อถือ

เมื่อกำหนดค่า Agent เสร็จสมบูรณ์แล้ว เรามาทดสอบและวิเคราะห์ลักษณะการทำงานของ Agent กัน นี่คือจุดที่เราจะค้นพบว่าทำไม Agent แบบง่ายๆ จึงไม่น่าเชื่อถือเมื่อต้องจัดการกับการตัดสินใจทางการเงิน

การทดสอบที่ 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 แล้วดูคำตอบ

หลังจากนั้นสักครู่ Agent จะสังเคราะห์ผลการค้นหาเป็นคำตอบดังนี้

จากการค้นเว็บ องค์กรการกุศลที่ได้รับการยกย่องอย่างสูงด้านการอ่านออกเขียนได้ของเด็กๆ ได้แก่ Reading Is Fundamental และ Room to Read แหล่งข้อมูลอย่าง Charity Navigator และ GuideStar มักได้รับการแนะนำให้ใช้เพื่อยืนยันสถานะและการจัดอันดับ นอกจากนี้ ฉันยังพบการสนทนาออนไลน์หลายรายการ รวมถึงในฟอรัมอย่าง Reddit ซึ่งผู้ใช้แชร์ประสบการณ์ส่วนตัวเกี่ยวกับโปรแกรมการอ่านออกเขียนได้ในท้องถิ่นขนาดเล็กต่างๆ

มาวิเคราะห์เรื่องนี้กัน ตัวแทนแก้ปัญหาให้เราได้ไหม

❌ ไม่ AI จำลองประสบการณ์ของมนุษย์ที่เราอธิบายไว้ในโมดูล 1 ได้อย่างสมบูรณ์แบบ มันทำให้กระบวนการ "ค้นหาใน Google" เป็นแบบอัตโนมัติได้สำเร็จ และส่งปัญหา "การวิเคราะห์จนเป็นอัมพาต" กลับมาให้เรา

ซึ่งเผยให้เห็นช่องว่างด้านความน่าเชื่อถือประการแรก นั่นคือการขาดข้อมูลที่เชื่อถือได้

เอเจนต์กำลังค้นหาเว็บแบบเปิด ซึ่งหมายความว่า

  • ✅ พบผลลัพธ์อย่างรวดเร็ว (ปรับปรุงประสบการณ์ของผู้ใช้)
  • ❌ มีการผสมผสานองค์กรที่ได้รับคะแนนสูงกับการสนทนาใน Reddit (แหล่งข้อมูลที่ไม่น่าเชื่อถือ)
  • ❌ ไม่สามารถแยกแยะระหว่างองค์กรการกุศลที่ผ่านการตรวจสอบกับสแกมที่อาจเกิดขึ้น (ไม่มีการยืนยัน)
  • ❌ ขอให้เรายืนยันข้อมูลที่เพิ่งให้มา (ผลักภาระกลับมา)

การทดสอบที่ 2: ปัญหาด้านการดำเนินการ

ตอนนี้มาถึงการทดสอบครั้งที่ 2 ที่สำคัญแล้ว เมื่อมีข้อความแจ้งจาก [user]: ให้ลองบริจาคให้เสร็จสมบูรณ์โดยทำดังนี้

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

Agent จะตอบกลับด้วยคำขอโทษ โดยยอมรับข้อจำกัดของตนเอง ดังนี้

เราเข้าใจว่าคุณต้องการบริจาค ซึ่งเป็นเรื่องที่ยอดเยี่ยมมาก อย่างไรก็ตาม ฉันเป็นผู้ช่วยค้นคว้าวิจัยและไม่มีความสามารถในการจัดการธุรกรรมทางการเงินหรือประมวลผลการชำระเงิน หากต้องการบริจาค คุณจะต้องไปที่เว็บไซต์อย่างเป็นทางการของ Room to Read โดยตรง

นี่คือช่วงเวลา "อ๋อ" ที่สำคัญไม่แพ้กัน

ไม่เพียงแต่ไม่สามารถเชื่อถือตัวแทนในการค้นหาองค์กรการกุศลที่เหมาะสมได้เท่านั้น แต่ยังไม่สามารถเชื่อถือตัวแทนในการดำเนินการบริจาคได้ด้วย

👉 กด

Ctrl+C

เพื่อออกเมื่อทดสอบเสร็จแล้ว

ภาพแสดงช่องว่าง 2 ช่อง

ปัญหาด้านความน่าเชื่อถือ

สิ่งที่คุณเพิ่งได้เรียนรู้

ในโมดูลนี้ คุณได้สร้างและติดตั้ง AI Agent ตัวแรกเรียบร้อยแล้ว ในการทำเช่นนี้ คุณได้ค้นพบความท้าทายพื้นฐาน 2 ประการในการสร้างระบบที่น่าเชื่อถือ

แนวคิดหลักที่เข้าใจอย่างถ่องแท้

✅ คลาส Agent:

  • องค์ประกอบหลักของ ADK
  • รวมการให้เหตุผลของ LLM (สมอง) เข้ากับเครื่องมือ (มือ)
  • กำหนดค่าด้วยโมเดล คำสั่ง และเครื่องมือ

✅ โครงสร้างตามโฟลเดอร์:

  • Agent แต่ละรายการจะอยู่ในโฟลเดอร์ของตัวเอง
  • ADK ค้นหา agent_folder/agent.py
  • วิ่งด้วย adk run agent_folder

✅ รายการเครื่องมือ

  • กำหนดความสามารถด้าน Agentic AI
  • LLM จะตัดสินใจว่าจะใช้เครื่องมือเมื่อใดและอย่างไร
  • มีเครื่องมือหลายอย่างสำหรับการดำเนินการที่แตกต่างกันได้

✅ พรอมต์คำสั่ง:

  • แนะนำลักษณะการทำงานของ Agent เช่น คำอธิบายลักษณะงาน
  • ระบุบทบาท ทริกเกอร์ การดำเนินการ และรูปแบบเอาต์พุต
  • สำคัญต่อการใช้เครื่องมือที่เชื่อถือได้

✅ ปัญหาด้านความน่าเชื่อถือ

  • ช่องว่างในการค้นพบ: แหล่งข้อมูลที่ไม่ได้รับการตรวจสอบ คุณภาพไม่สม่ำเสมอ
  • ช่องว่างในการดำเนินการ: ไม่มีฟีเจอร์ที่ปลอดภัย ไม่มีความยินยอม ไม่มีบันทึกการตรวจสอบ

ต้องทำอะไรต่อไป

ในโมดูลถัดไป เราจะเริ่มสร้างโซลูชันโดยใช้สถาปัตยกรรมตามบทบาทของ AP2

มาสร้าง Agent แรกและดูการแยกบทบาทกัน

4. การสร้าง Shopping Agent - การค้นพบตามบทบาท

แบนเนอร์

รากฐานของความน่าเชื่อถือ: การแยกบทบาท

ในโมดูลที่แล้ว คุณได้ทราบว่า Agent อเนกประสงค์แบบง่ายๆ ไม่สามารถทำงานได้ใน 2 ด้าน ได้แก่ ไม่สามารถให้การค้นพบที่น่าเชื่อถือ และไม่สามารถทำธุรกรรมที่ปลอดภัยได้ ตอนนี้เราจะเริ่มแก้ปัญหาเหล่านี้โดยใช้หลักการแรกจากโปรโตคอลการชำระเงินของ Agent ซึ่งก็คือสถาปัตยกรรมตามบทบาท

ก่อนที่จะเขียนโค้ด เรามาทำความเข้าใจกันก่อนว่าทำไมหลักการนี้จึงสำคัญ

หลักการ AP2: การแยกบทบาท

ปัญหาเกี่ยวกับ Agent ที่ "ทำทุกอย่าง"

ลองนึกภาพว่าคุณจ้างคนๆ หนึ่งให้เป็นที่ปรึกษาทางการเงิน นักบัญชี และโบรกเกอร์การลงทุน สะดวกไหม ได้ ปลอดภัยไหม ไม่ใช่เลยแม้แต่น้อย โดยผู้ใช้จะมีสิทธิ์ต่อไปนี้

  • เป้าหมายการลงทุนของคุณ (บทบาทที่ปรึกษา)
  • สิทธิ์เข้าถึงบัญชีของคุณ (บทบาทนักบัญชี)
  • สิทธิ์ในการย้ายเงิน (บทบาทโบรกเกอร์)

หากบุคคลนี้ถูกบุกรุกหรือทำผิดพลาด ทุกอย่างก็จะตกอยู่ในความเสี่ยง

โซลูชันของ AP2: 1 Agent 1 งาน

AP2 ใช้หลักการแยกความกังวลเพื่อสร้างขอบเขตความน่าเชื่อถือ ดังนี้

สถาปัตยกรรม

ความสำคัญ

  • ✅ ขอบเขตความเสียหายที่จำกัด: หาก Shopping Agent ถูกบุกรุก ผู้โจมตีจะไม่สามารถเข้าถึงข้อมูลเข้าสู่ระบบการชำระเงินได้
  • ✅ ความเป็นส่วนตัว: ผู้ให้บริการข้อมูลเข้าสู่ระบบจะไม่เห็นการสนทนาเกี่ยวกับการช็อปปิ้งของคุณ
  • ✅ การปฏิบัติตามข้อกำหนด: ปฏิบัติตามข้อกำหนด PCI-DSS ได้ง่ายขึ้นเมื่อแยกข้อมูลการชำระเงิน
  • ✅ ความรับผิดชอบ: ความรับผิดชอบที่ชัดเจนสำหรับแต่ละขั้นตอน

วิธีที่ Agent สื่อสาร: สถานะเป็นแผ่นจดบันทึกที่ใช้ร่วมกัน

เนื่องจาก Agent ไม่สามารถเข้าถึงข้อมูลของกันและกันได้โดยตรง จึงต้องสื่อสารผ่านสถานะที่แชร์ ให้คิดว่ากระดานนี้เป็นไวท์บอร์ดที่ Agent ทั้งหมดสามารถเขียนและอ่านได้ ดังนี้

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

วิธีนี้ช่วยให้เรารักษาขอบเขตความน่าเชื่อถือได้ในขณะที่เปิดใช้การทำงานร่วมกัน

Agent แรกของเรา: Shopping Agent

ความรับผิดชอบของ Shopping Agent นั้นเรียบง่ายและมุ่งเน้นไปที่สิ่งต่อไปนี้

  1. ใช้เครื่องมือ find_charities เพื่อค้นหาฐานข้อมูลที่เชื่อถือได้ของเรา
  2. แสดงตัวเลือกให้ผู้ใช้
  3. ใช้เครื่องมือ save_user_choice เพื่อสร้าง IntentMandate และบันทึกลงในสถานะ
  4. ส่งต่อให้ตัวแทนคนถัดไป (ผู้ขาย)

เท่านี้เอง ไม่มีการจัดการการชำระเงิน ไม่มีการสร้างรถเข็น มีเพียงการค้นพบและการส่งต่อ

มาสร้างกันทีละขั้นตอน

ขั้นตอนที่ 1: เพิ่มตัวช่วยตรวจสอบอินพุต

เมื่อสร้างเครื่องมือเวอร์ชันที่ใช้งานจริง การตรวจสอบอินพุตเป็นสิ่งสำคัญอย่างยิ่ง มาสร้างฟังก์ชันตัวช่วยที่ตรวจสอบข้อมูลองค์กรการกุศลก่อนบันทึกลงในสถานะกัน

👉 เปิด

charity_advisor/tools/charity_tools.py

คุณจะเห็นฟังก์ชัน find_charities (เสร็จสมบูรณ์แล้ว) ที่ด้านบน เลื่อนลงเพื่อดูข้อมูลต่อไปนี้

# MODULE_4_STEP_1_ADD_VALIDATION_HELPER

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 2: เพิ่ม IntentMandate Creation Helper

ตอนนี้เรามาสร้างตัวช่วยที่สร้างโครงสร้าง IntentMandate ของ AP2 กัน ซึ่งเป็นหนึ่งในข้อมูลเข้าสู่ระบบที่ยืนยันได้ 3 รายการใน AP2

👉 ในไฟล์เดียวกัน ให้ค้นหาบรรทัดต่อไปนี้

# MODULE_4_STEP_2_ADD_INTENTMANDATE_CREATION_HELPER

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3: สร้างเครื่องมือส่งต่อสถานะด้วย IntentMandate

ตอนนี้เรามาสร้างเครื่องมือที่สร้าง IntentMandate และบันทึกไว้ในสถานะกัน

👉 ในไฟล์เดียวกัน ให้เลื่อนลงไปที่

save_user_choice

ค้นหา

# MODULE_4_STEP_3_COMPLETE_SAVE_TOOL

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 4: เพิ่ม Display Formatting Helper

ก่อนที่จะสร้าง Agent เรามาเพิ่มผู้ช่วยอีก 1 รายที่จัดรูปแบบข้อมูลการกุศลเพื่อให้แสดงผลได้อย่างเข้าใจง่าย

👉 เลื่อนเพื่อดูหัวข้อต่อไปนี้

# MODULE_4_STEP_4_ADD_FORMATTING_HELPER

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 5: สร้าง Shopping Agent - นำเข้าคอมโพเนนต์

เมื่อเครื่องมือของเราสมบูรณ์และมีประสิทธิภาพแล้ว มาสร้าง Agent ที่จะใช้เครื่องมือเหล่านั้นกัน

👉 เปิด

charity_advisor/shopping_agent/agent.py

คุณจะเห็นเทมเพลตที่มีความคิดเห็นตัวยึดตำแหน่ง มาสร้างกันทีละขั้นตอน

👉 ค้นหา

# MODULE_4_STEP_5_IMPORT_COMPONENTS

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 6: เขียนคำสั่งสำหรับ Agent

คำสั่งคือส่วนที่เรากำหนดรายละเอียดงานและเวิร์กโฟลว์ของ Agent ขั้นตอนนี้สำคัญมาก เพราะคำสั่งที่เขียนไม่ดีจะทำให้เกิดลักษณะการทำงานที่ไม่น่าเชื่อถือ

👉 ค้นหา

# 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: เพิ่มเครื่องมือลงใน Agent

ตอนนี้เรามาให้สิทธิ์ Agent เข้าถึงทั้ง 2 เครื่องมือกัน

👉 ค้นหา

# MODULE_4_STEP_7_ADD_TOOLS

👉 แทนที่ 2 บรรทัดดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 8: ยืนยัน Agent ที่สมบูรณ์

มาตรวจสอบกันว่าเดินสายไฟทุกอย่างถูกต้องแล้ว

👉 Your complete

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

✅ เยี่ยมเลย คุณได้สร้าง Agent ที่มีคุณภาพระดับเวอร์ชันที่ใช้งานจริงและเป็นไปตามข้อกำหนดของ AP2 โดยมีสิ่งต่อไปนี้

  • การตรวจสอบข้อมูลที่ป้อน
  • การสร้าง IntentMandate ที่เหมาะสมโดยใช้โมเดล AP2 Pydantic
  • เอาต์พุตที่จัดรูปแบบ
  • ขอบเขตบทบาทที่ชัดเจน
  • วิธีการโดยละเอียด
  • การจัดการข้อผิดพลาด

ขั้นตอนที่ 9: ทดสอบ Shopping Agent

มาตรวจสอบกันว่า Agent ทำงานอย่างถูกต้อง สร้าง IntentMandate ที่เหมาะสม และเคารพขอบเขตของตนเอง

👉 ในเทอร์มินัล Cloud Shell ให้เรียกใช้คำสั่งต่อไปนี้

adk run charity_advisor/shopping_agent

ข้อความแจ้ง [user]: จะปรากฏขึ้น

การทดสอบที่ 1: การค้นพบด้วยฐานข้อมูลที่เชื่อถือได้

👉 ประเภท:

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

หลังจากนั้นสักครู่ Agent จะให้คำตอบ ผลลัพธ์ที่ได้จะจัดรูปแบบอย่างสวยงามด้วยตัวช่วย _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% ของเงินทุนนำไปใช้ในโครงการ
📋 พันธกิจ: นำการศึกษาวิทยาการคอมพิวเตอร์ไปสู่โรงเรียนที่ด้อยโอกาส

คุณต้องการสนับสนุนองค์กรการกุศลใดและต้องการบริจาคเท่าใด

เปรียบเทียบกับ Agent แบบง่ายของโมดูล 3 ซึ่งให้ผลการค้นหาของ Google ที่ยังไม่ผ่านการตรวจสอบ นี่คือความแตกต่างระหว่างการค้นพบที่ไม่น่าเชื่อถือและการค้นพบที่น่าเชื่อถือ

การทดสอบที่ 2: บันทึกตัวเลือกของผู้ใช้และสร้าง IntentMandate

👉 ประเภท:

I'll donate $50 to Room to Read.

คุณควรเห็น Agent เรียกใช้เครื่องมือ save_user_choice ด้วยพารามิเตอร์ที่ถูกต้อง การสร้าง IntentMandate โดยใช้โมเดล AP2 จะช่วยให้คุณเห็นคำตอบที่มีโครงสร้างชัดเจนยิ่งขึ้น ดังนี้

เยี่ยมเลย ฉันได้สร้าง IntentMandate สำหรับการบริจาคของคุณแล้ว

รายละเอียด Intent:

  • Intent ID: intent_774795905_1730927536
  • จำนวนเงิน: $50.00 ให้กับ Room to Read (EIN: 77-0479905)
  • Expires: 2024-11-07T15:32:16Z (in 1 hour)

IntentMandate นี้จะบันทึกเจตนาในการบริจาคของคุณและรวมข้อจำกัดต่างๆ เพื่อให้มั่นใจว่าธุรกรรมจะได้รับการประมวลผลอย่างปลอดภัย ตอนนี้ฉันจะส่งต่อข้อมูลนี้ไปยังผู้ประมวลผลการชำระเงินที่ปลอดภัยของเราเพื่อสร้างข้อเสนออย่างเป็นทางการและดำเนินการบริจาคให้เสร็จสมบูรณ์

เบื้องหลังมีสิ่งต่างๆ เกิดขึ้นมากมาย ดังนี้

  1. _validate_charity_data() ยืนยันข้อมูลที่ป้อนแล้ว
  2. _create_intent_mandate() ใช้โมเดล AP2 Pydantic เพื่อสร้างโครงสร้างดังนี้
   # Created and validated via Pydantic
   intent_mandate_model = IntentMandate(
       user_cart_confirmation_required=True,
       natural_language_description="Donate $50.00 to Room to Read",
       merchants=["Room to Read"],
       skus=None,
       requires_refundability=False,
       intent_expiry="2024-11-07T15:32:16Z"
   )
   
   # Converted to dict and extended with custom fields
   intent_mandate_dict = intent_mandate_model.model_dump()
   intent_mandate_dict.update({
       "charity_ein": "77-0479905",
       "amount": 50.0,
       "currency": "USD"
   })
  1. เครื่องมือเขียนเฉพาะ IntentMandate ไปยังสถานะที่แชร์:
   state["intent_mandate"] = intent_mandate_dict
  1. ระบบส่งข้อความแสดงความสำเร็จพร้อมรายละเอียดความตั้งใจกลับไปยัง LLM แล้ว
  2. LLM เขียนข้อความสุดท้ายของผู้ใช้

ตอนนี้ IntentMandate นี้พร้อมให้ตัวแทนผู้ขาย (โมดูล 5) รับไปดำเนินการแล้ว ผู้ขายจะดึงข้อมูลชื่อองค์กรการกุศลและจำนวนเงินจาก IntentMandate และตรวจสอบว่ายังไม่หมดอายุ

การทดสอบที่ 3: การตรวจสอบความถูกต้องในการดำเนินการ

มาตรวจสอบว่าผู้ช่วยตรวจสอบความถูกต้องตรวจจับอินพุตที่ไม่ถูกต้องได้หรือไม่

👉 ประเภท:

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

ตัวแทนควรตรวจจับจำนวนเงินที่ไม่ถูกต้อง:

ฉันพบปัญหา: จำนวนเงินบริจาคต้องเป็นจำนวนบวก แต่ได้รับ: $-25.0

โปรดระบุจำนวนเงินบริจาคที่มากกว่า 0 แล้วเราจะสร้าง IntentMandate ให้คุณ

นี่คือการเขียนโปรแกรมเชิงป้องกันที่ใช้งานจริง ผู้ช่วย _validate_charity_data ของเราป้องกันไม่ให้ข้อมูลที่ไม่ถูกต้องเข้าสู่ระบบและสร้าง IntentMandate ที่มีรูปแบบไม่ถูกต้อง

การทดสอบที่ 4: ยืนยันขอบเขตความน่าเชื่อถือ

👉 ลองขอให้ Agent ประมวลผลการชำระเงิน:

Now process my credit card payment.

Agent ควรปฏิเสธโดยเคารพขอบเขตบทบาทของตนเอง ดังนี้

เราไม่มีความสามารถในการประมวลผลการชำระเงิน เนื่องจากไม่ใช่ส่วนหนึ่งของบทบาทของเรา งานของฉันคือการช่วยคุณค้นหาองค์กรการกุศลที่ได้รับการยืนยันและสร้าง IntentMandate ที่บันทึกเจตนาในการบริจาคของคุณ

ระบบได้สร้าง IntentMandate ของคุณและส่งไปยังผู้ประมวลผลการชำระเงินที่ปลอดภัยของเราแล้ว ตัวแทนผู้ขายจะสร้างข้อเสนออย่างเป็นทางการ (CartMandate) จากนั้นผู้ให้บริการข้อมูลเข้าสู่ระบบจะจัดการการชำระเงินจริงโดยได้รับความยินยอมอย่างชัดแจ้งจากคุณ

นี่คือการทำงานของขอบเขตความน่าเชื่อถือ Agent ทราบว่าตนไม่ได้รับอนุญาตให้จัดการข้อมูลการชำระเงิน และคำสั่งจะแนะนำอย่างชัดเจนให้อธิบายเรื่องนี้แก่ผู้ใช้ พร้อมทั้งสอนผู้ใช้เกี่ยวกับแนวคิด IntentMandate ด้วย

👉 กด

Ctrl+C

เพื่อออกเมื่อทดสอบเสร็จแล้ว

สิ่งที่คุณเพิ่งสร้าง

คุณได้ติดตั้งใช้งานส่วนแรกของสถาปัตยกรรม AP2 เรียบร้อยแล้วด้วยการสร้าง IntentMandate ที่เหมาะสมโดยใช้โมเดล Pydantic ของ AP2

แนวคิดหลักที่เข้าใจอย่างถ่องแท้

✅ สถาปัตยกรรมตามบทบาท:

  • Agent แต่ละรายการมีงานที่กำหนดไว้อย่างชัดเจน 1 งาน
  • Agent จะสื่อสารผ่านสถานะที่แชร์ ไม่ใช่การเข้าถึงโดยตรง
  • ขอบเขตความน่าเชื่อถือจะจำกัดผลกระทบของการละเมิด

✅ IntentMandate (AP2 Credential #1):

  • สร้างขึ้นโดยใช้โมเดล AP2 Pydantic อย่างเป็นทางการสำหรับการตรวจสอบความถูกต้อง
  • การบันทึกความตั้งใจของผู้ใช้อย่างเป็นระบบ
  • รวมถึงการหมดอายุเพื่อความปลอดภัย (ป้องกันการโจมตีแบบ Replay Attack)
  • ระบุข้อจำกัด (ผู้ขาย การคืนเงิน การยืนยัน)
  • คำอธิบายภาษาธรรมชาติสำหรับมนุษย์
  • ที่เครื่องอ่านได้สำหรับ Agent
  • โมเดลได้รับการตรวจสอบก่อนแปลงเป็นพจนานุกรม

ระบุว่าเป็นความทรงจำที่แชร์ร่วมกัน:

  • tool_context.state คือ "แผ่นจดบันทึก" ที่ตัวแทนทั้งหมดเข้าถึงได้
  • Writing to state = การทำให้ข้อมูลเข้าสู่ระบบที่ยืนยันได้พร้อมใช้งาน
  • การอ่านจากสถานะ = การใช้และการตรวจสอบข้อมูลเข้าสู่ระบบ
  • ตัวแทนปลายทางจะดึงข้อมูลที่ต้องการจากข้อมูลเข้าสู่ระบบ

✅ FunctionTool:

  • แปลงฟังก์ชัน Python เป็นเครื่องมือที่ LLM เรียกใช้ได้
  • ใช้ Docstring และคำแนะนำประเภทเพื่อให้ LLM เข้าใจ
  • จัดการการเรียกใช้โดยอัตโนมัติ
  • ความสามารถในการประกอบเครื่องมือ: เครื่องมือขนาดเล็กที่มุ่งเน้นเฉพาะด้าน > เครื่องมือขนาดใหญ่แบบรวมศูนย์

✅ คำสั่งสำหรับ Agent

  • คำแนะนำด้านเวิร์กโฟลว์แบบทีละขั้นตอน
  • ขอบเขตที่ชัดเจน ("อย่า...")
  • ข้อกำหนดเฉพาะของพารามิเตอร์เพื่อป้องกันข้อผิดพลาด
  • คำจำกัดความทางเทคนิค (IntentMandate คืออะไร)
  • การจัดการกรณีที่เป็นปัญหาที่สุด (สิ่งที่ควรพูดเมื่อ...)

ต้องทำอะไรต่อไป

ในโมดูลถัดไป เราจะสร้าง Merchant Agent เพื่อรับ IntentMandate และสร้างเอกสารรับรองที่ยืนยันได้รายการที่ 2 ซึ่งก็คือ CartMandate

ตัวแทน Shopping ได้สร้าง IntentMandate ที่บันทึกความตั้งใจของผู้ใช้พร้อมวันหมดอายุ ตอนนี้เราต้องการตัวแทนเพื่ออ่านข้อมูลเข้าสู่ระบบดังกล่าว ตรวจสอบว่ายังไม่หมดอายุ และสร้างข้อเสนอที่ลงนามอย่างเป็นทางการซึ่งระบุว่า "ฉันซึ่งเป็นผู้ขายจะยอมรับราคานี้และส่งมอบสินค้าเหล่านี้"

มาสร้าง Merchant Agent และดูการทำงานของข้อมูลเข้าสู่ระบบ AP2 รายการที่ 2 กัน

5. การสร้าง Merchant Agent - ข้อเสนอที่มีผลผูกพันและ CartMandate

แบนเนอร์

จากการค้นพบสู่การมีส่วนร่วม

ในโมดูลก่อนหน้า คุณได้สร้าง Shopping Agent ซึ่งเป็นผู้เชี่ยวชาญที่ค้นหาองค์กรการกุศลที่ได้รับการยืนยันและสร้าง IntentMandate ที่บันทึกเจตนาของผู้ใช้ ตอนนี้เราต้องการตัวแทนเพื่อรับ IntentMandate นั้นและสร้างข้อเสนอที่มีผลผูกพันอย่างเป็นทางการ

นี่คือจุดที่หลักการสำคัญข้อที่ 2 ของ AP2 เข้ามามีบทบาท นั่นคือข้อมูลเข้าสู่ระบบที่ยืนยันได้ผ่าน CartMandate

หลักการ AP2: CartMandate และข้อเสนอที่มีผลผูกพัน

เหตุใดเราจึงต้องมีบทบาทผู้ขาย

ในโมดูล 4 ตัวแทน Shopping ได้สร้าง IntentMandate และบันทึกไว้ในสถานะดังนี้

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

แต่นี่เป็นเพียงความตั้งใจของผู้ใช้ เราต้องได้รับข้อมูลต่อไปนี้ก่อนจึงจะประมวลผลการชำระเงินได้

  • โครงสร้างข้อเสนออย่างเป็นทางการที่ระบบการชำระเงินเข้าใจ
  • หลักฐานที่แสดงว่าผู้ขายจะยอมรับราคานี้
  • ข้อผูกมัดที่มีผลผูกพันซึ่งไม่สามารถเปลี่ยนแปลงได้ในระหว่างการทำธุรกรรม
  • การตรวจสอบว่า Intent ยังไม่หมดอายุ

นี่คือหน้าที่ของ Merchant Agent

CartMandate คืออะไร

CartMandate เป็นคำที่ AP2 ใช้เรียก "รถเข็นช็อปปิ้งดิจิทัล" ซึ่งทำหน้าที่เป็นข้อเสนอที่มีผลผูกพัน โดยมีโครงสร้างตามมาตรฐาน PaymentRequest ของ W3C ซึ่งหมายความว่า

  • ผู้ประมวลผลการชำระเงินทั่วโลกรู้จักรูปแบบนี้
  • ซึ่งมีรายละเอียดธุรกรรมทั้งหมดในรูปแบบมาตรฐาน
  • สามารถลงนามด้วยการเข้ารหัสเพื่อพิสูจน์ความถูกต้อง

ลองนึกถึงใบเสนอราคาที่เป็นลายลักษณ์อักษรจากผู้รับเหมา

  • ❌ ทางวาจา: "ได้ครับ ผมทำงานนั้นให้ได้ในราคาประมาณ 1, 500 บาท"
  • ✅ ใบเสนอราคาที่เป็นลายลักษณ์อักษร: ค่าใช้จ่ายแยกตามรายการ ยอดรวม ลายเซ็น วันที่

ใบเสนอราคาที่เป็นลายลักษณ์อักษรมีผลผูกพัน CartMandate คือเอกสารมอบอำนาจในรูปแบบดิจิทัล

ความตั้งใจที่จะเพิ่มลงในรถเข็น

โครงสร้างของ CartMandate

CartMandate ใน AP2 มีโครงสร้างที่ฝังอยู่โดยเฉพาะ ดังนี้

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 - Wrapper ของรถเข็นที่มีข้อมูลต่อไปนี้

  • รหัสรถเข็นและวันหมดอายุ
  • ชื่อผู้ขาย
  • PaymentRequest ของ W3C

2. payment_request (ภายในเนื้อหา) - สิ่งที่ซื้อ:

  • method_data: รูปแบบการชำระเงินที่ยอมรับ
  • รายละเอียด: รายการและยอดรวม
  • ตัวเลือก: การจัดส่ง ข้อกำหนดด้านข้อมูลผู้ชำระเงิน

3. merchant_authorization - ลายเซ็นที่เข้ารหัสลับ

ลายเซ็นของผู้ขาย: หลักฐานการยืนยันความมุ่งมั่น

ลายเซ็นของผู้ขายเป็นสิ่งสำคัญ ซึ่งจะพิสูจน์สิ่งต่อไปนี้

  • ข้อเสนอนี้มาจากผู้ขายที่ได้รับอนุญาต
  • ผู้ขายตกลงที่จะใช้ราคานี้
  • ข้อเสนอไม่ได้รับการแก้ไขนับตั้งแต่สร้างขึ้น

ในเวอร์ชันที่ใช้งานจริง ลายเซ็นนี้จะเป็นลายเซ็นเข้ารหัสที่ใช้ PKI (โครงสร้างพื้นฐานคีย์สาธารณะ) หรือ JWT (โทเค็นเว็บ JSON) สำหรับเวิร์กช็อปด้านการศึกษานี้ เราจะจำลองการดำเนินการนี้ด้วยแฮช SHA-256

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

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

พันธกิจของเรา: สร้าง Merchant Agent

ตัวแทนของผู้ขายจะดำเนินการดังนี้

  1. อ่าน IntentMandate จากสถานะ (สิ่งที่ Shopping Agent เขียน)
  2. ตรวจสอบว่า Intent ยังไม่หมดอายุ
  3. ดึงข้อมูลชื่อองค์กรการกุศล จำนวนเงิน และรายละเอียดอื่นๆ
  4. สร้างโครงสร้าง PaymentRequest ที่สอดคล้องกับ W3C โดยใช้โมเดล AP2 Pydantic
  5. รวมไว้ใน CartMandate ของ AP2 พร้อมวันหมดอายุ
  6. เพิ่มลายเซ็นผู้ขายจำลอง
  7. เขียน CartMandate ไปยังสถานะสำหรับผู้ให้บริการข้อมูลเข้าสู่ระบบ (โมดูลถัดไป)

มาสร้างกันทีละขั้นตอน

ขั้นตอนที่ 1: เพิ่ม Expiry Validation Helper

ก่อนอื่น เรามาตั้งค่าไฟล์เครื่องมือที่เกี่ยวข้องกับผู้ขายและเพิ่มตัวช่วยเพื่อตรวจสอบความถูกต้องของการหมดอายุของ IntentMandate กัน

👉 เปิด

charity_advisor/tools/merchant_tools.py

มาเพิ่มการตรวจสอบการหมดอายุกัน

👉 ค้นหา

# MODULE_5_STEP_1_ADD_EXPIRY_VALIDATION_HELPER

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 2: เพิ่ม Signature Generation Helper

ตอนนี้เรามาสร้างตัวช่วยที่สร้างลายเซ็นผู้ขายจำลองกัน

👉 ค้นหา

# MODULE_5_STEP_2_ADD_SIGNATURE_HELPER

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ก: สร้างลายเซ็นและการตั้งค่าเครื่องมือ

คราวนี้เรามาเริ่มสร้างเครื่องมือหลักกัน เราจะสร้างสคริปต์นี้ทีละส่วนใน 4 ขั้นตอนย่อย อันดับแรกคือลายเซ็นของฟังก์ชันและการตั้งค่าเริ่มต้น

👉 ค้นหา

# MODULE_5_STEP_3A_CREATE_TOOL_SIGNATURE

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ข: เพิ่มตรรกะการตรวจสอบความถูกต้อง

ตอนนี้เรามาเพิ่มตรรกะเพื่ออ่านและตรวจสอบ IntentMandate โดยใช้โมเดล AP2 Pydantic และดึงข้อมูลที่เราต้องการกัน

👉 ค้นหา

# MODULE_5_STEP_3B_ADD_VALIDATION_LOGIC

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ค: สร้างโครงสร้าง CartMandate

ตอนนี้เรามาสร้างโครงสร้าง PaymentRequest ที่เป็นไปตามข้อกำหนดของ W3C และรวมไว้ใน AP2 CartMandate โดยใช้โมเดล Pydantic กัน

👉 ค้นหา

# MODULE_5_STEP_3C_CREATE_CARTMANDATE_STRUCTURE

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ง: เพิ่มลายเซ็นและบันทึกไปยังสถานะ

สุดท้าย ให้ลงนาม CartMandate โดยใช้โมเดล Pydantic และบันทึกไว้ในสถานะสำหรับ Agent ถัดไป

👉 ค้นหา

# MODULE_5_STEP_3D_ADD_SIGNATURE_AND_SAVE

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 4: สร้างตัวแทน Merchant - นำเข้าคอมโพเนนต์

ตอนนี้เรามาสร้าง Agent ที่จะใช้เครื่องมือนี้กัน

👉 เปิด

charity_advisor/merchant_agent/agent.py

คุณจะเห็นเทมเพลตที่มีเครื่องหมายตัวยึดตำแหน่ง มาเริ่มด้วยการนำเข้าสิ่งที่เราต้องการกัน

👉 ค้นหา

# MODULE_5_STEP_4_IMPORT_COMPONENTS

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 5: เขียนคำสั่งสำหรับ Merchant Agent

ตอนนี้เรามาเขียนคำสั่งที่บอก 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

👉 ค้นหา

# MODULE_5_STEP_6_ADD_TOOLS
tools=[],

👉 แทนที่ 2 บรรทัดดังกล่าวด้วยโค้ดต่อไปนี้

    tools=[
        FunctionTool(func=create_cart_mandate)
    ],

ขั้นตอนที่ 7: ยืนยันตัวแทนผู้ขายที่สมบูรณ์

มาตรวจสอบว่าเดินสายไฟทุกอย่างถูกต้องแล้ว

👉 Your complete

charity_advisor/merchant_agent/agent.py

ควรมีลักษณะดังนี้

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

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


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

Your workflow:

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

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

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

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

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

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

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

✅ จุดตรวจสอบ: ตอนนี้คุณมี Merchant Agent ที่สมบูรณ์พร้อมการสร้าง AP2 CartMandate ที่เหมาะสมโดยใช้โมเดล Pydantic แล้ว

ขั้นตอนที่ 8: ทดสอบ Merchant Agent

ตอนนี้เรามาตรวจสอบกันว่า 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
======================================================================

สิ่งที่คุณเพิ่งสร้าง

คุณได้ติดตั้งใช้งาน CartMandate ของ AP2 โดยใช้โมเดล Pydantic เพื่อให้มีโครงสร้าง การตรวจสอบการหมดอายุ และลายเซ็นของผู้ขายที่เหมาะสมเรียบร้อยแล้ว

แนวคิดหลักที่เข้าใจอย่างถ่องแท้

✅ CartMandate (AP2 Credential #2):

  • สร้างโดยใช้โมเดล Pydantic ของ AP2 อย่างเป็นทางการ
  • โครงสร้าง AP2 พร้อม Wrapper เนื้อหา
  • W3C PaymentRequest ซ้อนอยู่ภายใน
  • การหมดอายุของรถเข็น (สั้นกว่าความตั้งใจ)
  • ลายเซ็นของผู้ขายสำหรับข้อผูกพันที่มีผลผูกพัน
  • การตรวจสอบโมเดลช่วยให้มั่นใจได้ว่าสอดคล้องกับข้อกำหนดเฉพาะ

✅ การตรวจสอบวันหมดอายุ

  • กำลังอ่าน IntentMandate จากสถานะ
  • กำลังตรวจสอบโครงสร้างด้วย IntentMandate.model_validate()
  • การแยกวิเคราะห์การประทับเวลา ISO 8601
  • กำลังเปรียบเทียบกับเวลาปัจจุบัน
  • ฟีเจอร์ความปลอดภัยที่ป้องกันการประมวลผลที่ล้าสมัย

ลายเซ็นของผู้ขาย:

  • พิสูจน์ความถูกต้องและความมุ่งมั่น
  • สร้างจากโมเดล Pydantic ที่ตรวจสอบแล้ว
  • ใช้ model_dump(mode='json') สำหรับการแสดง Canonical
  • จำลองด้วย SHA-256 เพื่อการศึกษา
  • เวอร์ชันที่ใช้งานจริงใช้ PKI/JWT
  • ลงนามโมเดลเนื้อหา ไม่ใช่พจนานุกรม

✅ W3C PaymentRequest:

  • สร้างขึ้นโดยใช้โมเดล PaymentRequest Pydantic ของ AP2
  • มาตรฐานอุตสาหกรรมสำหรับข้อมูลการชำระเงิน
  • ฝังอยู่ภายในโครงสร้าง AP2
  • มี method_data, details, options
  • เปิดใช้ความสามารถในการทำงานร่วมกัน

✅ เชนข้อมูลเข้าสู่ระบบที่มีโมเดล:

  • Shopping → IntentMandate (ตรวจสอบแล้ว)
  • ผู้ขายอ่าน IntentMandate → CartMandate (ตรวจสอบทั้ง 2 โมเดลแล้ว)
  • ผู้ให้บริการข้อมูลเข้าสู่ระบบจะอ่าน CartMandate → PaymentMandate
  • แต่ละขั้นตอนจะตรวจสอบข้อมูลเข้าสู่ระบบก่อนหน้าโดยใช้ Pydantic

✅ การพัฒนาที่ขับเคลื่อนด้วยโมเดล:

  • การตรวจสอบข้อมูลที่ป้อนผ่าน model_validate()
  • การสร้างที่ปลอดภัยในการกำหนดประเภท
  • การจัดทำหมายเลขซีเรียลอัตโนมัติผ่าน model_dump()
  • รูปแบบที่พร้อมใช้งานจริง

ต้องทำอะไรต่อไป

ในโมดูลถัดไป เราจะสร้างผู้ให้บริการข้อมูลเข้าสู่ระบบเพื่อประมวลผลการชำระเงินอย่างปลอดภัย

ตัวแทนผู้ขายได้สร้างข้อเสนอที่มีผลผูกพันซึ่งมีวันหมดอายุโดยใช้โมเดล AP2 ตอนนี้เราต้องการ Agent เพื่ออ่าน CartMandate นั้น ขอความยินยอมของผู้ใช้ และดำเนินการชำระเงิน

มาสร้างผู้ให้บริการเอกสารสิทธิ์และสร้างเชนเอกสารสิทธิ์ AP2 ให้เสร็จสมบูรณ์กัน

6. การสร้างผู้ให้บริการข้อมูลเข้าสู่ระบบ - การดำเนินการชำระเงินที่ปลอดภัย

แบนเนอร์

ตั้งแต่ข้อเสนอที่มีผลผูกพันไปจนถึงการดำเนินการชำระเงิน

ในโมดูลที่ 5 คุณได้สร้าง Merchant Agent ซึ่งเป็นผู้เชี่ยวชาญที่อ่าน IntentMandate, ตรวจสอบว่ายังไม่หมดอายุ และสร้าง CartMandate ที่มีผลผูกพันพร้อมลายเซ็นของผู้ขาย ตอนนี้เราต้องการตัวแทนเพื่อรับ CartMandate นั้นและดำเนินการชำระเงินจริง

นี่คือจุดที่หลักการที่ 3 และหลักการสุดท้ายของ AP2 เข้ามามีบทบาท ซึ่งก็คือการดำเนินการชำระเงินที่ปลอดภัยผ่าน PaymentMandate

หลักการ AP2: คำสั่งการชำระเงินและการดำเนินการชำระเงิน

เหตุใดเราจึงต้องมีบทบาทผู้ให้บริการข้อมูลเข้าสู่ระบบ

ในโมดูลที่ 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 สำหรับการให้สิทธิ์ขั้นสุดท้ายที่อนุญาตให้ดำเนินการชำระเงินได้ ซึ่งเป็นเอกสารรับรองที่ยืนยันได้รายการที่ 3 และรายการสุดท้ายในเชน AP2

ให้คิดว่าข้อมูลเข้าสู่ระบบทั้ง 3 รายการเป็นเหมือนกระบวนการลงนามในสัญญา ดังนี้

  • IntentMandate: "ฉันสนใจซื้อสิ่งนี้" (หนังสือแสดงเจตจำนง)
  • CartMandate: "ฉันซึ่งเป็นผู้ขายเสนอขายในราคานี้" (ใบเสนอราคาที่เป็นลายลักษณ์อักษร)
  • PaymentMandate: "ฉันอนุญาตให้คุณเรียกเก็บเงินจากวิธีการชำระเงินของฉัน" (สัญญาที่ลงนามแล้ว)

การชำระเงินจะดำเนินการได้ก็ต่อเมื่อมีข้อมูลเข้าสู่ระบบทั้ง 3 รายการเท่านั้น

เชนข้อมูลเข้าสู่ระบบที่สมบูรณ์

โครงสร้างของ PaymentMandate

PaymentMandate ใน AP2 มีโครงสร้างที่เฉพาะเจาะจงดังนี้

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 - Wrapper การให้สิทธิ์ที่มีข้อมูลต่อไปนี้

  • payment_mandate_id: ตัวระบุที่ไม่ซ้ำกัน
  • payment_details_id: ลิงก์กลับไปยัง CartMandate
  • user_consent: ผู้ใช้ให้การอนุมัติหรือไม่
  • amount: จำนวนเงินที่ชำระ (ดึงมาจาก CartMandate)

2. agent_present - ระบุว่านี่เป็นขั้นตอนแบบมีมนุษย์ร่วมหรือไม่

3. timestamp - เวลาที่สร้างการให้สิทธิ์

ภารกิจของเรา: สร้างผู้ให้บริการข้อมูลเข้าสู่ระบบ

โปรแกรมการเข้าสู่ระบบจะดำเนินการดังนี้

  1. อ่าน CartMandate จากสถานะ (สิ่งที่ตัวแทนผู้ขายเขียน)
  2. ตรวจสอบว่ารถเข็นยังไม่หมดอายุโดยใช้โมเดล AP2 Pydantic
  3. ดึงข้อมูลรายละเอียดการชำระเงินจากโครงสร้างที่ฝังอยู่
  4. สร้าง PaymentMandate โดยได้รับความยินยอมจากผู้ใช้โดยใช้โมเดล AP2
  5. จำลองการประมวลผลการชำระเงิน (ในเวอร์ชันที่ใช้งานจริง จะเรียกใช้ API การชำระเงินจริง)
  6. เขียน PaymentMandate และผลการชำระเงินลงในสถานะ

มาสร้างกันทีละขั้นตอน

ขั้นตอนที่ 1: เพิ่มตัวช่วยตรวจสอบการหมดอายุของรถเข็นช็อปปิ้ง

ก่อนอื่น มาสร้างตัวช่วยที่ตรวจสอบว่า CartMandate ยังไม่หมดอายุ เช่นเดียวกับที่เราตรวจสอบการหมดอายุของ IntentMandate ในโมดูล 5

👉 เปิด

charity_advisor/tools/payment_tools.py

มาเพิ่มการตรวจสอบการหมดอายุกัน

👉 ค้นหา

# MODULE_6_STEP_1_ADD_CART_EXPIRY_VALIDATION_HELPER

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 2: เพิ่ม PaymentMandate Creation Helper

ตอนนี้เรามาสร้างตัวช่วยที่สร้างโครงสร้าง PaymentMandate โดยใช้โมเดล AP2 Pydantic อย่างเป็นทางการกัน

👉 ค้นหา

# MODULE_6_STEP_2_ADD_PAYMENT_MANDATE_CREATION_HELPER

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ก: สร้างลายเซ็นและการตั้งค่าเครื่องมือ

ตอนนี้เรามาเริ่มสร้างเครื่องมือหลักกันทีละส่วน อันดับแรกคือลายเซ็นของฟังก์ชันและการตั้งค่าเริ่มต้น

👉 ค้นหา

# MODULE_6_STEP_3A_CREATE_TOOL_SIGNATURE

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ข: ตรวจสอบ CartMandate

ตอนนี้เรามาเพิ่มตรรกะเพื่ออ่าน ตรวจสอบ CartMandate โดยใช้โมเดล AP2 Pydantic และตรวจสอบวันหมดอายุกัน

👉 ค้นหา

# MODULE_6_STEP_3B_VALIDATE_CARTMANDATE

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ค: ดึงรายละเอียดการชำระเงินจากโครงสร้างที่ซ้อนกัน

ตอนนี้เรามาดูโมเดล CartMandate ที่ตรวจสอบแล้วเพื่อดึงรายละเอียดการชำระเงินที่เราต้องการกัน

👉 ค้นหา

# MODULE_6_STEP_3C_EXTRACT_PAYMENT_DETAILS

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ง: สร้าง PaymentMandate และจำลองการชำระเงิน

สุดท้าย ให้สร้าง PaymentMandate โดยใช้ตัวช่วยที่อิงตาม Pydantic, จำลองการประมวลผลการชำระเงิน และบันทึกทุกอย่างลงในสถานะ

👉 ค้นหา

# MODULE_6_STEP_3D_CREATE_PAYMENTMANDATE_AND_SIMULATE

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 4: สร้างเอเจนต์ผู้ให้บริการข้อมูลเข้าสู่ระบบ - นำเข้าคอมโพเนนต์

ตอนนี้เรามาสร้าง Agent ที่ใช้เครื่องมือนี้กัน

👉 เปิด

charity_advisor/credentials_provider/agent.py

คุณจะเห็นเทมเพลตที่มีเครื่องหมายตัวยึดตำแหน่ง มาเริ่มด้วยการนำเข้าสิ่งที่เราต้องการกัน

👉 ค้นหา

# MODULE_6_STEP_4_IMPORT_COMPONENTS

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 5: เขียนวิธีการสำหรับผู้ให้บริการข้อมูลเข้าสู่ระบบ

ตอนนี้เรามาเขียนคำสั่งที่จะแนะนำ Agent กัน

👉 ค้นหา

# 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: ยืนยันผู้ให้บริการข้อมูลเข้าสู่ระบบที่สมบูรณ์

มาตรวจสอบว่าเดินสายไฟทุกอย่างถูกต้องแล้ว

👉 Your complete

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

✅ จุดตรวจสอบ: ตอนนี้คุณมี Credentials Provider ที่สมบูรณ์พร้อมการอ่าน CartMandate และการสร้าง PaymentMandate ที่เหมาะสมโดยใช้โมเดล AP2 Pydantic

ขั้นตอนที่ 8: ทดสอบผู้ให้บริการข้อมูลเข้าสู่ระบบ

ตอนนี้เรามาตรวจสอบกันว่า Agent ประมวลผลการชำระเงินและดำเนินการตามเชนข้อมูลเข้าสู่ระบบอย่างถูกต้องหรือไม่

👉 ในเทอร์มินัล 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 Agent ที่สมบูรณ์

ตอนนี้มาทดสอบการทำงานร่วมกันของ Agent ทั้ง 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 ที่สมบูรณ์ซึ่งกำลังทำงานอยู่

Agent แต่ละรายการมีคุณสมบัติดังนี้

  1. อ่านข้อมูลเข้าสู่ระบบจากสถานะ
  2. ตรวจสอบความถูกต้องโดยใช้โมเดล Pydantic (โครงสร้าง + การตรวจสอบการหมดอายุ)
  3. สร้างข้อมูลเข้าสู่ระบบถัดไปโดยใช้โมเดล AP2
  4. เขียนลงในสถานะสำหรับ Agent ถัดไป

สิ่งที่คุณเพิ่งสร้าง

คุณได้สร้างเชนข้อมูลเข้าสู่ระบบของ Agent 3 รายใน AP2 เสร็จสมบูรณ์แล้ว โดยมีการตรวจสอบโครงสร้างที่เหมาะสมโดยใช้โมเดล Pydantic และการจำลองการชำระเงิน

แนวคิดหลักที่เข้าใจอย่างถ่องแท้

✅ PaymentMandate (AP2 Credential #3):

  • สร้างโดยใช้โมเดล Pydantic ของ AP2 อย่างเป็นทางการ
  • ข้อมูลเข้าสู่ระบบขั้นสุดท้ายที่ให้สิทธิ์การดำเนินการชำระเงิน
  • ลิงก์ไปยัง CartMandate ผ่าน payment_details_id
  • บันทึกความยินยอมของผู้ใช้และการประทับเวลา
  • มีจำนวนเงินที่ชำระซึ่งดึงมาจาก CartMandate
  • รวมแฟล็ก agent_present สำหรับโมเดลแบบมีมนุษย์ร่วม
  • การตรวจสอบโมเดลช่วยให้มั่นใจได้ว่าสเปกเป็นไปตามข้อกำหนด

✅ การอ่านจาก CartMandate:

  • ตรวจสอบโครงสร้างด้วย CartMandate.model_validate()
  • การเข้าถึงแอตทริบิวต์ที่ปลอดภัยในการกำหนดประเภท: cart_model.contents.payment_request.details.total.amount
  • ทำความเข้าใจ Wrapper ของ AP2 กับการแยกมาตรฐาน W3C
  • ดึงข้อมูล merchant_name, amount, currency จากโมเดลอย่างปลอดภัย
  • Pydantic จะตรวจจับข้อผิดพลาดของโครงสร้างโดยอัตโนมัติ

✅ การตรวจสอบการหมดอายุของรถเข็น:

  • ยอมรับโมเดล Pydantic CartMandate ที่ตรวจสอบแล้ว
  • อ่านจาก cart.contents.cart_expiry (การเข้าถึงแอตทริบิวต์)
  • ฟีเจอร์ความปลอดภัยที่ป้องกันการประมวลผลรถเข็นที่ไม่มีการอัปเดต
  • ระยะเวลาสั้นกว่า (15 นาที) ความตั้งใจ (1 ชั่วโมง)

✅ การจำลองการชำระเงิน:

  • จำลองการศึกษาของผู้ประมวลผลการชำระเงินจริง
  • สร้างรหัสธุรกรรม
  • บันทึก payment_result ในสถานะ
  • ทำเครื่องหมายว่าเป็นการจำลองอย่างชัดเจน (การจำลอง: แฟล็ก True)

เชน AP2 ที่สมบูรณ์พร้อมโมเดล:

  • Agent 3 ราย, ข้อมูลเข้าสู่ระบบ 3 รายการ, การตรวจสอบความถูกต้องของ Pydantic 3 รายการ
  • ตัวแทนแต่ละรายจะตรวจสอบโครงสร้างของข้อมูลเข้าสู่ระบบก่อนหน้าโดยใช้โมเดล
  • ข้อมูลเข้าสู่ระบบแต่ละรายการจะลิงก์กับข้อมูลเข้าสู่ระบบก่อนหน้าเพื่อใช้เป็นเส้นทางการตรวจสอบ
  • การส่งต่อตามสถานะจะรักษาการแยกบทบาทไว้
  • ความปลอดภัยในการกำหนดประเภทตลอดทั้งเชน

✅ การพัฒนาที่ขับเคลื่อนด้วยโมเดล:

  • การตรวจสอบข้อมูลที่ป้อนผ่าน model_validate()
  • การสร้างที่ปลอดภัยในการกำหนดประเภทด้วยโมเดลที่ฝังอยู่
  • การจัดทำหมายเลขซีเรียลอัตโนมัติผ่าน model_dump(mode='json')
  • รูปแบบที่พร้อมใช้งานจริงตั้งแต่เริ่มต้น

ต้องทำอะไรต่อไป

ในโมดูลถัดไป เราจะสร้าง Orchestrator Agent ที่ประสานงาน Agent ผู้เชี่ยวชาญทั้ง 3 ราย

คุณได้สร้าง Agent ผู้เชี่ยวชาญที่มีประสิทธิภาพ 3 รายโดยใช้โมเดล AP2 Pydantic ตอนนี้เรามาสร้างตัวนำที่จะประสานองค์ประกอบเหล่านี้ให้เป็นประสบการณ์การบริจาคที่ราบรื่นกัน

มาสร้าง Orchestrator และดูการทำงานของระบบทั้งหมดกัน

7. การจัดการเป็นกลุ่ม - รวมทุกอย่างเข้าด้วยกัน

ไปป์ไลน์ตามลำดับ

จากผู้เชี่ยวชาญสู่ประสบการณ์ที่ราบรื่น

ในโมดูลก่อนหน้านี้ คุณได้สร้าง Agent เฉพาะทาง 3 รายการ ได้แก่

  • Shopping Agent: ค้นหาองค์กรการกุศล สร้าง IntentMandate
  • Merchant Agent: สร้าง CartMandate จาก IntentMandate
  • ผู้ให้บริการข้อมูลเข้าสู่ระบบ: สร้าง PaymentMandate และประมวลผลการชำระเงิน

โดยทั่วไปแล้ว Agent เหล่านี้จะแบ่งออกเป็น 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 ก่อนการประมวลผลการชำระเงิน
  • ✅ Agent แต่ละรายการจะทำงานในบริบทที่แยกต่างหาก
  • ✅ สถานะจะไหลไปข้างหน้าผ่านเชนข้อมูลเข้าสู่ระบบ

พันธกิจของเรา: สร้างระบบที่สมบูรณ์

เราจะสร้าง 2 เลเยอร์ ดังนี้

เลเยอร์ 1: ไปป์ไลน์การประมวลผล (SequentialAgent)

  • เชื่อมต่อ Merchant → ข้อมูลเข้าสู่ระบบ
  • ทำงานโดยอัตโนมัติตามลำดับหลังจากเลือกองค์กรการกุศลแล้ว
  • การดำเนินการข้อเสนอและการชำระเงินแบบอะตอมมิก

เลเยอร์ 2: Root Orchestrator (Agent ที่แสดงต่อผู้ใช้)

  • บุคลิกที่เป็นมิตร
  • มอบสิทธิ์ให้ shopping_agent สำหรับการเลือกองค์กรการกุศล
  • มอบสิทธิ์ให้ไปป์ไลน์การประมวลผลหลังจากสร้าง IntentMandate แล้ว
  • จัดการการสนทนาและการเปลี่ยนเฟส

แนวทาง 2 ชั้นนี้สอดคล้องกับขั้นตอนตามธรรมชาติ ดังนี้

  • ระยะการเลือกซื้อ: การสนทนาแบบหลายเทิร์น (ผู้ใช้เลือกดู ถามคำถาม ตัดสินใจ)
  • ระยะการประมวลผล: การดำเนินการแบบอะตอม (ข้อเสนอ → การชำระเงิน)

มาสร้างทั้ง 2 อย่างกันเลย

ขั้นตอนที่ 1: นำเข้าคอมโพเนนต์การจัดการเรียบเรียง

ก่อนอื่น มาตั้งค่าไฟล์การจัดเรียงด้วยการนำเข้าที่จำเป็นกัน

👉 เปิด

charity_advisor/agent.py

มาเริ่มกันที่การนำเข้า

👉 ค้นหา

# MODULE_7_STEP_1_IMPORT_COMPONENTS

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 2: สร้างไปป์ไลน์การประมวลผล

ตอนนี้เราจะสร้างไปป์ไลน์ที่เรียกใช้การสร้างข้อเสนอและการประมวลผลการชำระเงินแบบอะตอมมิก

👉 ค้นหา

# MODULE_7_STEP_2_CREATE_SEQUENTIAL_PIPELINE

👉 แทนที่ 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
    ]
)

ขั้นตอนที่ 3ก: สร้างการตั้งค่า Agent รูท

ตอนนี้เรามาสร้าง Agent ที่แสดงต่อผู้ใช้ซึ่งจะประสานงานทั้ง 2 ระยะกัน เราจะสร้างส่วนนี้เป็น 3 ส่วน ได้แก่ การตั้งค่า (3A), วิธีการ (3B) และ Agent ย่อย (3C)

👉 ค้นหา

# MODULE_7_STEP_3A_CREATE_ROOT_AGENT_SETUP

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

ขั้นตอนที่ 3ข: เขียนคำสั่งสำหรับ Agent ระดับรูท

ตอนนี้เรามาเพิ่มคำสั่งที่จะกำหนดลักษณะการทำงานของที่ปรึกษาด้านการกุศลในทั้ง 2 ระยะกัน

👉 ค้นหา

# MODULE_7_STEP_3B_WRITE_ROOT_AGENT_INSTRUCTION

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

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

Your workflow has TWO distinct phases:

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

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

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

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

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

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

ขั้นตอนที่ 3ค: เพิ่ม Agent ย่อย

สุดท้าย เราจะให้สิทธิ์ที่ปรึกษาด้านการกุศลเข้าถึงทั้งตัวแทนการช็อปปิ้งและไปป์ไลน์การประมวลผล แล้วปิดคำจำกัดความของตัวแทน

👉 ค้นหา

# MODULE_7_STEP_3C_ADD_ROOT_AGENT_SUBAGENTS

👉 แทนที่บรรทัดเดียวดังกล่าวด้วยโค้ดต่อไปนี้

    sub_agents=[
        shopping_agent,
        donation_processing_pipeline
    ]
)

ขั้นตอนที่ 4: ยืนยันทั้งระบบ

มาตรวจสอบกันว่าการจัดเรียงมีการเชื่อมต่ออย่างถูกต้อง

👉 Your complete

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: เพิ่มความปลอดภัยด้วย Callback การตรวจสอบ (ไม่บังคับ ข้ามไปยังขั้นตอนที่ 7)

callbacks

SequentialAgent รับประกันลำดับการดำเนินการ แต่จะเกิดอะไรขึ้นในกรณีต่อไปนี้

  • Shopping Agent ไม่ทำงานโดยไม่มีการแจ้งเตือน (ไม่เคยสร้าง IntentMandate)
  • เวลาผ่านไป 1 ชั่วโมงระหว่างการเลือกซื้อและการซื้อ (ความตั้งใจหมดอายุ)
  • สถานะเสียหายหรือถูกล้าง
  • มีคนพยายามโทรหาผู้ขายโดยตรงโดยไม่ผ่าน Shopping

Callback เพิ่มการบังคับใช้ทางสถาปัตยกรรม โดยจะตรวจสอบข้อกำหนดเบื้องต้นก่อนที่ Agent จะเริ่มการเรียก LLM นี่คือการป้องกันหลายชั้น โดยเครื่องมือจะตรวจสอบระหว่างการดำเนินการ ส่วน Callback จะตรวจสอบก่อนการดำเนินการ

มาเพิ่ม Callback การตรวจสอบความถูกต้องให้กับตัวแทน Merchant และผู้ให้บริการข้อมูลเข้าสู่ระบบกัน

ขั้นตอนที่ 5ก: เพิ่มการตรวจสอบผู้ขาย - นำเข้าประเภท Callback

ก่อนอื่น ให้เพิ่มการนําเข้าที่จําเป็นสําหรับ Callback

👉 เปิด

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

ขั้นตอนที่ 5ข: สร้างฟังก์ชันการตรวจสอบความตั้งใจ

ตอนนี้เรามาสร้างฟังก์ชัน Callback ที่ตรวจสอบ IntentMandate ก่อนที่ตัวแทนผู้ขายจะทำงานกัน

👉 In

charity_advisor/merchant_agent/agent.py

ให้เพิ่มฟังก์ชันนี้ก่อน

merchant_agent = Agent(...)

คำจำกัดความ:

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

ขั้นตอนที่ 5ค: แนบ Callback กับตัวแทนผู้ขาย

ตอนนี้เราจะเชื่อมต่อการติดต่อกลับกับตัวแทน

👉 In

charity_advisor/merchant_agent/agent.py

ให้แก้ไข

merchant_agent = 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,

ตอนนี้คำจำกัดความของ Agent ควรมีลักษณะดังนี้

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)

รูปแบบเดียวกัน - มาเพิ่มการตรวจสอบความถูกต้องสำหรับขั้นตอนการชำระเงินกัน

ขั้นตอนที่ 6ก: ประเภท Callback ของการนำเข้า

👉 เปิด

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

ขั้นตอนที่ 6ข: สร้างฟังก์ชันการตรวจสอบความถูกต้องของรถเข็นช็อปปิ้ง

👉 In

charity_advisor/credentials_provider/agent.py

ให้เพิ่มฟังก์ชันนี้ก่อน

credentials_provider = Agent(...)

:

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

ขั้นตอนที่ 6ค: แนบ Callback กับผู้ให้บริการข้อมูลเข้าสู่ระบบ

👉 In

charity_advisor/credentials_provider/agent.py

ให้แก้ไข

credentials_provider = Agent(...)

:

ค้นหาบรรทัดนี้ในคำจำกัดความของ 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,

ตอนนี้คำจำกัดความของ Agent ควรมีลักษณะดังนี้

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

ขั้นตอนที่ 7: ทดสอบด้วย ADK Web UI

ตอนนี้เรามาทดสอบระบบที่ผ่านการเสริมความปลอดภัยทั้งหมดโดยเปิดใช้งาน Callback การตรวจสอบความถูกต้องกัน

👉 ในเทอร์มินัล Cloud Shell ให้เรียกใช้คำสั่งต่อไปนี้

adk web

คุณควรเห็นเอาต์พุตดังนี้

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

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

👉 ถัดไป หากต้องการเข้าถึง ADK Web UI จากเบราว์เซอร์ ให้ทำดังนี้

จากไอคอนตัวอย่างเว็บ (ดูเหมือนดวงตาหรือสี่เหลี่ยมจัตุรัสที่มีลูกศร) ในแถบเครื่องมือ Cloud Shell (โดยปกติจะอยู่ด้านขวาบน) ให้เลือกเปลี่ยนพอร์ต ในหน้าต่างป๊อปอัป ให้ตั้งค่าพอร์ตเป็น 8000 แล้วคลิก "Change and Preview" จากนั้น Cloud Shell จะเปิดแท็บเบราว์เซอร์ใหม่ที่แสดง UI บนเว็บของ ADK

webpreview

👉 เลือกตัวแทนจากเมนูแบบเลื่อนลง

ใน UI บนเว็บของ ADK คุณจะเห็นเมนูแบบเลื่อนลงที่ด้านบน เลือก charity_advisor จากรายการ

agent-select

คุณจะเห็นอินเทอร์เฟซเว็บของ ADK พร้อมด้วยข้อมูลต่อไปนี้

  • แผงแชท: ด้านซ้าย สำหรับการสนทนา
  • แผงการติดตาม: ด้านขวา สำหรับความสามารถในการสังเกต (เราจะใช้แผงนี้ในโมดูลที่ 9)

การทดสอบที่ 1: ขั้นตอนการบริจาคที่สมบูรณ์ (กรณีปกติ)

👉 ในอินเทอร์เฟซแชท ให้พิมพ์ดังนี้

I want to donate to an education charity

ดูขั้นตอนทั้งหมดได้ที่นี่

adk web shopping agent

ไปป์ไลน์การประมวลผลการบริจาคบนเว็บของ ADK

สิ่งที่จะเกิดขึ้น (ดูได้ในแผงการติดตามทางด้านขวา)

1. Advisor มอบสิทธิ์ให้ ShoppingAgent:

  • ShoppingAgent ค้นหาองค์กรการกุศลด้านการศึกษา
  • แสดงตัวเลือกที่ได้รับการยืนยัน 3 รายการพร้อมรายละเอียด

2. คุณโต้ตอบกับ ShoppingAgent (อาจใช้เวลาหลายรอบ)

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

3. ShoppingAgent สร้าง IntentMandate:

  • สร้างและลงนามใน Intent
  • การยืนยันการคืนสินค้าพร้อมรหัส Intent

4. ที่ปรึกษาเปลี่ยนไปสู่ระยะการประมวลผล:

เยี่ยมเลย กำลังประมวลผลการบริจาค $50 ให้กับ Room to Read...

5. DonationProcessingPipeline จะเปิดใช้งานเมื่อ

  • Merchant callback validates IntentMandate (✓ passed) ← ใหม่
  • ตัวแทนผู้ขายสร้าง CartMandate พร้อมลายเซ็น
  • Callback ข้อมูลเข้าสู่ระบบจะตรวจสอบ CartMandate (✓ ผ่าน) ← ใหม่
  • ผู้ให้บริการข้อมูลเข้าสู่ระบบเตรียมการชำระเงิน

6. การประมวลผลการชำระเงิน

  • ผู้ให้บริการข้อมูลเข้าสู่ระบบจะสร้าง PaymentMandate
  • จำลองการประมวลผลการชำระเงิน
  • แสดงรหัสธุรกรรม

7. สรุปจาก Advisor

เยี่ยมเลย ระบบประมวลผลการบริจาคของคุณเรียบร้อยแล้ว 🎉

รายละเอียด

  • จำนวนเงิน: $50.00
  • องค์กรการกุศล: Room to Read (EIN: 77-0479905)
  • รหัสธุรกรรม: txn_a3f7b2c8d9e1f4a2

การทดสอบที่ 2: ยืนยันว่า Callback ตรวจจับความล้มเหลว (การทดสอบขั้นสูงที่ไม่บังคับ)

หากต้องการดูการทำงานของ Callback ในการตรวจจับข้อผิดพลาด คุณจะต้องทำให้สถานะเสียหายด้วยตนเอง (การแก้ไขข้อบกพร่องขั้นสูง) แต่ในเวอร์ชันที่ใช้งานจริง Callback จะตรวจจับสิ่งต่อไปนี้

  • เครื่องมือ Shopping Agent ไม่ทำงาน → การเรียกกลับของ Merchant บล็อก: "ข้อผิดพลาด: สร้างรถเข็นไม่ได้..."
  • ผ่านไป 2 ชั่วโมง → Callback ของผู้ขายบล็อก: "ข้อผิดพลาด: Intent หมดอายุ..."
  • รถเข็นหมดอายุ → บล็อก Callback ของข้อมูลเข้าสู่ระบบ: "ข้อผิดพลาด: รถเข็นหมดอายุ (จำกัด 15 นาที)..."

ตอนนี้กรณีที่เกิดขึ้นไม่บ่อยเหล่านี้จะบังคับใช้ตามสถาปัตยกรรมโดย Callback การตรวจสอบความถูกต้อง

สิ่งที่คุณเพิ่งสร้าง

คุณได้จัดระเบียบ Agent เฉพาะทาง 3 รายให้เป็นระบบที่ราบรื่นและน่าเชื่อถือพร้อมการตรวจสอบสถาปัตยกรรมเรียบร้อยแล้ว

ต้องทำอะไรต่อไป

ตอนนี้คุณได้ทำความเข้าใจแกนหลักทางเทคนิคของการสร้าง Agent ที่น่าเชื่อถือแล้ว ซึ่งได้แก่

คุณได้สร้างระบบที่เชื่อถือได้โดยสมบูรณ์ซึ่งบังคับใช้เชนข้อมูลเข้าสู่ระบบในเครื่อง ตอนนี้เรามาทำให้ผู้ใช้จริงเข้าถึงได้ผ่านการติดตั้งใช้งานเวอร์ชันที่ใช้งานจริง และเปิดใช้เส้นทางการตรวจสอบความรับผิดชอบที่ทำให้โมดูล 9 เป็นไปได้

มาทำให้ Agent ที่ผ่านการเสริมความปลอดภัยใช้งานได้ใน Google Cloud กัน

8. การทำให้ใช้งานได้

แบนเนอร์

ตอนนี้ระบบการบริจาคที่เชื่อถือได้ของคุณเสร็จสมบูรณ์แล้ว โดยมี Agent เฉพาะทาง 3 รายที่ทำงานในเครื่อง ดังนี้

แต่จะทำงานในคอมพิวเตอร์สำหรับการพัฒนาซอฟต์แวร์เท่านั้น คุณต้องทำให้ระบบนี้ใช้งานได้จริงสำหรับผู้ใช้จริง และบันทึกเส้นทางการตรวจสอบความรับผิดชอบที่พิสูจน์ความน่าเชื่อถือ โดยคุณต้องทำให้ระบบนี้ใช้งานได้จริงในเวอร์ชันที่ใช้งานจริง

โมดูลนี้จะแนะนำคุณเกี่ยวกับการติดตั้งใช้งาน Agent ใน Google Cloud โดยเปิดใช้ความสามารถในการสังเกตตั้งแต่วันแรก แฟล็ก --trace_to_cloud ที่คุณจะใช้ในระหว่างการติดตั้งใช้งานคือสิ่งที่ทำให้เกิดเส้นทางการตรวจสอบความรับผิดชอบในโมดูล 9

ทำความเข้าใจตัวเลือกการติดตั้งใช้งาน

ADK รองรับเป้าหมายการติดตั้งใช้งานหลายรายการ แต่ละวิธีมีลักษณะที่แตกต่างกันในด้านความซับซ้อน การจัดการเซสชัน การปรับขนาด และค่าใช้จ่าย ดังนี้

ปัจจัย

ในพื้นที่ (adk web)

Agent Engine

Cloud Run

ความซับซ้อน

มินิมอล

ต่ำ

ปานกลาง

ความต่อเนื่องของเซสชัน

ในหน่วยความจำเท่านั้น (หายไปเมื่อรีสตาร์ท)

จัดการโดย Vertex AI (อัตโนมัติ)

Cloud SQL (PostgreSQL) หรือในหน่วยความจำ

โครงสร้างพื้นฐาน

ไม่มี (เฉพาะเครื่องที่ใช้พัฒนา)

การจัดการครบวงจร

คอนเทนเนอร์ + ฐานข้อมูลที่ไม่บังคับ

Cold Start

ไม่มี

100-500 มิลลิวินาที

100-2000 มิลลิวินาที

การปรับขนาด

อินสแตนซ์เดียว

อัตโนมัติ

อัตโนมัติ (เป็น 0)

รูปแบบต้นทุน

ฟรี (การประมวลผลในเครื่อง)

อิงตามการประมวลผล

ตามคำขอ + รุ่นฟรี

การสนับสนุน UI

มี (ในตัว)

ไม่ (เฉพาะ API)

ใช่ (ผ่านแฟล็ก --with_ui)

การตั้งค่าความสามารถในการสังเกต

เครื่องมือดูการติดตามในเครื่อง

อัตโนมัติด้วย --trace_to_cloud

ต้องมีแฟล็ก --trace_to_cloud

เหมาะสำหรับ

การพัฒนาและการทดสอบ

Agent เวอร์ชันที่ใช้งานจริง

ตัวแทนฝ่ายผลิต

คำแนะนำ: สำหรับระบบการบริจาคที่น่าเชื่อถือนี้ เราขอแนะนำให้ใช้ Agent Engine เป็นการติดตั้งใช้งานเวอร์ชันที่ใช้งานจริงหลัก เนื่องจากมีข้อดีดังนี้

  • โครงสร้างพื้นฐานที่มีการจัดการครบวงจร (ไม่มีคอนเทนเนอร์ให้จัดการ)
  • ความต่อเนื่องของเซสชันในตัวผ่าน VertexAiSessionService
  • การปรับขนาดอัตโนมัติโดยไม่ต้องเริ่มระบบใหม่
  • การติดตั้งใช้งานที่ง่ายดาย (ไม่จำเป็นต้องมีความรู้เกี่ยวกับ Docker)
  • การผสานรวม Cloud Trace ที่พร้อมใช้งานทันที

ตัวเลือกเพิ่มเติม: Google Kubernetes Engine (GKE)

สำหรับผู้ใช้ขั้นสูงที่ต้องการการควบคุมระดับ Kubernetes, ระบบเครือข่ายที่กำหนดเอง หรือการจัดการหลายบริการเป็นกลุ่ม คุณสามารถใช้การติดตั้งใช้งาน GKE ได้ ตัวเลือกนี้ให้ความยืดหยุ่นสูงสุด แต่ต้องอาศัยความเชี่ยวชาญด้านการปฏิบัติงานมากกว่า (การจัดการคลัสเตอร์, ไฟล์ Manifest, บัญชีบริการ)

Codelab นี้ไม่ครอบคลุมการติดตั้งใช้งาน GKE แต่มีเอกสารประกอบฉบับเต็มอยู่ในคู่มือการติดตั้งใช้งาน GKE ของ ADK

ข้อกำหนดเบื้องต้น

1. การตั้งค่าโปรเจ็กต์ Google Cloud

คุณต้องมีโปรเจ็กต์ Google Cloud ที่เปิดใช้การเรียกเก็บเงิน หากไม่มี ให้ทำดังนี้

  1. สร้างโปรเจ็กต์: คอนโซล Google Cloud
  2. เปิดใช้การเรียกเก็บเงิน: เปิดใช้การเรียกเก็บเงิน
  3. จดรหัสโปรเจ็กต์ (ไม่ใช่ชื่อหรือหมายเลขโปรเจ็กต์)

2. การตรวจสอบสิทธิ์ซ้ำ (ไม่บังคับ)

ตรวจสอบสิทธิ์ด้วย Google Cloud โดยทำดังนี้

gcloud auth application-default login
gcloud config set project YOUR_PROJECT_ID

แทนที่ YOUR_PROJECT_ID ด้วยรหัสโปรเจ็กต์ Google Cloud จริง

ยืนยันการตรวจสอบสิทธิ์โดยทำดังนี้

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 ด้วยรหัสโปรเจ็กต์จริง (หรือใช้คำสั่งด้านบน)
  • หากต้องการใช้ GOOGLE_CLOUD_LOCATION ให้ใช้ภูมิภาคที่รองรับ
  • ระบบจะสร้างที่เก็บชั่วคราวโดยอัตโนมัติหากไม่มีอยู่เมื่อคุณเรียกใช้สคริปต์การติดตั้งใช้งาน

4. เปิดใช้ API ที่จำเป็น

กระบวนการติดตั้งใช้งานต้องเปิดใช้ Google Cloud API หลายรายการ เรียกใช้คำสั่งนี้เพื่อเปิดใช้

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

คำสั่งนี้จะเปิดใช้สิ่งต่อไปนี้

  • AI Platform API - สำหรับโมเดล Agent Engine และ Vertex AI
  • Cloud Storage API - สำหรับบักเก็ตพื้นที่งาน
  • 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 - ทำให้ใช้งานได้กับ Cloud Run โดยมี UI ที่ไม่บังคับ

วิธีการทำงานเบื้องหลัง

สำหรับการติดตั้งใช้งาน Agent Engine สคริปต์จะดำเนินการดังนี้

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

สำหรับการทำให้ใช้งานได้บน Cloud Run ระบบจะดำเนินการดังนี้

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

แฟล็ก --trace_to_cloud มีความสำคัญต่อการติดตั้งใช้งานทั้ง 2 ประเภท เนื่องจากจะเปิดใช้การผสานรวม Cloud Trace สำหรับเส้นทางการตรวจสอบความรับผิดชอบที่คุณจะได้สำรวจในโมดูล 9

ขั้นตอนที่ 2: เตรียม Agent Engine Wrapper

Agent Engine ต้องใช้จุดแรกเข้าที่เฉพาะเจาะจงซึ่งรวม Agent ของคุณไว้สำหรับรันไทม์ที่มีการจัดการ ระบบสร้างไฟล์นี้ให้คุณแล้ว

👉 ตรวจสอบ

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 กำหนดให้ Agent ต้องรวมอยู่ในออบเจ็กต์ AdkApp
  • พารามิเตอร์ enable_tracing=True จะเปิดใช้การผสานรวม Cloud Trace โดยอัตโนมัติ
  • Wrapper นี้จะได้รับการอ้างอิงโดย ADK CLI ในระหว่างการติดตั้งใช้งาน
  • โดยจะกำหนดค่า VertexAiSessionService สำหรับการคงเซสชันอัตโนมัติ

Agent Engine เป็นการทำให้ใช้งานได้จริงที่แนะนำสำหรับระบบการบริจาคที่เชื่อถือได้ เนื่องจากมีโครงสร้างพื้นฐานที่มีการจัดการครบวงจรพร้อมความคงอยู่ของเซสชันในตัว

เรียกใช้การติดตั้งใช้งาน

จากรูทของโปรเจ็กต์ ให้ทำดังนี้

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

ระยะการติดตั้งใช้งาน

ดูสคริปต์ดำเนินการตามขั้นตอนต่อไปนี้

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

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

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

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

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

ขั้นตอนนี้ใช้เวลา 5-10 นาที เนื่องจากระบบจะจัดแพ็กเกจ Agent และติดตั้งใช้งานในโครงสร้างพื้นฐานของ Vertex AI

บันทึกรหัส Agent Engine

เมื่อทำให้ใช้งานได้สำเร็จแล้ว

✅ 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 ของคุณประกอบด้วยสิ่งต่อไปนี้

✅ Agent ทั้ง 3 รายการ (Shopping, Merchant, Credentials) ทำงานในรันไทม์ที่มีการจัดการ
✅ ตรรกะเชนข้อมูลเข้าสู่ระบบที่สมบูรณ์ (Intent → Cart → Payment mandates)
✅ กลไกการขอความยินยอมของผู้ใช้พร้อมเวิร์กโฟลว์การยืนยัน
✅ ความต่อเนื่องของเซสชันอัตโนมัติผ่าน VertexAiSessionService
✅ โครงสร้างพื้นฐานการปรับขนาดอัตโนมัติที่จัดการโดย Google
✅ การผสานรวม Cloud Trace เพื่อความสามารถในการสังเกตที่สมบูรณ์

ขั้นตอนที่ 4: ทดสอบ Agent ที่ติดตั้งใช้งาน

อัปเดตสภาพแวดล้อม

ตรวจสอบว่า .env มีรหัสเครื่องมือ Agent ดังนี้

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

รายการตรวจสอบการยืนยัน

หลังจากทดสอบแล้ว ให้ตรวจสอบสิ่งต่อไปนี้

✅ Agent ตอบคำถาม
✅ Agent ทั้ง 3 รายทำงานตามลำดับ (Shopping → Merchant → ข้อมูลเข้าสู่ระบบ)
✅ กลไกการขอความยินยอมเปิดใช้งาน (ขอการยืนยัน)
✅ เซสชันยังคงอยู่ตลอดคำขอ
✅ ไม่มีข้อผิดพลาดในการตรวจสอบสิทธิ์
✅ ไม่มีการหมดเวลาการเชื่อมต่อ

หากพบข้อผิดพลาด ให้ทำดังนี้

  • ตรวจสอบว่าตั้งค่าตัวแปรสภาพแวดล้อมอย่างถูกต้อง
  • ยืนยันว่าเปิดใช้ API แล้ว: gcloud services list --enabled
  • ตรวจสอบบันทึก Agent Engine ในคอนโซล Vertex AI
  • ตรวจสอบว่ามีไฟล์ agent_engine_app.py อยู่ในโฟลเดอร์ charity_advisor

ขั้นตอนที่ 5: ทำให้ใช้งานได้กับ Cloud Run (ไม่บังคับ)

แม้ว่าเราจะแนะนำให้ใช้ Agent Engine เพื่อการติดตั้งใช้งานเวอร์ชันที่ใช้งานจริงที่มีประสิทธิภาพ แต่ Cloud Run ก็ช่วยให้ควบคุมได้มากขึ้นและรองรับ UI บนเว็บของ ADK ส่วนนี้จะระบุหรือไม่ก็ได้

กรณีที่ควรใช้ Cloud Run

เลือก Cloud Run หากต้องการสิ่งต่อไปนี้

  • UI บนเว็บของ ADK สำหรับการโต้ตอบของผู้ใช้
  • ควบคุมสภาพแวดล้อมของคอนเทนเนอร์ได้อย่างเต็มที่
  • การกำหนดค่าฐานข้อมูลที่กำหนดเอง
  • การผสานรวมกับบริการ Cloud Run ที่มีอยู่

เรียกใช้การติดตั้งใช้งาน

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

สิ่งที่แตกต่างออกไป

สคริปต์จะดำเนินการต่อไปนี้โดยอัตโนมัติ

  • สร้างคอนเทนเนอร์ Docker ด้วยโค้ด Agent
  • สร้างฐานข้อมูล Cloud SQL PostgreSQL (หากจำเป็น)
  • กำหนดค่าการเชื่อมต่อฐานข้อมูล
  • ติดตั้งใช้งานโดยเปิดใช้ UI บนเว็บของ ADK

การทำให้ใช้งานได้จะใช้เวลา 10-15 นาทีเนื่องจากการจัดสรร Cloud SQL

การจัดการเซสชัน:

  • ใช้ DatabaseSessionService แทน VertexAiSessionService
  • ต้องใช้ข้อมูลเข้าสู่ระบบฐานข้อมูลใน .env (หรือสร้างโดยอัตโนมัติ)
  • สถานะจะยังคงอยู่ในฐานข้อมูล PostgreSQL

การรองรับ UI:

  • UI บนเว็บพร้อมใช้งานที่ https://charity-advisor-xyz.a.run.app

การทดสอบการทำให้ใช้งานได้ของ Cloud Run

หากทำให้ใช้งานได้กับ Cloud Run ด้วย --with_ui คุณจะทดสอบในเบราว์เซอร์ได้โดยตรงโดยทำดังนี้

  1. ไปที่ URL ของบริการ (ระบุไว้ในเอาต์พุตการติดตั้งใช้งาน)
  2. คุณจะเห็นอินเทอร์เฟซเว็บของ ADK เลือก Agent จากเมนูแบบเลื่อนลง
  3. เริ่มการบริจาคทดสอบ
   I want to donate $50 to a children's education charity
  1. สังเกตขั้นตอนการดำเนินการ
    • ShoppingAgent จะค้นหาองค์กรการกุศลและบันทึกความตั้งใจของคุณ
    • MerchantAgent สร้างคำสั่งรถเข็น
    • CredentialsProvider สร้างหนังสือยินยอมหักชำระเงินและขอการยืนยัน
    • หลังจากที่คุณยืนยัน ระบบจะประมวลผลการชำระเงิน
  2. ตรวจสอบว่าการตอบกลับมีข้อมูลต่อไปนี้
    • คำแนะนำเกี่ยวกับองค์กรการกุศล
    • คำขอยืนยัน
    • ข้อความแสดงความสำเร็จหลังจากการอนุมัติ

การแก้ปัญหา

ปัญหาทั่วไป

ปัญหา: ERROR: GOOGLE_CLOUD_PROJECT is not set

วิธีแก้ไข: ตรวจสอบว่าไฟล์ .env มีรหัสโปรเจ็กต์ที่ถูกต้อง โดยทำดังนี้

GOOGLE_CLOUD_PROJECT=your-actual-project-id

ปัญหา: ระบบไม่สร้างที่เก็บข้อมูลชั่วคราวโดยอัตโนมัติ

วิธีแก้ไข: สคริปต์ควรสร้างที่เก็บข้อมูลโดยอัตโนมัติ หากไม่มี ให้สร้างด้วยตนเองโดยทำดังนี้

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

สรุป

คุณได้ดำเนินการต่อไปนี้เรียบร้อยแล้ว

✅ ทำความเข้าใจโครงสร้างพื้นฐานการติดตั้งใช้งานที่ deploy.sh มีให้
✅ ตรวจสอบการกำหนดค่า Wrapper ของ Agent Engine
✅ ติดตั้งใช้งานระบบการบริจาคที่เชื่อถือได้ใน Agent Engine (แนะนำ)
✅ เปิดใช้การผสานรวม Cloud Trace กับ --trace_to_cloud
✅ ยืนยันว่าตัวแทนเข้าถึงได้และทำงานได้
✅ สร้างรากฐานสำหรับเส้นทางการตรวจสอบความรับผิดชอบในโมดูลที่ 9

ในโมดูลถัดไป คุณจะได้เห็นว่าแฟล็กนี้จะปลดล็อกอะไรบ้าง ซึ่งก็คือการมองเห็นข้อมูลทั้งหมดเกี่ยวกับการบริจาคทุกครั้ง ช่วงเวลาที่ให้ความยินยอมทุกครั้ง และทุกขั้นตอนของเชนข้อมูลเข้าสู่ระบบ

9. ความสามารถในการสังเกต

แบนเนอร์

การติดตามกราฟ

ในโมดูลที่ 1 คุณได้เรียนรู้เกี่ยวกับปัญหาพื้นฐาน นั่นคือเมื่อ AI Agent จัดการเงิน คุณจะพิสูจน์สิ่งที่เกิดขึ้นได้อย่างไร

ผู้ใช้อาจอ้างสิทธิ์ดังนี้

  • "ฉันไม่เคยเลือกองค์กรการกุศลนั้นเลย"
  • "ฉันไม่ได้อนุมัติการชำระเงินนั้น"
  • "ระบบเรียกเก็บเงินจากฉันโดยที่ฉันไม่ยินยอม"

ในระบบ AI แบบกล่องดำแบบดั้งเดิม คุณจะไม่มีทางพิสูจน์เป็นอย่างอื่นได้ แต่ระบบการบริจาคที่น่าเชื่อถือของคุณนั้นแตกต่างออกไป ในโมดูล 8 คุณได้ติดตั้งใช้งานด้วยแฟล็ก --trace_to_cloud ซึ่งหมายความว่าตอนนี้การบริจาคทุกครั้งจะสร้างเส้นทางการตรวจสอบที่สมบูรณ์และป้องกันการปลอมแปลงใน Cloud Trace

โมดูลนี้จะสอนวิธีอ่านร่องรอยเหล่านั้นและใช้เป็นหลักฐาน คุณจะได้เรียนรู้วิธี

  • ไปยัง Cloud Trace Explorer เพื่อค้นหาการติดตามเวอร์ชันที่ใช้งานจริง
  • อ่านมุมมอง Waterfall เพื่อทำความเข้าใจขั้นตอนการดำเนินการ
  • ค้นหาเชนข้อมูลเข้าสู่ระบบ (Intent → รถเข็น → หนังสือยินยอมหักชำระเงิน)
  • ค้นหาช่วงเวลาที่ให้ความยินยอมพร้อมหลักฐานการประทับเวลา
  • ใช้การติดตามเพื่อระงับข้อพิพาท
  • ส่งออกการติดตามเพื่อการปฏิบัติตามข้อกำหนดและการตรวจสอบ

นี่คือสิ่งที่แยกระบบที่เชื่อถือได้ออกจากระบบที่มีความสามารถแต่ไม่โปร่งใส นั่นคือความสามารถในการพิสูจน์สิ่งที่เกิดขึ้นด้วยความแม่นยำทางนิติวิทยาศาสตร์

ทำความเข้าใจการติดตามและช่วงเวลา

ก่อนดูการติดตามใน Cloud Trace คุณต้องทำความเข้าใจสิ่งที่คุณกำลังดูอยู่

Trace คืออะไร

การติดตามคือไทม์ไลน์ทั้งหมดที่ Agent จัดการคำขอเดียว โดยจะบันทึกทุกอย่างตั้งแต่เมื่อผู้ใช้ส่งคำถามจนถึงการส่งคำตอบสุดท้าย

การติดตามแต่ละรายการจะแสดงข้อมูลต่อไปนี้

  • ระยะเวลาทั้งหมดของคําขอ
  • การดำเนินการทั้งหมดที่ทำไปแล้ว
  • การดำเนินการต่างๆ เกี่ยวข้องกันอย่างไร (ความสัมพันธ์แบบหลัก-ย่อย)
  • เวลาที่การดำเนินการแต่ละรายการเริ่มต้นและสิ้นสุด
  • สถานะสำเร็จหรือไม่สำเร็จ

สำหรับตัวแทนการกุศล: 1 Trace = ขั้นตอนการบริจาคที่สมบูรณ์ 1 ครั้งตั้งแต่ "ฉันต้องการบริจาค" ไปจนถึง "ชำระเงินสำเร็จ"

Span คืออะไร

Span แสดงถึงหน่วยงานเดียวภายใน Trace ให้คิดว่า Span เป็นองค์ประกอบพื้นฐานของ Trace

ประเภทช่วงที่พบบ่อยในระบบการบริจาคมีดังนี้

ประเภท Span

ความหมาย

ตัวอย่าง

agent_run

การดำเนินการของ Agent

ShoppingAgent.run, MerchantAgent.run

call_llm

คำขอไปยังโมเดลภาษา

คำขอเลือกองค์กรการกุศล gemini-2.5-flash รายการ

execute_tool

การดำเนินการฟังก์ชันเครื่องมือ

find_charities, create_payment_mandate

state_read

กำลังอ่านจากหน่วยความจำของเซสชัน

กำลังดึงข้อมูล intent_mandate จากรัฐ

state_write

กำลังเขียนลงในหน่วยความจำของเซสชัน

กำลังจัดเก็บ cart_mandate ในรัฐ

แต่ละช่วงประกอบด้วยข้อมูลต่อไปนี้

  • ชื่อ: การดำเนินการที่แสดงถึงสิ่งนี้
  • ระยะเวลาที่ใช้ (เวลาเริ่มต้น → เวลาสิ้นสุด)
  • แอตทริบิวต์: ข้อมูลเมตา เช่น อินพุตของเครื่องมือ, คำตอบของโมเดล, จำนวนโทเค็น
  • สถานะ: สำเร็จ (OK) หรือข้อผิดพลาด (ERROR)
  • ความสัมพันธ์แบบหลัก-ย่อย: การดำเนินการใดที่ทริกเกอร์การดำเนินการใด

วิธีที่ Span สร้าง Trace

Span จะซ้อนกันเพื่อแสดงความสัมพันธ์แบบเป็นเหตุเป็นผล

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

ลำดับชั้นนี้จะแสดงสิ่งที่เกิดขึ้นและลำดับที่เกิดขึ้นอย่างชัดเจน คุณจะเห็นว่าหนังสือยินยอมหักชำระเงินสร้างขึ้นหลังจากหนังสือยินยอมหักชำระเงินสำหรับรถเข็น ซึ่งสร้างขึ้นหลังจากที่ผู้ใช้เลือกองค์กรการกุศล

ขั้นตอนที่ 1: เข้าถึง Cloud Trace Explorer

คราวนี้มาดูการติดตามจริงจาก Agent ที่คุณติดตั้งใช้งานกัน

  1. เปิดคอนโซล Google Cloud: console.cloud.google.com
  2. เลือกโปรเจ็กต์จากเมนูแบบเลื่อนลงที่ด้านบน (ระบบควรเลือกไว้ล่วงหน้าหากคุณทำงานในโปรเจ็กต์นั้นอยู่)
  3. ไปที่ Cloud Trace Explorer
    • ในแถบด้านข้างทางซ้าย ให้เลื่อนไปที่ส่วนความสามารถในการสังเกต
    • คลิกติดตาม
    • หรือใช้ลิงก์โดยตรง: console.cloud.google.com/traces/list

สิ่งที่คุณกำลังดูอยู่

Trace Explorer จะแสดงรายการการติดตามทั้งหมดจากโปรเจ็กต์ของคุณ ดังนี้

คอลัมน์

สิ่งที่แสดง

คำขอ

เมธอด HTTP และปลายทาง (สำหรับคำขอ API)

เวลาเริ่มต้น

เวลาที่เริ่มส่งคำขอ

เวลาในการตอบสนอง

ระยะเวลาทั้งหมดของคําขอ

Spans

จำนวนการดำเนินการในการติดตาม

แต่ละแถวแสดงคำขอที่สมบูรณ์ 1 รายการไปยัง Agent ที่ติดตั้งใช้งาน

สร้างการติดตามทดสอบ (หากจำเป็น)

หากยังไม่เห็นการติดตามใดๆ รายการอาจว่างเปล่าเนื่องจากสาเหตุต่อไปนี้

  • ยังไม่มีคำขอที่ส่งไปยัง Agent ที่ทำให้ใช้งานได้แล้ว
  • การติดตามจะใช้เวลา 1-2 นาทีจึงจะปรากฏหลังจากส่งคำขอ

สร้างการติดตามทดสอบ

หากคุณติดตั้งใช้งานใน Cloud Run ด้วย UI ให้ไปที่ URL ของบริการและบริจาคให้เสร็จสมบูรณ์ในเบราว์เซอร์

หากคุณทำให้ใช้งานได้กับ Agent Engine ให้เรียกใช้สคริปต์ทดสอบจากโมดูล 8 ดังนี้

python scripts/test_deployed_agent.py

รอ 1-2 นาที แล้วรีเฟรชหน้า Cloud Trace Explorer ตอนนี้คุณควรเห็นการติดตามแล้ว

กรองการติดตาม

ใช้ตัวเลือกตัวกรองที่ด้านบนเพื่อค้นหาการติดตามที่เฉพาะเจาะจง ดังนี้

  • ช่วงเวลา: เปลี่ยนจาก "ชั่วโมงที่ผ่านมา" เป็น "24 ชั่วโมงที่ผ่านมา" หากจำเป็น
  • เวลาในการตอบสนองต่ำสุด/สูงสุด: กรองคำขอที่ช้า
  • ตัวกรองคำขอ: ค้นหาตามการดำเนินการที่เฉพาะเจาะจง (เช่น "DonationPipeline")

สำหรับโมดูลนี้ ให้เน้นที่การติดตามที่มีระยะเวลานานขึ้น (>5 วินาที) เนื่องจากแสดงถึงขั้นตอนการบริจาคที่สมบูรณ์ซึ่งมี Agent ทั้ง 3 ตัวทำงานอยู่

ขั้นตอนที่ 2: ตรวจสอบขั้นตอนการบริจาคที่สมบูรณ์

คลิกการติดตามใดก็ได้ในรายการเพื่อเปิดมุมมอง Waterfall คุณจะใช้เวลาส่วนใหญ่ในการวิเคราะห์พฤติกรรมของ Agent ที่นี่

ทำความเข้าใจมุมมอง Waterfall

มุมมอง Waterfall เป็นแผนภูมิแกนต์ที่แสดงไทม์ไลน์การดำเนินการทั้งหมด ดังนี้

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              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 เริ่มทำงานแล้ว
✅ ความยินยอมเป็นการดำเนินการที่ใช้เวลานานที่สุด: 3.0 วินาทีสำหรับ create_payment_mandate (เนื่องจากต้องรอการยืนยันจากผู้ใช้)
✅ การเรียก LLM ปรากฏขึ้น: Agent แต่ละรายการส่งคำขอ Gemini 1 รายการ
✅ ระบบบันทึกการเรียกใช้เครื่องมือ: เครื่องมือทั้ง 6 รายการทำงานสำเร็จ

ภาพนี้จะแสดงให้เห็นทันทีว่าใช้เวลาไปกับอะไรและการดำเนินการต่างๆ ทำงานตามลำดับใด

คลิกที่ Span เพื่อดูรายละเอียด

คลิกที่ invocation span (สแปนรูทที่ด้านบน) คุณจะเห็นแอตทริบิวต์โดยละเอียดในแผงด้านขวา ดังนี้

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

แอตทริบิวต์เหล่านี้ให้บริบทเกี่ยวกับคำขอทั้งหมด

ขั้นตอนที่ 3: ค้นหาเชนข้อมูลเข้าสู่ระบบ

ระบบที่เชื่อถือได้จะใช้เชนข้อมูลเข้าสู่ระบบเพื่อพิสูจน์การให้สิทธิ์ในแต่ละขั้นตอน ดังนี้

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

มาค้นหาคำสั่งแต่ละรายการในร่องรอยกัน

กำลังค้นหา IntentMandate

คลิก execute_tool: save_user_choice span (ใต้ ShoppingAgent)

คุณจะเห็นสิ่งต่อไปนี้ในแผงแอตทริบิวต์

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

ซึ่งพิสูจน์ได้ว่า

  • ✅ ผู้ใช้เลือก "Save the Children"
  • ✅ จำนวนเงินคือ $50
  • ✅ ระบบบันทึกตัวเลือกเมื่อเวลา 15:30:12 น. UTC
  • ✅ สร้างลายเซ็นแล้ว (ในเวอร์ชันที่ใช้งานจริง ลายเซ็นนี้จะเป็นการเข้ารหัสลับ)

ตอนนี้ IntentMandate อยู่ในสถานะเซสชันและพร้อมใช้งานสำหรับตัวแทนที่ตามมา

การค้นหา CartMandate

คลิก execute_tool: create_cart_mandate span (ใต้ MerchantAgent)

ในแผงแอตทริบิวต์ ให้ทำดังนี้

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

ซึ่งพิสูจน์ได้ว่า

  • ✅ MerchantAgent ได้รับ IntentMandate (อินพุตแสดงข้อมูลนี้)
  • ✅ สร้างรถเข็นที่มีรหัส "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 ไม่เพียงแต่พิสูจน์สิ่งที่เกิดขึ้น แต่ยังแสดงให้เห็นว่าใช้เวลาไปกับอะไร เพื่อให้คุณเพิ่มประสิทธิภาพได้

ระบุจุดวิกฤต

ในมุมมอง Waterfall ให้มองหาช่วงที่ยาวที่สุดในสแต็กแนวตั้ง ซึ่งแสดงถึงคอขวดด้านประสิทธิภาพ

จากตัวอย่างการติดตามของเรา

Total: 8.2 seconds

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

ข้อมูลเชิงลึกที่สำคัญ: CredentialsProvider ใช้เวลา 49% ของเวลาทั้งหมด ทำไมจึงเป็นเช่นนั้น

เจาะลึกช่วง CredentialsProvider:

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

ความล่าช้า 3.0 วินาทีเป็นสิ่งที่คาดไว้และเป็นเรื่องดี เนื่องจากเป็นช่วงที่ผู้ใช้กำลังพิจารณาก่อนที่จะยืนยัน ซึ่งไม่ใช่ปัญหาด้านประสิทธิภาพ แต่เป็นหลักฐานที่แสดงถึงความยินยอมที่ผ่านการพิจารณาอย่างรอบคอบ

การติดตามค่าใช้จ่าย LLM

คลิกช่วง call_llm เพื่อดูการใช้งานโทเค็น ดังนี้

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

ซึ่งนำไปใช้เพื่อจุดประสงค์เหล่านี้ได้

  • ติดตามต้นทุนต่อคำขอ (โทเค็น × ราคาโมเดล)
  • ระบุพรอมต์ที่ยาวเกินความจำเป็น
  • เปรียบเทียบประสิทธิภาพของโมเดล (Flash กับ Pro)
  • เพิ่มประสิทธิภาพสำหรับเวลาในการตอบสนองเทียบกับคุณภาพ

ตัวอย่างการคำนวณ

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

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

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

ระดับการเข้าถึงที่ละเอียดนี้ช่วยให้คุณตัดสินใจเลือกโมเดลโดยอิงตามข้อมูลได้

การเปรียบเทียบการติดตามต่างๆ

กรองการติดตามหลายรายการและเปรียบเทียบระยะเวลา

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

ข้อมูลเชิงลึก: ความแปรปรวนส่วนใหญ่มาจากเวลาที่ผู้ใช้ใช้ในการตัดสินใจ ไม่ใช่ประสิทธิภาพของระบบ การดำเนินการของ Agent หลัก (ไม่รวมความยินยอม) จะใช้เวลาประมาณ 5 วินาทีอย่างสม่ำเสมอ

ซึ่งบ่งบอกว่าระบบทำงานได้อย่างน่าเชื่อถือ

สำหรับระบบเวอร์ชันที่ใช้งานจริง ให้ตั้งค่าการแจ้งเตือนเพื่อตรวจจับปัญหาก่อนที่ผู้ใช้จะร้องเรียน

แจ้งเตือนเมื่ออัตราข้อผิดพลาดสูง

สร้างการแจ้งเตือนเมื่อการติดตามมากกว่า 5% มีข้อผิดพลาด

  1. ไปที่ Cloud Monitoring
  2. คลิก "Alerting" → "Create Policy"
  3. กำหนดค่า
    Resource: Cloud Trace Span
    Metric: Span error count
    Condition: Rate > 5% over 5 minutes
    Notification: Email your-team@example.com
    

การแจ้งเตือนเกี่ยวกับเวลาในการตอบสนองสูง

สร้างการแจ้งเตือนเมื่อเวลาในการตอบสนอง p95 เกิน 15 วินาที

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

ซึ่งจะช่วยตรวจจับประสิทธิภาพที่ลดลงก่อนที่จะส่งผลกระทบต่อประสบการณ์ของผู้ใช้

สร้างการแจ้งเตือนหากมีการประมวลผลการชำระเงินโดยไม่มีการยืนยัน โดยทำดังนี้

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

นี่คือเครื่องตรวจจับการละเมิดความปลอดภัย หากมีการเริ่มทำงาน แสดงว่ากลไกการขอความยินยอมของคุณมีปัญหาอย่างมาก

สิ่งที่คุณได้เรียนรู้

ตอนนี้คุณเข้าใจวิธีดำเนินการต่อไปนี้ผ่าน Cloud Trace แล้ว

✅ ไปยังส่วนต่างๆ ของ Cloud Trace Explorer เพื่อค้นหาการติดตามการใช้งานจริง
✅ อ่านมุมมอง Waterfall เพื่อดูลำดับการดำเนินการทั้งหมด
✅ ติดตามเชนข้อมูลเข้าสู่ระบบผ่าน 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.

This is the power of accountability trails. คุณเปลี่ยนจาก "เชื่อเรา" เป็น "ให้เราแสดงให้คุณเห็นว่าเกิดอะไรขึ้น"

ต้องทำอะไรต่อไป

ตอนนี้คุณได้ทำความเข้าใจแกนหลักทางเทคนิคของการสร้าง Agent ที่น่าเชื่อถือแล้ว ซึ่งได้แก่

✅ โมดูล 1-6: ออกแบบสถาปัตยกรรมที่เชื่อถือได้ (บทบาท, ข้อมูลเข้าสู่ระบบ, ความยินยอม)
✅ โมดูล 7: จัดระเบียบเวิร์กโฟลว์ที่ซับซ้อน (SequentialAgent)
✅ โมดูล 8: ติดตั้งใช้งานโดยเปิดใช้ความสามารถในการสังเกต
✅ โมดูล 9: เรียนรู้วิธีอ่านและใช้เส้นทางการตรวจสอบความรับผิดชอบ

สถาปัตยกรรมที่คุณสร้างขึ้น ไม่ว่าจะเป็นการแยกบทบาท, เชนข้อมูลเข้าสู่ระบบ, กลไกการขอความยินยอม, ความสามารถในการสังเกตที่สมบูรณ์ จะโอนไปยังระบบเวอร์ชันที่ใช้งานจริงโดยตรง ซึ่งจะจัดการเงินจริง ข้อมูลจริง และผลลัพธ์จริง

10. เส้นทางสู่ความสำเร็จ

สิ่งที่คุณสร้าง

คุณเริ่มเวิร์กช็อปนี้ด้วยคำถามที่ว่า "ฉันจะสร้าง AI Agent ที่ฉันไว้ใจให้จัดการเรื่องเงินได้อย่างไร"

ตอนนี้คุณมีคำตอบแล้ว

จุดเริ่มต้นของคุณ (โมดูล 3):

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

สิ่งที่คุณกำลังเรียนรู้อยู่ (โมดูล 10):

  • ✅ Agent เฉพาะทาง 3 รายที่มีการแยกบทบาท
  • ✅ ข้อมูลเข้าสู่ระบบที่ยืนยันได้ 3 รายการ (ความตั้งใจ → รถเข็น → หนังสือยินยอมหักชำระเงิน)
  • ✅ ห่วงโซ่ข้อมูลเข้าสู่ระบบที่สมบูรณ์พร้อมการตรวจสอบการหมดอายุในแต่ละขั้นตอน
  • ✅ กลไกการขอความยินยอมโดยชัดแจ้งพร้อมหลักฐานการประทับเวลา
  • ✅ การทำให้ใช้งานได้จริงใน Agent Engine พร้อมความสามารถในการสังเกต
  • ✅ เส้นทางการตรวจสอบความรับผิดชอบที่สมบูรณ์ใน Cloud Trace
  • ✅ หลักฐานทางนิติวิทยาศาสตร์สำหรับการระงับข้อพิพาท

เวิร์กช็อปเทียบกับการใช้งานจริง: ช่องว่าง

ระบบของคุณแสดงสถาปัตยกรรมและรูปแบบที่ถูกต้อง แต่ใช้การลดความซับซ้อนเพื่อการศึกษาซึ่งต้องอัปเกรดเพื่อใช้เงินจริงและผู้ใช้จริง

ต่อไปนี้คือสิ่งที่ได้รับการปรับให้เข้าใจง่ายขึ้นและสิ่งที่เวอร์ชันที่ใช้งานจริงต้องการ

ส่วนประกอบ

การนำเวิร์กช็อปไปใช้จริง

ข้อกำหนดด้านการผลิต

ลายเซ็น

แฮช SHA-256 (SIG_abc123) สำหรับการสาธิต

ลายเซ็นการเข้ารหัสจริงที่ใช้ PKI หรือ JWT กับคีย์ส่วนตัว

การประมวลผลการชำระเงิน

ผลตอบแทนจำลอง (แฟล็ก simulation: True)

การผสานรวมกับ API การชำระเงินจริง (Stripe, PayPal, Square)

การตรวจสอบสิทธิ์ผู้ใช้

ความเชื่อถือโดยนัย (ไม่ต้องเข้าสู่ระบบ)

OAuth 2.0, WebAuthn หรือการจัดการเซสชัน

Secret Manager

ตัวแปรสภาพแวดล้อมในไฟล์ .env

Google Secret Manager หรือ Cloud KMS ที่มีการเข้ารหัส

ฐานข้อมูลองค์กรการกุศล

ไฟล์ JSON จำลองที่มีองค์กรการกุศล 9 แห่ง

การผสานรวม Live API (IRS Tax Exempt Organization Search, Charity Navigator API)

การจัดการข้อผิดพลาด

Try-catch พื้นฐานพร้อมข้อความแสดงข้อผิดพลาด

ตรรกะการลองใหม่ด้วย Exponential Backoff, เซอร์กิตเบรกเกอร์, คิวข้อความที่ส่งไม่ได้

การทดสอบ

การยืนยันด้วยตนเองผ่านสคริปต์

ชุดโปรแกรมทดสอบ Unit/Integration/E2E ที่ครอบคลุมพร้อม CI/CD

ความต่อเนื่องของเซสชัน

ในหน่วยความจำ (ในเครื่อง) หรืออัตโนมัติ (Agent Engine)

ฐานข้อมูลเวอร์ชันที่ใช้งานจริงพร้อมการสำรองข้อมูลและการกู้ข้อมูลคืนหลังจากภัยพิบัติ

การจำกัดอัตราคำขอ

ไม่มี (สภาพแวดล้อมทางการศึกษา)

การจำกัดอัตราคำขอต่อผู้ใช้ การควบคุมปริมาณตาม IP การตรวจจับการละเมิด

รูปแบบสถาปัตยกรรมหลักที่คุณเชี่ยวชาญ

รูปแบบที่คุณได้เรียนรู้ในเวิร์กช็อปนี้เป็นรูปแบบการใช้งานจริง อย่าสงสัยในตัวพวกเขา

การแยกบทบาท (หลักการ AP2 ข้อที่ 1)

Agent แต่ละตัวมีงานที่ชัดเจน 1 งานและเห็นเฉพาะสิ่งที่จำเป็นเท่านั้น หาก Agent รายหนึ่งถูกบุกรุก ผู้โจมตีจะไม่สามารถเข้าถึงข้อมูลของ Agent รายอื่นๆ ได้ ซึ่งจะช่วยจำกัดขอบเขตความเสียหาย

ระบบเวอร์ชันที่ใช้งานจริงที่ใช้รูปแบบนี้: การประมวลผลการชำระเงิน, เวิร์กโฟลว์เอกสาร, เชนการอนุมัติ, แบบฟอร์มหลายขั้นตอนที่มีเกตการตรวจสอบความถูกต้อง

ข้อมูลเข้าสู่ระบบที่ยืนยันได้ (หลักการ AP2 ข้อที่ 2)

ข้อมูลเข้าสู่ระบบแต่ละรายการมีเวลาหมดอายุ อ้างอิงข้อมูลเข้าสู่ระบบก่อนหน้า และต้องมีการตรวจสอบก่อนขั้นตอนถัดไป ซึ่งจะสร้างเชนการตรวจสอบที่ป้องกันการงัดแงะ

คุณค่าในการผลิต: หลักฐานที่สมบูรณ์เกี่ยวกับสิ่งที่เกิดขึ้น เวลา และลำดับเหตุการณ์ ซึ่งจำเป็นสำหรับการระงับข้อพิพาทและการปฏิบัติตามกฎระเบียบ

หลักฐานการประทับเวลาที่ผู้ใช้อนุมัติการดำเนินการ ไม่สามารถโต้แย้งได้

ค่าที่ใช้จริง: ข้อกำหนดทางกฎหมายสำหรับธุรกรรมทางการเงิน ปกป้องทั้งผู้ใช้และบริษัท

การเรียบเรียงตามลำดับ (รูปแบบ ADK)

บังคับใช้ลำดับการดำเนินการที่ถูกต้อง ป้องกันการข้ามขั้นตอน รับประกันว่า Agent แต่ละรายจะเห็นเอาต์พุตของ Agent ก่อนหน้า

คุณค่าในการใช้งานจริง: เหมาะอย่างยิ่งสำหรับระบบแบบมีมนุษย์ร่วมซึ่งผู้ใช้คาดหวังผลลัพธ์ที่รวดเร็ว รูปแบบนี้เหมาะสำหรับขั้นตอนการบริจาค กระบวนการชำระเงิน และเชนการอนุมัติ

ความสามารถในการสังเกตที่สมบูรณ์ (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 Agent ที่น่าเชื่อถือแล้ว รูปแบบเหล่านี้จะถ่ายโอนไปยังโดเมนใดก็ตามที่ AI Agent จัดการการดำเนินการที่มีความละเอียดอ่อน เช่น ธุรกรรมทางการเงิน การตัดสินใจด้านการดูแลสุขภาพ เอกสารทางกฎหมาย การดำเนินการด้านซัพพลายเชน

การโอนหลัก โมเดลความน่าเชื่อถือได้ผล

ตอนนี้ก็ไปสร้างสิ่งที่น่าเชื่อถือได้เลย ❤️

แบนเนอร์