Building Trustworthy Charity Agents with Google ADK and AP2

1. בניית אמון כדי לעודד נדיבות

באנר

רגע של השראה

הטלפון רוטט. אתם רואים כתבה בחדשות על תוכנית אוריינות מוצלחת שעוזרת לילדים בקהילות מוחלשות ללמוד לקרוא. אתם מרגישים דחף חזק לתרום. אתם פותחים את הדפדפן ומחפשים "תרומות לתוכנית אוריינות לילדים".

חיפוש Google, חיפוש גוגל

מופיעות מאות תוצאות.

אתם לוחצים על הקישור הראשון. האתר נראה מקצועי. אתם גוללים למטה לנתונים הפיננסיים שלה. "עלויות ניהול: 28%". אתם משהים את המודעה. רק 72 סנט מכל דולר שתתרמו יממנו בפועל את התוכנית. זה טוב? אתם לא בטוחים.

אתם מנסים ארגון אחר. מעולם לא שמעתם עליהם. האם הם לגיטימיים? חיפוש מהיר מוביל אתכם למחילת הארנב. אתם מוצאים שרשור ב-Reddit מלפני שנתיים שבו אחד המשתמשים טוען: "זו תרמית, התרומה שלי לא הגיעה לשום מקום". אחרת מגנה עליהם בלהט: "הם בשטח, עושים עבודה אמיתית!" העמימות הזו משתקת.

אחרי חצי שעה, אתם מוצאים את עצמכם במבוך של ביקורות סותרות, דירוגי יעילות ודוחות של IRS, ועדיין לא תרמתם. הניצוץ הראשוני של הנדיבות הוחלף בחיכוך של המחקר. הכרטיסייה נשארת פתוחה במשך כמה ימים, תזכורת קטנה לכוונה טובה, עד שאתם סוגרים אותה בסופו של דבר.

זה לא כישלון אישי, זה כשל מערכתי

החוויה הזו היא אוניברסלית. הרצון לתת הוא גדול, אבל התהליך מלא במכשולים שגורמים להיסוס ולספק:

  • ❌ קושי במחקר: כל עמותה דורשת מחקר משלה.
  • ❌ אימות מהימנות: קשה להבחין בין ארגונים יעילים מאוד לבין ארגונים לא יעילים או אפילו תרמיות של ממש.
  • ❌ שיתוק ניתוח: מספר עצום של אפשרויות מוביל לקושי בקבלת החלטות.
  • ❌ אובדן המומנטום: הדחף הרגשי לתרום דועך ככל שהנטל הלוגיסטי גדל.

החיכוך הזה גורם לעלויות עצומות בעולם האמיתי. היקף התרומות של אנשים פרטיים בארצות הברית הוא עצום – תורמים פרטיים תרמו כ-374 מיליארד דולר בשנת 2023 בלבד, לפי Giving USA 2024. עם זאת, מחקרים מראים שהמכשולים בדרך לתרומה – כולל עלויות החיפוש, חיכוך פסיכולוגי ומגבלות זמן – מפחיתים באופן משמעותי את הסכום שמגיע למטרות צדקה. מחקרים שכללו מיליוני תורמים מצאו שאפילו קשיים קטנים בתהליך התרומה באינטרנט מונעים מאנשים לממש את כוונותיהם לתרום.

מדובר במיליארדי דולרים של תרומות שלא מגיעות למטרות שלשמן הן נועדו.

החזון

דמיינו חוויה אחרת. במקום להשקיע 30 דקות במחקר, אתם פשוט אומרים:

"אני רוצה לתרום 50 $לתוכנית ללימוד קריאה וכתיבה לילדים. תמצא לי עמותה מאומתת, יעילה ועם דירוג גבוה".

ותוך כמה שניות, אתם מקבלים תשובה שנותנת לכם ביטחון:

כרטיס תוצאות של ארגון צדקה

זה מה שסוכן AI לתרומות יכול לעשות. אבל כדי לממש את החזון הזה, אנחנו צריכים לפתור אתגר בסיסי: כשסוכן AI אוטונומי מטפל בכסף, האמון הוא לא אופציונלי, הוא הבסיס לכל המערכת.

  • איך אפשר להוכיח מה המשתמש אישר?
  • מי אחראי אם נעשית טעות?
  • איך אנחנו נותנים לתורמים, לארגוני צדקה ולרשתות תשלומים את הביטחון להשתתף?

המשימה שלך להיום

בסדנה הזו תבנו נציג מהימן באמצעות שילוב של שתי טכנולוגיות מתקדמות:

ערכת פיתוח הסוכנים (ADK) של Google

‫Agent Payments Protocol‏ (AP2)

תפקיד

הסביבה לפיתוח סוכני AI ברמה שמתאימה לסביבת ייצור

התוכנית האדריכלית לאמון בעסקאות AI

מה מקבלים

• framework לתזמור של כמה סוכנים
• אמצעי אבטחה מובנים כמו אישור כלים
• ניראות (observability) ומעקב שמוכנות לייצור
• ממשק Python פשוט להתנהגויות מורכבות של סוכנים

• גבולות אבטחה מבוססי-תפקידים
• אישורים דיגיטליים שניתנים לאימות (מנדטים)
• הוכחה קריפטוגרפית להסכמה
• נתיבי ביקורת מלאים לאחריות

מידע נוסף

מסמכי תיעוד של ADK

פרוטוקול AP2

מה תפַתחו

אדריכלות

בסוף הסדנה הזו, תיצרו:

‫✅ מערכת מרובת סוכנים עם תפקידים ייעודיים:

  • סוכן שופינג שמוצא עמותות מאומתות
  • סוכן של מוכר שיוצר הצעות מחייבות לתרומות
  • ספק פרטי כניסה שמעבד תשלומים באופן מאובטח
  • מנצח (Orchestrator) שמתאם את כל התהליך

‫✅ שלושה סוגים של פרטי כניסה ניתנים לאימות:

  • IntentMandate: "Find me an education charity"
  • CartMandate: "$50 to Room to Read, signed by merchant"
  • ‫PaymentMandate: "עיבוד באמצעות תשלום מדומה"

‫✅ אבטחה בכל שכבה:

  • גבולות אמון מבוססי-תפקיד
  • הסכמה מפורשת מהמשתמשים

‫✅ נתיב ביקורת מלא:

  • כל החלטה ניתנת למעקב
  • כל הסכמה מתועדת
  • כל העברה גלויה

🔒 חשוב: זו סביבת למידה בטוחה

רוצים לבנות אמון?

ביחידה הבאה נגדיר את סביבת הפיתוח וניצור את סוכן ה-AI הראשון שלכם. במהירות תגלו למה אי אפשר לסמוך על נציגים פשוטים, ואז תלמדו איך לפתור את הבעיה.

קודם כול, נבין מה הבעיה.

2. הכנת סביבת העבודה

הבסיס לסוכנים מהימנים

לפני שנוכל לבנות את סוכן ה-AI Giving שלנו, אנחנו צריכים להכין סביבת פיתוח נקייה, עקבית ומוגדרת בצורה נכונה. המודול הזה הוא שלב ממוקד שנועד לוודא שכל הכלים והשירותים הנדרשים קיימים.

אם תסיימו את ההגדרה הזו בהצלחה, תוכלו להתמקד לגמרי בעבודה המעניינת של בניית הלוגיקה של הנציג במודולים הבאים, בלי לדאוג לגבי בעיות בהגדרות.

גישה ל-Cloud Shell

קודם נפתח את Cloud Shell, שהוא מסוף מבוסס-דפדפן שמותקנים בו מראש Google Cloud SDK וכלים חיוניים אחרים.

לוחצים על Activate Cloud Shell בחלק העליון של מסוף Google Cloud (זהו סמל הטרמינל בסרגל הניווט שבפינה הימנית העליונה).

cloud shell

איך מוצאים את מזהה הפרויקט ב-Google Cloud:

  • פותחים את מסוף Google Cloud: ‏https://console.cloud.google.com
  • בתפריט הנפתח של הפרויקטים בחלק העליון של הדף, בוחרים את הפרויקט שרוצים להשתמש בו בסדנה הזו.
  • מזהה הפרויקט מוצג בכרטיס Project info במרכז הבקרה מזהה פרויקט

אחרי ש-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

התהליך עשוי להימשך דקה עד שתי דקות. הפרטים שמוצגים הם:

Operation "operations/..." finished successfully.

מה ממשקי ה-API האלה מספקים:

  • ‫aiplatform.googleapis.com: גישה למודלים של Gemini לצורך הסקת מסקנות של הנציג
  • ‫secretmanager.googleapis.com: אחסון מאובטח של מפתחות API (שיטה מומלצת בסביבת ייצור)
  • ‫cloudtrace.googleapis.com: ניטור של נתיב האחריות שלנו

שכפול הקוד לתחילת הדרך

מורידים את מאגר הסדנה עם כל קוד התבנית והמשאבים:

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

בואו נבדוק מה יש לנו:

ls -la

אמור להופיע:

  • ‫charity_advisor/ – המקום שבו ניצור את הסוכנים והכלים שלנו
  • ‫scripts/ – סקריפטים של עזרה לבדיקה ואימות
  • ‫deploy.sh – סקריפט עזר לפריסה
  • ‫setup.py – סקריפט עזר להתקנת מודולים
  • ‫.env.template – קובץ משתני סביבה

הגדרת סביבת Python

עכשיו ניצור סביבת Python מבודדת לפרויקט שלנו.

יצירה והפעלה של סביבה וירטואלית

# Create the virtual environment
python3 -m venv venv

# Activate it
source venv/bin/activate

✅ אימות: ההנחיה אמורה להציג עכשיו את הקידומת (venv).

התקנת יחסי תלות

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

ההתקנה כוללת:

  • google-adk: Agent Development Kit framework
  • ‫google-cloud-aiplatform: שילוב של Vertex AI ו-Gemini
  • ‫ap2: Agent Payments Protocol SDK (מ-GitHub)
  • ‫python-dotenv: ניהול משתני סביבה

הדגל -e מאפשר לייבא מודולים של adk_ap2_charity_agents מכל מקום.

הגדרת קובץ הסביבה

יוצרים את ההגדרות מהתבנית:

# Copy the template
cp .env.template .env

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

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

# Verify the replacement worked
grep GOOGLE_CLOUD_PROJECT .env

אמור להופיע:

GOOGLE_CLOUD_PROJECT=your-actual-project-id

אימות

מריצים את סקריפט האימות כדי לוודא שהכול מוגדר בצורה נכונה:

python scripts/verify_setup.py

כל סימני הווי צריכים להיות ירוקים:

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

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

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

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

פתרון בעיות

מה השלב הבא?

הסביבה שלכם מוכנה. יש לך:

  • ‫✅ הפרויקט ב-Google Cloud הוגדר
  • ‫✅ ממשקי ה-API הנדרשים מופעלים
  • ‫✅ ספריות ADK ו-AP2 מותקנות
  • ‫✅ קוד התבנית מוכן לשינוי

במודול הבא תבנו את סוכן ה-AI הראשון שלכם בכמה שורות קוד ותגלו למה סוכנים פשוטים לא אמינים כשמדובר בטיפול בעסקאות פיננסיות.

3. הסוכן הראשון שלכם ופער האמון

באנר

מרעיון לאינטראקציה

במודול הקודם הכנו את סביבת הפיתוח שלנו. עכשיו מתחילה העבודה המעניינת. נבנה ונפעיל את הנציג הראשון שלנו, ניתן לו את היכולת הראשונה שלו, ובכך נגלה את האתגרים הבסיסיים שעלינו לפתור כדי להפוך אותו לאמין באמת.

המודול הזה הוא תמונת ה "לפני" שלכם – הרגע שבו תבינו למה כדי לבנות סוכנים מהימנים לא מספיק לתת ל-LLM גישה לכלים.

שלב 1: בחינת הנציג למתחילים

קודם נסתכל על התבנית של הנציג הראשון. הוא מכיל מבנה בסיסי עם פלייסהולדרים שנשלים בשלבים הבאים.

👉 פותחים את הקובץ

charity_advisor/simple_agent/agent.py

בכלי העריכה.

הפרטים שמוצגים הם:

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

# MODULE_3_STEP_2_IMPORT_COMPONENTS


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

שימו לב שהתגובות של הפלייסהולדרים פועלות לפי תבנית: MODULE_3_STEP_X_DESCRIPTION. נחליף את הסמנים האלה כדי לבנות את הנציג שלנו בהדרגה.

שלב 2: מייבאים את הרכיבים הנדרשים

לפני שנוכל ליצור מופע של המחלקה Agent או להשתמש בכלי google_search, אנחנו צריכים לייבא אותם לקובץ שלנו.

👉 חיפוש:

# MODULE_3_STEP_2_IMPORT_COMPONENTS

👉 מחליפים את השורה הזו בשורות הבאות:

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

עכשיו המחלקה Agent והכלי google_search זמינים בקובץ שלנו.

שלב 3: כותבים את ההוראות לסוכן

ההוראה היא "תיאור התפקיד" של הסוכן – היא מסבירה ל-LLM מתי ואיך להשתמש בכלים שלו. בואו נכתוב הוראה שתנחה את הנציג לחפש מידע על ארגוני צדקה.

👉 חיפוש:

# MODULE_3_STEP_3_WRITE_INSTRUCTION
instruction="""""",

👉 מחליפים את שתי השורות האלה בשורות הבאות:

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

שלב 4: מוסיפים את כלי החיפוש

סוכן בלי כלים הוא רק שותף לשיחה. בואו ניתן לסוכן את היכולת הראשונה שלו: היכולת לחפש באינטרנט.

👉 חיפוש:

# MODULE_3_STEP_4_ADD_TOOLS
tools=[]

👉 מחליפים את שתי השורות האלה בשורות הבאות:

tools=[google_search]

שלב 5: אימות הנציג המלא

לפני שנתחיל בבדיקה, נוודא שהכול מוכן.

👉 המדריך המלא

charity_advisor/simple_agent/agent.py

אמור להיראות בדיוק כך:

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

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


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

שלב 6: בודקים את הסוכן – חושפים את פערי האמון

עכשיו, כשהסוכן מוגדר במלואו, נבדוק אותו וננתח את ההתנהגות שלו. כאן אנחנו מגלים למה סוכנים פשוטים לא אמינים כשמדובר בהחלטות פיננסיות.

בדיקה 1: בעיית הגילוי

👉 במסוף Cloud Shell, מריצים את הפקודה הבאה:

adk run charity_advisor/simple_agent

הפלט אמור להיראות כך:

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

[user]:

ההנחיה [user]: מחכה עכשיו לקלט שלכם.

👉 בפרומפט [user]:, מקלידים:

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

👉 לוחצים על Enter ובוחנים את התשובה.

אחרי כמה רגעים, הנציג יסכם את תוצאות החיפוש לתשובה כזו:

לפי חיפוש באינטרנט, כמה עמותות מוערכות שעוסקות באוריינות של ילדים הן Reading Is Fundamental ו-Room to Read. כדי לאמת את הסטטוס והדירוג של העמותה, מומלץ להשתמש במקורות כמו Charity Navigator ו-GuideStar. מצאתי גם כמה דיונים באינטרנט, כולל בפורומים כמו Reddit, שבהם משתמשים משתפים חוויות אישיות עם תוכניות אוריינות מקומיות קטנות יותר.

בואו ננתח את זה. האם הנציג פתר את הבעיה?

❌ לא. הוא משחזר בצורה מושלמת את החוויה האנושית שתיארנו במודול 1. הוא הפך את תהליך החיפוש ב-Google לאוטומטי, והחזיר לנו את הבעיה של "שיתוק מרוב ניתוח".

כאן נחשף הפער הראשון באמון: מחסור בנתונים מהימנים.

הסוכן מחפש ברחבי האינטרנט, כלומר:

  • ‫✅ הוא מצא תוצאות במהירות (חוויית משתמש משופרת)
  • ❌ הוא מערבב בין ארגונים עם דירוג גבוה לבין דיונים ב-Reddit (מקורות לא מהימנים)
  • ❌ הוא לא יכול להבחין בין עמותות מאומתות לבין הונאות פוטנציאליות (אין אימות)
  • ❌ הוא מבקש מאיתנו לאמת את המידע שהוא סיפק (מעביר את הנטל בחזרה)

בדיקה 2: בעיית הביצוע

עכשיו מגיע השלב השני והחשוב. בהודעה של [user]:, מנסים להשלים את התרומה:

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

הסוכן יתנצל ויודה במגבלה שלו:

הבנתי שרצית לתרום, וזה נהדר! עם זאת, אני עוזר מחקר ואין לי יכולת לטפל בעסקאות פיננסיות או לעבד תשלומים. כדי לתרום, צריך להיכנס ישירות לאתר הרשמי של Room to Read.

זהו רגע ה "אהה!" השני, שחשוב לא פחות.

לא רק שאי אפשר לסמוך על הסוכן שימצא את העמותה הנכונה, אלא גם אי אפשר לסמוך עליו שיבצע את פעולת התרומה.

👉 לוחצים על

Ctrl+C

כדי לצאת כשתסיימו את הבדיקה.

המחשה של שני הפערים

בעיית אמון

מה למדתם

ביחידה הזו יצרתם והגדרתם את סוכן ה-AI הראשון שלכם. כך חשפתם את שני האתגרים הבסיסיים בבניית מערכת מהימנה.

מושגי מפתח שנלמדו

✅ The Agent Class:

  • אבן הבניין המרכזית של ADK
  • משלב בין הסקת מסקנות של LLM (המוח) לבין כלים (הידיים)
  • מוגדר עם מודל, הוראות וכלים

✅ מבנה מבוסס-תיקיות:

  • כל נציג נמצא בתיקייה משלו
  • ה-ADK מחפש את agent_folder/agent.py
  • ריצה עם adk run agent_folder

✅ רשימת הכלים:

  • הגדרת היכולות האג'נטיות
  • ה-LLM מחליט מתי ואיך להשתמש בכלים
  • יכול להכיל כמה כלים לפעולות שונות

‫✅ הנחיה:

  • הנחיות להתנהגות של הסוכן, כמו תיאור תפקיד
  • מגדירה תפקיד, טריגרים, פעולות ופורמט פלט
  • חשוב מאוד להשתמש בכלי אמין

‫✅ בעיית האמון:

  • פערים בחיפוש: מקורות שלא נבדקו, איכות מעורבת
  • פער בביצוע: אין יכולות אבטחה, אין הסכמה, אין נתיב ביקורת

המאמרים הבאים

במודול הבא נתחיל לבנות את הפתרון על ידי הטמעת הארכיטקטורה מבוססת התפקידים של AP2.

בואו ניצור את הנציג הראשון ונראה איך הפרדת התפקידים פועלת.

4. פיתוח סוכן השופינג – גילוי מבוסס-תפקיד

באנר

הבסיס לאמון: הפרדת תפקידים

ביחידה הקודמת גיליתם שסוכן לשימוש כללי נכשל בשתי חזיתות: הוא לא יכול לספק חיפוש מהימן, והוא לא יכול לבצע עסקאות מאובטחות. עכשיו נתחיל לפתור את הבעיות האלה על ידי יישום העיקרון הראשון של Agent Payments Protocol: ארכיטקטורה מבוססת-תפקידים.

לפני שנתחיל לכתוב קוד, נבין למה העיקרון הזה חשוב.

עיקרון AP2: הפרדת תפקידים

הבעיה עם סוכנים שעושים הכול

נניח שאתם שוכרים אדם אחד שיהיה היועץ הפיננסי, רואה החשבון וסוכן ההשקעות שלכם. נוח? כן. מאובטח? בהחלט לא. הם היו:

  • יעדי ההשקעה שלכם (תפקיד של יועץ)
  • גישה לחשבונות שלכם (תפקיד רואה חשבון)
  • סמכות להעביר את הכסף שלכם (תפקיד של ברוקר)

אם האדם הזה נפגע או עושה טעות, כל המידע נמצא בסיכון.

הפתרון של AP2: סוכן אחד, משימה אחת

ב-AP2 מיושם העיקרון של הפרדת תחומי האחריות כדי ליצור גבולות אמון:

אדריכלות

למה זה חשוב:

  • ‫✅ רדיוס פיצוץ מוגבל: אם סוכן השופינג נפרץ, לתוקף אין גישה לפרטי הכניסה לתשלום
  • ‫✅ פרטיות: ספק פרטי הכניסה אף פעם לא רואה את השיחה שלכם בנושא הקניות
  • ‫✅ תאימות: קל יותר לעמוד בדרישות של PCI-DSS כשנתוני התשלומים מבודדים
  • ‫✅ אחריותיות: אחריות ברורה לכל שלב

איך הסוכנים מתקשרים: המצב בתור פנקס הרשימות המשותף

מכיוון שהסוכנים לא יכולים לגשת ישירות לנתונים אחד של השני, הם מתקשרים באמצעות מצב משותף. אפשר לחשוב על זה כמו לוח שכל הנציגים יכולים לכתוב עליו ולקרוא ממנו:

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

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

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

כך אנחנו שומרים על גבולות האמון ומאפשרים שיתוף פעולה.

הסוכן הראשון שלנו: סוכן השופינג

תחומי האחריות של סוכן השופינג פשוטים וממוקדים:

  1. אפשר להשתמש בכלי find_charities כדי לשלוח שאילתות למסד הנתונים המהימן שלנו
  2. הצגת אפשרויות למשתמש
  3. משתמשים בכלי save_user_choice כדי ליצור IntentMandate ולשמור אותו במצב
  4. העברה לנציג הבא (המוכר)

זה הכול. אין טיפול בתשלומים, אין יצירה של עגלת קניות – רק גילוי והעברה.

בואו נבנה אותו שלב אחר שלב.

שלב 1: מוסיפים את Input Validation Helper

כשמפתחים כלים לסביבת ייצור, אימות הקלט הוא קריטי. בואו ניצור פונקציית עזר שמאמתת את נתוני העמותה לפני שהם נשמרים ב-state.

👉 פתיחה

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

עכשיו ניצור את ה-helper שבונה את המבנה של IntentMandate ב-AP2. זהו אחד משלושת פרטי הכניסה הניתנים לאימות ב-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 ושומר אותו ב-state.

👉 באותו קובץ, גוללים למטה אל

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

לפני שיוצרים את הנציג, נוסיף עוד פונקציית עזר שמעצבת את נתוני העמותה לתצוגה ידידותית למשתמש.

👉 גוללים כדי למצוא את:

# MODULE_4_STEP_4_ADD_FORMATTING_HELPER

👉 מחליפים את השורה הזו בשורות הבאות:

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

שלב 5: בניית הסוכן החכם של שופינג – ייבוא רכיבים

עכשיו, כשהכלים שלנו שלמים וחזקים, ניצור את הנציג שישתמש בהם.

👉 פתיחה

charity_advisor/shopping_agent/agent.py

תופיע תבנית עם הערות פלייסהולדר. בואו נבנה אותו שלב אחר שלב.

👉 חיפוש:

# MODULE_4_STEP_5_IMPORT_COMPONENTS

👉 מחליפים את השורה הזו בשורות הבאות:

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

שלב 6: כותבים את ההוראות לסוכן

בהוראה אנחנו מגדירים את תיאור התפקיד ואת תהליך העבודה של הנציג. זה קריטי – הוראה שכתובה בצורה לא טובה מובילה להתנהגות לא אמינה.

👉 חיפוש:

# MODULE_4_STEP_6_WRITE_INSTRUCTION
instruction="""""",

👉 מחליפים את שתי השורות האלה בשורות הבאות:

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

Your workflow:

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

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

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

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

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

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

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

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

שלב 7: מוסיפים כלים לסוכן

עכשיו ניתן לסוכן גישה לשני הכלים.

👉 חיפוש:

# MODULE_4_STEP_7_ADD_TOOLS

👉 מחליפים את שתי השורות האלה בשורות הבאות:

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

שלב 8: אימות הנציג המלא

כדאי לבדוק שהכול מחובר כמו שצריך.

👉 המדריך המלא

charity_advisor/shopping_agent/agent.py

אמור להיראות עכשיו כך:

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

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


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

Your workflow:

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

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

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

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

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

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

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

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

✅ מעולה! יצרתם נציג באיכות ייצור שתואם ל-AP2 עם:

  • אימות קלט
  • יצירה תקינה של IntentMandate באמצעות מודלים של AP2 Pydantic
  • פלט מעוצב
  • גבולות ברורים לתפקידים
  • הוראות מפורטות
  • טיפול בשגיאות

שלב 9: בודקים את סוכן השופינג

בואו נוודא שהנציג שלנו פועל בצורה תקינה, יוצר IntentMandates מתאימים ומכבד את הגבולות שלו.

👉 בטרמינל של Cloud Shell, מריצים את הפקודה:

adk run charity_advisor/shopping_agent

תופיע ההנחיה [user]:.

בדיקה 1: גילוי באמצעות מסד נתונים מהימן

👉 סוג:

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

אחרי כמה רגעים, הסוכן ייתן תשובה. התוצאות מעוצבות בצורה יפה בזכות פונקציית העזר _format_charity_display:

מצאתי במסד הנתונים שלנו 3 עמותות מאומתות בתחום החינוך:

‫Room to Read (מספר EIN‏: 77-0479905)
⭐ דירוג: 4.9/5.0
💰 יעילות: 88% מהכספים מועברים לתוכניות
📋 מטרה: שינוי חייהם של מיליוני ילדים בקהילות עם הכנסה נמוכה על ידי התמקדות באוריינות ובשוויון מגדרי בחינוך.

‫Teach For America (מספר EIN‏: 13-3541913)
⭐ דירוג: 4.7 מתוך 5.0
💰 יעילות: 81% מהכספים מועברים לתוכניות
📋 מטרה: פועל להרחבת ההזדמנויות החינוכיות לילדים שמתמודדים עם קשיים.

Tech Education Alliance (EIN: 45-2345678)
⭐ דירוג: 4.8/5.0
💰 יעילות: 92% מהכספים מועברים לתוכניות
📋 מטרה: להביא את החינוך למדעי המחשב לבתי ספר שאין להם גישה לזה.

באיזו עמותה היית רוצה לתמוך, וכמה היית רוצה לתרום?

השוו את זה לסוכן הפשוט ביחידה 3, שנתן לכם תוצאות לא מאומתות מ-Google. זה ההבדל בין גילוי לא מהימן לגילוי מהימן.

בדיקה 2: תיעוד אפשרויות בחירה למשתמשים ויצירת IntentMandate

👉 סוג:

I'll donate $50 to Room to Read.

הנציג אמור להפעיל את הכלי save_user_choice עם הפרמטרים הנכונים. בזכות יצירת IntentMandate באמצעות מודלים של AP2, התשובה שתקבלו תהיה מובנית יותר:

יופי! יצרתי IntentMandate לתרומה שלך:

פרטי Intent:

  • Intent ID: intent_774795905_1730927536
  • סכום: 50.00$ לארגון Room to Read (מספר EIN‏: 77-0479905)
  • תאריך תפוגה: 2024-11-07T15:32:16Z (בעוד שעה)

ה-IntentMandate הזה מתעד את כוונת התרומה שלכם וכולל אילוצים כדי להבטיח שהעסקה תעובד בצורה מאובטחת. עכשיו אעביר את זה לספק שירותי התשלומים המאובטח שלנו כדי ליצור הצעה רשמית ולהשלים את התרומה שלך.

מאחורי הקלעים, כמה דברים קרו:

  1. ‫_validate_charity_data() אימת את הקלט
  2. ‫_create_intent_mandate() השתמש במודל AP2 Pydantic כדי ליצור את המבנה:
   # Created and validated via Pydantic
   intent_mandate_model = IntentMandate(
       user_cart_confirmation_required=True,
       natural_language_description="Donate $50.00 to Room to Read",
       merchants=["Room to Read"],
       skus=None,
       requires_refundability=False,
       intent_expiry="2024-11-07T15:32:16Z"
   )
   
   # Converted to dict and extended with custom fields
   intent_mandate_dict = intent_mandate_model.model_dump()
   intent_mandate_dict.update({
       "charity_ein": "77-0479905",
       "amount": 50.0,
       "currency": "USD"
   })
  1. הכלי כתב רק את IntentMandate למצב המשותף:
   state["intent_mandate"] = intent_mandate_dict
  1. הודעת הצלחה עם פרטי הכוונה הוחזרה ל-LLM
  2. ה-LLM ניסח את ההודעה הסופית למשתמש

ה-IntentMandate הזה מוכן עכשיו לאיסוף על ידי סוכן המכירות (מודול 5). המוכר יחלץ את שם העמותה והסכום מ-IntentMandate ויוודא שהתוקף שלו לא פג.

בדיקה 3: אימות בפעולה

בואו נוודא שכלי העזר לאימות מזהה קלט שגוי.

👉 סוג:

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

הנציג צריך לזהות את הסכום הלא תקין:

נתקלתי בבעיה: סכום התרומה חייב להיות חיובי, אבל קיבלתי: ‎$-25.0

צריך לציין סכום תרומה חיובי ואני אצור בשבילך את IntentMandate.

זו דוגמה לתכנות הגנתי בפעולה. הכלי _validate_charity_data מנע כניסה של נתונים לא חוקיים למערכת ויצירה של IntentMandate לא תקין.

בדיקה 4: אימות גבול האמון

👉 נסו לבקש מהסוכן לעבד את התשלום:

Now process my credit card payment.

הסוכן צריך לסרב, בהתאם לגבולות התפקיד שלו:

אין לי אפשרות לעבד תשלומים – זה לא חלק מהתפקיד שלי. התפקיד שלי הוא לעזור לך למצוא עמותות מאומתות וליצור את IntentMandate שמתעד את כוונת התרומה שלך.

ה-IntentMandate כבר נוצר והועבר לספק שירותי התשלומים המאובטח שלנו. הסוכן של המוכר ייצור הצעה רשמית (CartMandate), ואז ספק פרטי הכניסה יטפל בתשלום בפועל בהסכמתכם המפורשת.

ככה פועל גבול האמון. הנציג יודע שאין לו הרשאה לטפל בנתוני תשלומים, וההוראות שלו מנחות אותו במפורש להסביר את זה למשתמשים, וגם ללמד אותם על הקונספט של IntentMandate.

👉 לוחצים על

Ctrl+C

כדי לצאת כשתסיימו את הבדיקה.

מה שיצרתם עכשיו

הטמעתם בהצלחה את החלק הראשון של הארכיטקטורה של AP2 עם יצירה נכונה של IntentMandate באמצעות מודלים של AP2 Pydantic.

מושגי מפתח שנלמדו

‫✅ ארכיטקטורה מבוססת-תפקידים:

  • לכל נציג יש תפקיד אחד שמוגדר בבירור
  • הסוכנים מתקשרים באמצעות מצב משותף, ולא באמצעות גישה ישירה
  • גבולות האמון מגבילים את ההשפעה של פגיעה באבטחה

‫✅ IntentMandate (AP2 Credential #1):

  • נוצר באמצעות מודלים רשמיים של AP2 Pydantic לאימות
  • תיעוד מובנה של כוונת המשתמש (Intent)
  • כולל תפוגה מטעמי אבטחה (למניעת התקפות של הפעלה חוזרת)
  • מציין אילוצים (מוכרים, אפשרות לקבל החזר כספי, אישור)
  • תיאור בשפה טבעית לבני אדם
  • פורמט קריא למכונה לסוכנים
  • המודל אומת לפני ההמרה למילון

‫✅ מצב כזיכרון משותף:

  • ‫tool_context.state הוא "הפנקס" שכל הנציגים יכולים לגשת אליו
  • כתיבה למצב = הפיכת פרטי כניסה ניתנים לאימות לזמינים
  • קריאה מהמצב = צריכה ואימות של פרטי הכניסה
  • סוכנים במורד הזרם מחלצים את מה שהם צריכים מפרטי הכניסה

‫✅ FunctionTool:

  • המרת פונקציות Python לכלים שניתן להפעיל באמצעות LLM
  • מסתמך על מחרוזות תיעוד ורמזים לסוגי נתונים כדי שה-LLM יבין את הקוד
  • הפעלה אוטומטית
  • קומפוזביליות של כלים: כלים קטנים וממוקדים > כלים מונוליתיים

‫✅ הוראות לנציגים:

  • הנחיות מפורטות לתהליך העבודה
  • גבולות ברורים ("אל תעשה…")
  • מפרטי פרמטרים למניעת שגיאות
  • הגדרות טכניות (מה זה IntentMandate)
  • טיפול במקרי קצה (מה אומרים כש…)

המאמרים הבאים

במודול הבא, נבנה את סוכן המוכר כדי לקבל את IntentMandate וליצור את האישור השני שניתן לאימות: CartMandate.

סוכן השופינג יצר IntentMandate שמתעד את כוונת המשתמש עם תאריך תפוגה. עכשיו אנחנו צריכים סוכן שיקרא את פרטי הכניסה האלה, יוודא שהתוקף שלהם לא פג וייצור הצעה רשמית וחתום שאומרת: "אני, המוכר, אכבד את המחיר הזה ואספק את הסחורה הזו".

בואו ניצור את הסוכן של Merchant ונראה את פרטי הכניסה השניים של AP2 בפעולה.

5. יצירת סוכן Merchant – הצעות מחייבות ו-CartMandate

באנר

מגילוי למחויבות

במודול הקודם, יצרתם את סוכן השופינג – מומחה שמוצא עמותות מאומתות ויוצר IntentMandate שמתעד את כוונת המשתמש. עכשיו אנחנו צריכים נציג שיקבל את ה-IntentMandate וייצור הצעה רשמית ומחייבת.

כאן נכנס לתמונה העיקרון השני של AP2: אישורים שניתנים לאימות באמצעות CartMandate.

עיקרון AP2: ייפוי כוח לעגלת הקניות והצעות מחייבות

למה אנחנו צריכים תפקיד של מוכר

ביחידה 4, סוכן השופינג יצר IntentMandate ושמר אותו במצב:

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

אבל זו רק כוונת המשתמש (Intent). כדי שנוכל לעבד תשלום, אנחנו צריכים:

  • מבנה הצעה רשמי שמערכות תשלומים מבינות
  • הוכחה לכך שהמוכר יכבד את המחיר הזה
  • התחייבות מחייבת שאי אפשר לשנות באמצע העסקה
  • אימות שהכוונה לא פגה

זה התפקיד של סוכן Merchant.

מה זה CartMandate?

CartMandate הוא המונח של AP2 ל"עגלת קניות דיגיטלית" שמשמשת כהצעה מחייבת. הוא בנוי לפי תקן PaymentRequest של W3C, כלומר:

  • ספקי שירותי תשלומים ברחבי העולם מזהים את הפורמט
  • הוא מכיל את כל פרטי העסקה בצורה אחידה
  • אפשר לחתום עליו באופן קריפטוגרפי כדי להוכיח את האותנטיות שלו.

אפשר לחשוב על זה כמו על הצעת מחיר בכתב מקבלן:

  • ❌ בעל פה: "כן, אני יכול לעשות את העבודה הזו תמורת חמישים שקל בערך"
  • ‫✅ הצעת מחיר בכתב: פירוט העלויות, סכום כולל, חתימה, תאריך

הצעת המחיר בכתב מחייבת. ה-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
}

שלושה רכיבים עיקריים:

‫1. contents – רכיב העטיפה של עגלת הקניות, שמכיל את:

  • מזהה עגלת הקניות ותאריך התפוגה שלה
  • שם הסוחר
  • ‫W3C PaymentRequest

‫2. payment_request (בתוך contents) – מה נרכש:

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

המשימה שלנו: לפתח את סוכן המכירות הווירטואלי

הסוכן של המוכר:

  1. קריאת IntentMandate מהמצב (מה שסוכן השופינג כתב)
  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א: יצירת החתימה וההגדרה של הכלי

עכשיו נתחיל ליצור את הכלי הראשי. ניצור אותו בהדרגה בארבעה שלבי משנה. קודם כל, חתימת הפונקציה וההגדרה הראשונית.

👉 חיפוש:

# 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 ונעטוף אותו ב-CartMandate של AP2 באמצעות מודלים של 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 ונשמור אותו במצב של הנציג הבא.

👉 חיפוש:

# MODULE_5_STEP_3D_ADD_SIGNATURE_AND_SAVE

👉 מחליפים את השורה הזו בשורות הבאות:

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

‫שלב 4: בניית הנציג של המוֹכר – ייבוא רכיבים

עכשיו ניצור את הסוכן שישתמש בכלי הזה.

👉 פתיחה

charity_advisor/merchant_agent/agent.py

תופיע תבנית עם סמני פלייסהולדר. נתחיל בייבוא של מה שאנחנו צריכים.

👉 חיפוש:

# MODULE_5_STEP_4_IMPORT_COMPONENTS

👉 מחליפים את השורה הזו בשורות הבאות:

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

שלב 5: כותבים את ההוראות לסוכן של Merchant Center

עכשיו נכתוב את ההוראה שאומרת לסוכן מתי ואיך להשתמש בכלי שלו.

👉 חיפוש:

# MODULE_5_STEP_5_WRITE_INSTRUCTION
instruction="""""",

👉 מחליפים את שתי השורות האלה בשורות הבאות:

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

Your workflow:

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

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

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

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

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

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

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

שלב 6: הוספת כלים לסוכן של Merchant Center

👉 חיפוש:

# MODULE_5_STEP_6_ADD_TOOLS
tools=[],

👉 מחליפים את שתי השורות האלה בשורות הבאות:

    tools=[
        FunctionTool(func=create_cart_mandate)
    ],

שלב 7: אימות של סוכן המכירות המלא

כדאי לוודא שהכול מחובר כמו שצריך.

👉 המדריך המלא

charity_advisor/merchant_agent/agent.py

אמור להיראות עכשיו כך:

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

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


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

Your workflow:

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

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

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

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

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

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

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

‫✅ נקודת בקרה: עכשיו יש לכם סוכן Merchant Agent שלם עם יצירה תקינה של AP2 CartMandate באמצעות מודלים של Pydantic.

שלב 8: בודקים את סוכן Merchant

עכשיו נוודא שהנציג שלנו יוצר בצורה נכונה את CartMandates עם חתימות ומאמת את התפוגה.

הגדרת הבדיקה: הרצת סקריפט הבדיקה

👉 בטרמינל של Cloud Shell, מריצים את הפקודה:

python scripts/test_merchant.py

הפלט המצופה:

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

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

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

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

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

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

בדיקה 2: אימות התאימות ל-W3C

בואו נוודא שהמבנה של CartMandate תואם באופן מלא לתקנים של AP2 ושל W3C PaymentRequest.

👉 מריצים את סקריפט האימות:

python scripts/validate_cartmandate.py

הפלט המצופה:

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

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

מה שיצרתם עכשיו

הטמעתם בהצלחה את CartMandate של AP2 באמצעות מודלים של Pydantic כדי להבטיח מבנה תקין, אימות תפוגה וחתימות של מוכרים.

מושגי מפתח שנלמדו

‫✅ CartMandate (AP2 Credential #2):

  • נוצר באמצעות מודלים רשמיים של AP2 Pydantic
  • מבנה AP2 עם מעטפת תוכן
  • W3C PaymentRequest nested inside
  • תפוגת תוקף של עגלת הקניות (קצרה יותר מהכוונה)
  • חתימת המוכר על התחייבות מחייבת
  • אימות המודל מבטיח תאימות למפרט

‫✅ אימות תאריך התפוגה:

  • קריאת IntentMandate מהמצב
  • אימות המבנה באמצעות IntentMandate.model_validate()
  • ניתוח חותמות זמן בפורמט ISO 8601
  • השוואה לזמן הנוכחי
  • אמצעי אבטחה שמונע עיבוד של נתונים לא עדכניים

‫✅ חתימת המוכר:

  • מוכיח אותנטיות ומחויבות
  • נוצר ממודל Pydantic מאומת
  • משתמש ב-model_dump(mode='json') לייצוג קנוני
  • הדמיה באמצעות SHA-256 למטרות חינוכיות
  • בסביבת הייצור משתמשים ב-PKI או ב-JWT
  • חתימה על מודל התוכן, לא על המילונים

‫✅ W3C PaymentRequest:

  • מבוסס על המודל PaymentRequest Pydantic של AP2
  • התקן המקובל בתחום לנתוני תשלום
  • מקונן בתוך מבנה AP2
  • מכיל את method_data, ‏ details, ‏ options
  • מאפשרת יכולת פעולה הדדית

✅ שרשרת פרטי כניסה עם מודלים:

  • שופינג ← IntentMandate (מאומת)
  • המוכר קורא את IntentMandate‏ ← CartMandate (שני המודלים מאומתים)
  • ספק פרטי הכניסה יקרא את CartMandate‏ ← PaymentMandate
  • כל שלב מאמת את פרטי הכניסה הקודמים באמצעות Pydantic

‫✅ פיתוח מבוסס-מודל:

  • אימות קלט באמצעות model_validate()
  • בנייה עם מניעת שגיאות הקלדה
  • הוספה אוטומטית של מספרים סידוריים באמצעות model_dump()
  • תבניות מוכנות לייצור

המאמרים הבאים

במודול הבא, נבנה את ספק פרטי הכניסה כדי לעבד תשלומים בצורה מאובטחת.

הסוכן של Merchant Center יצר הצעה מחייבת עם תאריך תפוגה באמצעות מודלים של AP2. עכשיו אנחנו צריכים סוכן שיקרא את ה-CartMandate, יקבל הסכמה מהמשתמש ויבצע את התשלום.

בואו נבנה את ספק פרטי הכניסה ונשלים את שרשרת פרטי הכניסה של AP2.

6. פיתוח ספק פרטי הכניסה – ביצוע תשלום מאובטח

באנר

מהצעה מחייבת ועד לביצוע התשלום

ביחידה 5 יצרתם את סוכן המכירות – סוכן מומחה שקורא את IntentMandates, מאמת שהם לא פגו, ויוצר CartMandates מחייבים עם חתימות של מוכרים. עכשיו אנחנו צריכים סוכן שיקבל את ה-CartMandate ויבצע את התשלום בפועל.

כאן נכנס לתמונה העיקרון השלישי והאחרון של 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 לאישור הסופי שמאפשר לבצע את התשלום. זהו האישור השלישי והאחרון שניתן לאימות בשרשרת AP2.

אפשר לחשוב על שלושת פרטי הכניסה כמו על תהליך חתימה על חוזה:

  • IntentMandate: "אני רוצה לקנות את זה" (הצהרת כוונות)
  • CartMandate: "אני, המוכר, מציע למכור במחיר הזה" (הצעת מחיר כתובה)
  • ‫PaymentMandate: "אני מאשר/ת לך לחייב את אמצעי התשלום שלי" (חוזה חתום)

רק אחרי שכל שלושת פרטי הכניסה קיימים, אפשר לבצע תשלום.

שרשרת פרטי כניסה מלאה

המבנה של 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 – מעטפת ההרשאה שמכילה את:

  • ‫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: מוסיפים את Cart Expiry Validation Helper

קודם כול, ניצור פונקציית עזר שמאמתת שהתוקף של 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, נדמה עיבוד תשלומים ונשמור את הכול ב-state.

👉 חיפוש:

# 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: בניית הסוכן של ספק פרטי הכניסה – ייבוא רכיבים

עכשיו ניצור את הסוכן שמשתמש בכלי הזה.

👉 פתיחה

charity_advisor/credentials_provider/agent.py

תופיע תבנית עם סמני פלייסהולדר. נתחיל בייבוא של מה שאנחנו צריכים.

👉 חיפוש:

# MODULE_6_STEP_4_IMPORT_COMPONENTS

👉 מחליפים את השורה הזו בשורות הבאות:

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

שלב 5: כותבים את ההוראות לספק פרטי הכניסה

עכשיו נכתוב את ההוראה שמנחה את הסוכן.

👉 חיפוש:

# MODULE_6_STEP_5_WRITE_INSTRUCTION
instruction="""""",

👉 מחליפים את שתי השורות האלה בשורות הבאות:

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

Your workflow:

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

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

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

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

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

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

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

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

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

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

שלב 6: הוספת כלים לספק פרטי הכניסה

👉 חיפוש:

# MODULE_6_STEP_6_ADD_TOOLS
tools=[],

👉 מחליפים את שתי השורות האלה בשורות הבאות:

    tools=[
        FunctionTool(func=create_payment_mandate)
    ],

שלב 7: אימות של ספק פרטי הכניסה המלא

כדאי לוודא שהכול מחובר כמו שצריך.

👉 המדריך המלא

charity_advisor/credentials_provider/agent.py

אמור להיראות עכשיו כך:

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

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


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

Your workflow:

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

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

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

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

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

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

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

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

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

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

✅ נקודת בדיקה: כעת יש לך ספק אישורים מלא עם קריאת CartMandate ויצירת PaymentMandate תקינים באמצעות מודלים של AP2 Pydantic.

שלב 8: בודקים את ספק פרטי הכניסה

עכשיו נוודא שהנציג שלנו מעבד את התשלומים בצורה נכונה ומשלים את שרשרת פרטי הכניסה.

👉 בטרמינל של Cloud Shell, מריצים את הפקודה:

python scripts/test_credentials_provider.py

הפלט המצופה:

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

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

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

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

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

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

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

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

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

שלב 9: בודקים את כל תהליך העבודה של שלושת הנציגים

עכשיו נבדוק את שלושת הנציגים כשהם עובדים ביחד.

👉 מריצים את בדיקת הצינור המלאה:

python scripts/test_full_pipeline.py

הפלט המצופה:

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

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

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

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

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

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

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

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

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

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

ככה פועלת שרשרת האישורים המלאה של AP2.

כל סוכן:

  1. קריאת פרטי כניסה מהמצב
  2. מאמת את הנתונים באמצעות מודלים של Pydantic (מבנה + בדיקת תפוגה)
  3. יצירת פרטי הכניסה הבאים באמצעות מודלים של AP2
  4. כותב למצב של הנציג הבא

מה שיצרתם עכשיו

השלמתם בהצלחה את שרשרת האישורים של שלושת הנציגים ב-AP2, עם אימות מבנה תקין באמצעות מודלים של Pydantic וסימולציית תשלום.

מושגי מפתח שנלמדו

✅ PaymentMandate (AP2 Credential #3):

  • נוצר באמצעות מודלים רשמיים של AP2 Pydantic
  • פרטי כניסה סופיים שמאשרים את ביצוע התשלום
  • קישורים ל-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 דקות) מהכוונה (שעה)

✅ סימולציית תשלום:

  • הדמיה לימודית של ספק שירותי תשלומים אמיתי
  • יצירת מזהה עסקה
  • מתעד את payment_result במצב
  • מסומן בבירור כסימולציה (סימולציה: סימון True)

✅ שרשרת AP2 מלאה עם מודלים:

  • שלושה נציגים, שלושה פרטי כניסה, שלושה אימותים של Pydantic
  • כל נציג מאמת את המבנה של פרטי הכניסה הקודמים באמצעות מודלים
  • כל פרטי כניסה מקושרים לפרטי הכניסה הקודמים לצורך נתיב ביקורת
  • העברת הטיפול על סמך מצב שומרת על הפרדת התפקידים
  • מניעת שגיאות הקלדה לאורך כל השרשרת

‫✅ פיתוח מבוסס-מודל:

  • אימות קלט באמצעות model_validate()
  • יצירת מודלים עם מניעת שגיאות הקלדה באמצעות מודלים בתצוגת עץ
  • סדרה אוטומטית באמצעות model_dump(mode='json')
  • תבניות מוכנות לייצור מההתחלה

המאמרים הבאים

במודול הבא נבנה את סוכן הניהול שמתאם בין שלושת הסוכנים המומחים.

יצרתם שלושה סוכנים מומחים ורבי-עוצמה באמצעות מודלים של AP2 Pydantic. עכשיו נבנה את המנצח שמנצח עליהם כדי ליצור חוויית תרומה חלקה.

בואו נבנה את ה-Orchestrator ונראה את המערכת המלאה בפעולה.

7. תזמור – איך הכול משתלב יחד

פייפליין רציף

ממומחים לחוויה חלקה

ביחידות הקודמות, יצרתם שלושה נציגים מיוחדים:

  • סוכן שופינג: מוצא עמותות ויוצר IntentMandate
  • סוכן המכירות: יוצר CartMandate מ-IntentMandate
  • ספק פרטי הכניסה: יוצר את PaymentMandate ומעבד את התשלום

הסוכנים האלה מתחלקים באופן טבעי לשני שלבים:

  • שלב 1 (שופינג): שיחה עם כמה שלבים כדי למצוא ולבחור ארגון צדקה
  • שלב 2 (עיבוד): ביצוע אטומי של יצירת ההצעה והתשלום

אבל כרגע, אתם צריכים לתזמר את השלבים האלה בעצמכם באופן ידני.

כאן באים לידי ביטוי דפוסי התיאום של ADK.

עיקרון AP2: תזמור אוכף את גבולות האמון

למה תזמור חשוב לאבטחה

תזמור לא קשור רק לנוחות – הוא קשור לאכיפת גבולות האמון באמצעות ארכיטקטורה.

בלי תזמור:

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

עם תזמור:

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

צינור עיבוד הנתונים הסדרתי מבטיח:

  • ‫✅ IntentMandate נוצר לפני CartMandate
  • ‫✅ CartMandate נוצר לפני עיבוד התשלום
  • ‫✅ כל נציג פועל בהקשר מבודד משלו
  • ‫✅ המצב עובר קדימה בשרשרת פרטי הכניסה

המשימה שלנו: לבנות את המערכת המלאה

ניצור שתי שכבות:

שכבה 1: צינור עיבוד הנתונים (SequentialAgent)

  • מקשר בין המוכר ← לפרטי הכניסה
  • הפעולה מתבצעת באופן אוטומטי ברצף אחרי שבוחרים את העמותה
  • ביצוע אטומי של הצעה ותשלום

שכבה 2: Root Orchestrator (סוכן שגלוי למשתמשים)

  • אישיות ידידותית
  • העברת בקשות ל-shopping_agent לבחירת ארגון צדקה
  • העברה לצינור עיבוד נתונים אחרי שנוצר IntentMandate
  • מטפל בשיחות ובמעברים בין שלבים

הגישה הדו-שכבתית הזו תואמת לתהליך הטבעי:

  • שלב הקנייה: שיחה רב-שלבית (המשתמש מעיין, שואל שאלות, מחליט)
  • שלב העיבוד: ביצוע אטומי (הצעה ← תשלום)

בואו נבנה את שניהם.

שלב 1: מייבאים את רכיבי התזמור

קודם כל, נגדיר את קובץ התזמור עם הייבוא הנדרש.

👉 פתיחה

charity_advisor/agent.py

נתחיל עם ייבוא:

👉 חיפוש:

# MODULE_7_STEP_1_IMPORT_COMPONENTS

👉 מחליפים את השורה הזו בשורות הבאות:

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

שלב 2: יצירת צינור עיבוד הנתונים

עכשיו ניצור את צינור עיבוד הנתונים שמפעיל את יצירת ההצעה ואת עיבוד התשלום באופן אטומי.

👉 חיפוש:

# MODULE_7_STEP_2_CREATE_SEQUENTIAL_PIPELINE

👉 מחליפים את שתי השורות האלה בשורות הבאות:

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

שלב 3א: הגדרת הסוכן הראשי

עכשיו ניצור את הנציג שגלוי למשתמשים, שמתזמר את שני השלבים. נבנה את זה בשלושה חלקים: הגדרה (3א), הוראות (3ב) וסוכני משנה (3ג).

👉 חיפוש:

# 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ב: כותבים את ההוראות לסוכן הראשי

עכשיו נוסיף את ההוראה שמנחה את ההתנהגות של היועץ לעמותות בשני השלבים.

👉 חיפוש:

# 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ג': הוספת סוכני המשנה

לסיום, נותנים ליועץ הצדקה גישה גם לסוכן השופינג וגם לצינור עיבוד הנתונים, וסוגרים את הגדרת הסוכן.

👉 חיפוש:

# MODULE_7_STEP_3C_ADD_ROOT_AGENT_SUBAGENTS

👉 מחליפים את השורה הזו בשורות הבאות:

    sub_agents=[
        shopping_agent,
        donation_processing_pipeline
    ]
)

שלב 4: בודקים את המערכת כולה

עכשיו נוודא שהתזמור מוגדר כמו שצריך.

👉 המדריך המלא

charity_advisor/agent.py

אמור להיראות עכשיו כך:

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

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

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

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

Your workflow has TWO distinct phases:

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

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

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

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

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

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

שלב 5: הקשחת האבטחה באמצעות קריאות חוזרות (callbacks) לאימות (אפשר לדלג לשלב 7)

קריאות חוזרות (callbacks)

ה-SequentialAgent מבטיח את סדר הביצוע, אבל מה קורה אם:

  • סוכן השופינג נכשל בלי להציג הודעה (IntentMandate לא נוצר אף פעם)
  • עוברת שעה בין Shopping ל-Merchant (התוקף של ה-intent פג)
  • המצב נפגם או נמחק
  • מישהו מנסה להתקשר ישירות למוכר, בלי לעבור דרך Google שופינג

קריאות חוזרות (callbacks) מוסיפות אכיפה ארכיטקטונית – הן מאמתות את הדרישות המוקדמות עוד לפני שהנציג מתחיל את הקריאה ל-LLM. זוהי הגנה מעמיקה: הכלים מאמתים במהלך הביצוע, והקריאות החוזרות מאמתות לפני הביצוע.

בואו נוסיף קריאות חוזרות (callbacks) לאימות לנציגים של המוכר ושל ספק פרטי הכניסה.

שלב 5א: הוספת אימות של המוכר – ייבוא סוגי קריאות חוזרות (callback)

קודם כול, נוסיף את הייבוא שנדרש לקריאות החוזרות (callbacks).

👉 פתיחה

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 לפני ש-Merchant Agent פועל.

👉 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(...)

הגדרה:

מוצאים את השורה הזו בהגדרה של הנציג:

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

מוסיפים את השורה הזו מיד אחרי

description

:

    before_agent_callback=validate_intent_before_merchant,

עכשיו הגדרת הנציג אמורה להיראות כך:

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

שלב 6: הוספת אימות של ספק פרטי הכניסה (אופציונלי, אפשר לדלג לשלב 7)

אותה תבנית – נוסיף אימות לשלב התשלום.

שלב 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(...)

הגדרה:

מוצאים את השורה הזו בהגדרה של הנציג:

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

מוסיפים את השורה הזו מיד אחרי

description

:

    before_agent_callback=validate_cart_before_payment,

עכשיו הגדרת הנציג אמורה להיראות כך:

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

שלב 7: בדיקה באמצעות ממשק המשתמש של ADK באינטרנט

עכשיו נבדוק את המערכת המאובטחת המלאה עם קריאות חוזרות פעילות לאימות.

👉 בטרמינל של 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 preview (נראה כמו עין או ריבוע עם חץ) בסרגל הכלים של Cloud Shell (בדרך כלל בפינה הימנית העליונה), בוחרים באפשרות Change port. בחלון הקופץ, מגדירים את היציאה ל-8000 ולוחצים על Change and Preview (שינוי ותצוגה מקדימה). בשלב הזה, Cloud Shell יפתח כרטיסייה חדשה בדפדפן שבה יוצג ממשק המשתמש של ADK באינטרנט.

webpreview

👉 בוחרים את הנציג מהתפריט הנפתח:

בממשק האינטרנט של ADK, תפריט נפתח יופיע בחלק העליון. בוחרים באפשרות charity_advisor מהרשימה.

agent-select

ממשק האינטרנט של ADK יופיע עם:

  • חלונית הצ'אט: בצד ימין, לשיחה
  • חלונית המעקב: בצד שמאל, לצורך ניטור (נשתמש בה במודול 9)

בדיקה 1: תהליך תרומה מלא (מקרה רגיל)

👉 בממשק הצ'אט, מקלידים:

I want to donate to an education charity

ככה נראה התהליך המלא:

סוכן שופינג באינטרנט של ADK

צינור עיבוד נתונים של תרומות באינטרנט של adk

מה קורה (מוצג בחלונית המעקב משמאל):

1. היועץ מעביר את הטיפול ל-ShoppingAgent:

  • ‫ShoppingAgent מחפש עמותות בתחום החינוך
  • הצגת 3 אפשרויות מאומתות עם פרטים

2. אתם מקיימים אינטראקציה עם ShoppingAgent (יכול להיות שיידרשו כמה שלבים):

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

3. ‫ShoppingAgent יוצר IntentMandate:

  • יוצר וחותם על ה-intent
  • החזרת אישור עם מזהה Intent

4. היועץ עובר לשלב העיבוד:

יופי! התרומה שלך בסך 50 $ל-Room to Read בתהליך עיבוד...

5. ‫DonationProcessingPipeline מפעיל את:

  • הקריאה החוזרת (callback) של המוכר מאמתת את IntentMandate (✓ עבר) ← חדש!
  • הסוכן של המוכר יוצר CartMandate עם חתימה
  • הקריאה החוזרת (callback) של פרטי הכניסה מאמתת את CartMandate (✓ עבר) ← חדש!
  • ספק פרטי הכניסה מכין את התשלום

6. עיבוד תשלומים:

  • ספק פרטי הכניסה יוצר את PaymentMandate
  • מדמה עיבוד תשלומים
  • מזהה העסקה של ההחזרה

7. היועץ מסכם:

יופי! התרומה שלך עברה בהצלחה. 🎉

פרטים:

  • סכום: 50.00$
  • ארגון הצדקה: Room to Read (מספר EIN‏: 77-0479905)
  • מזהה העסקה: txn_a3f7b2c8d9e1f4a2

בדיקה 2: אימות שהקריאות החוזרות מזהות כשלים (בדיקה מתקדמת אופציונלית)

רוצים לראות איך פונקציות ה-callback תופסות שגיאות בפעולה? תצטרכו להשחית את המצב באופן ידני (ניפוי באגים מתקדם), אבל בסביבת הייצור, פונקציות ה-callback יתפסו את:

  • הכלי "סוכן שופינג" נכשל ← בלוקים של קריאה חוזרת (callback) של המוכר: "שגיאה: לא ניתן ליצור עגלת קניות..."
  • עוברות שעתיים ← הקריאה החוזרת (callback) של המוכר חוסמת: "שגיאה: פג התוקף של ה-Intent…"
  • פג תוקף העגלה ← בלוקים של קריאה חוזרת (callback) של פרטי כניסה: "שגיאה: פג תוקף העגלה (מגבלה של 15 דקות)..."

מקרי הקצה האלה נאכפים עכשיו מבחינה ארכיטקטונית על ידי פונקציות ה-callback לאימות.

מה שיצרתם עכשיו

הצלחתם לתזמר שלושה סוכנים מיוחדים למערכת חלקה ואמינה עם אימות ארכיטקטוני.

המאמרים הבאים

עכשיו השלמתם את החלק הטכני העיקרי של פיתוח סוכנים מהימנים:

בניתם מערכת מהימנה לחלוטין שאוכפת באופן מקומי את שרשרת פרטי הכניסה. עכשיו נהפוך אותו לנגיש למשתמשים אמיתיים באמצעות פריסה בסביבת הייצור, ונפעיל את נתיב האחריות שמאפשר את מודול 9.

עכשיו נטמיע את הסוכן המאובטח ב-Google Cloud.

8. פריסה

באנר

מערכת התרומות האמינה שלכם כוללת עכשיו שלושה סוכנים מיוחדים שפועלים באופן מקומי:

אבל הוא פועל רק במחשב הפיתוח שלכם. כדי שהמערכת הזו תהיה שימושית למשתמשים אמיתיים – וכדי לתעד את נתיבי האחריותיות שמוכיחים אמינות – צריך לפרוס אותה בסביבת הייצור.

במודול הזה נסביר איך לפרוס את הסוכן ב-Google Cloud עם יכולת תצפית מהיום הראשון. הדגל --trace_to_cloud שבו תשתמשו במהלך הפריסה הוא זה שמאפשר את נתיב האחריות במודול 9.

הסבר על אפשרויות הפריסה

ה-ADK תומך בכמה יעדי פריסה. לכל אחת מהן יש מאפיינים שונים מבחינת מורכבות, ניהול סשנים, התאמה לעומס ועלות:

פירוק לגורמים

מקומי (adk web)

Agent Engine

Cloud Run

מורכבות

מינימלי

נמוכה

בינונית

שמירת מצב הסשן

בזיכרון בלבד (הנתונים יאבדו בהפעלה מחדש)

מנוהל על ידי Vertex AI (אוטומטי)

‫Cloud SQL ‏(PostgreSQL) או בזיכרון

תשתית

ללא (מכונת פיתוח בלבד)

מנוהל במלואו

מאגר + מסד נתונים אופציונלי

הפעלה מההתחלה (cold startup)

לא רלוונטי

‫100-500 אלפיות השנייה

‫100 עד 2,000 אלפיות השנייה

שינוי קנה מידה

מופע יחיד

אוטומטי

אוטומטי (לאפס)

מודל עלות

חינם (עיבוד מקומי)

מבוססות-מחשוב

מבוסס-בקשות + תוכנית בחינם

תמיכה בממשק המשתמש

כן (מובנה)

לא (API בלבד)

כן (באמצעות הדגל --with_ui)

הגדרת ניראות

כלי מקומי להצגת נתוני מעקב

אוטומטי עם --trace_to_cloud

נדרש הדגל --trace_to_cloud

מתאים במיוחד עבור

פיתוח ובדיקה

סוכני ייצור

סוכני ייצור

המלצה: כדי ליצור מערכת תרומות מהימנה, מומלץ להשתמש ב-Agent Engine כפריסה הראשית בסביבת הייצור, כי הוא מספק:

  • תשתית מנוהלת (אין קונטיינרים שצריך לנהל)
  • שמירת סשן מובנית באמצעות VertexAiSessionService
  • התאמה אוטומטית לעומס (automatic scaling) בלי הפעלות במצב התחלתי (cold start)
  • פריסה פשוטה (לא נדרש ידע ב-Docker)
  • שילוב מובנה עם Cloud Trace

אפשרות נוספת: Google Kubernetes Engine (GKE)

למשתמשים מתקדמים שצריכים שליטה ברמת Kubernetes, רשתות בהתאמה אישית או תזמור של כמה שירותים, אפשר להשתמש בפריסת GKE. האפשרות הזו מספקת גמישות מקסימלית, אבל דורשת יותר מומחיות תפעולית (ניהול אשכולות, מניפסטים, חשבונות שירות).

הפריסה של GKE לא נכללת ב-Codelab הזה, אבל היא מתועדת במלואה במדריך לפריסת ADK GKE.

דרישות מוקדמות

1. הגדרת פרויקט בענן ב-Google

אתם צריכים פרויקט ב-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, צריך להיות באזור נתמך
  • אם קטגוריית ה-Staging לא קיימת, היא תיווצר באופן אוטומטי כשמריצים את סקריפט הפריסה.

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 – לקטגוריית ה-Staging
  • ‫Cloud Build API – ליצירת קונטיינרים (Cloud Run)
  • ‫Cloud Trace API – לתצפיתיות ולנתיבי ביקורת
  • ‫Compute Engine API – לניהול חשבונות שירות

שלב 1: הסבר על תשתית הפריסה

הפרויקט כולל סקריפט פריסה מאוחד (deploy.sh) שמטפל בכל מצבי הפריסה.

👉 בודקים את סקריפט הפריסה (אופציונלי):

cat deploy.sh

הסקריפט מספק שלושה מצבי פריסה:

  • ‫./deploy.sh local – הפעלה מקומית עם אחסון בזיכרון
  • ‫./deploy.sh agent-engine – פריסה ב-Vertex AI Agent Engine (מומלץ)
  • ‫./deploy.sh cloud-run – פריסה ב-Cloud Run עם ממשק משתמש אופציונלי

איך זה עובד מאחורי הקלעים:

בפריסה של Agent Engine, הסקריפט מריץ את הפעולות הבאות:

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

לפריסה של Cloud Run, הוא מריץ את:

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

הדגל --trace_to_cloud הוא קריטי לשני סוגי הפריסה – הוא מאפשר שילוב של Cloud Trace לנתיב האחריות שתחקרו במודול 9.

שלב 2: הכנת ה-wrapper של Agent Engine

כדי להשתמש ב-Agent Engine, צריך נקודת כניסה ספציפית שעוטפת את הסוכן לסביבת זמן הריצה המנוהלת. הקובץ הזה נוצר בשבילך.

👉 לבדיקה

charity_advisor/agent_engine_app.py

:

"""Agent Engine application wrapper.

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

from vertexai import agent_engines
from .agent import root_agent

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

למה צריך את הקובץ הזה:

  • כדי להשתמש ב-Agent Engine, צריך לעטוף את הסוכן באובייקט AdkApp
  • הפרמטר enable_tracing=True מפעיל את השילוב של Cloud Trace באופן אוטומטי
  • ה-wrapper הזה מקושר ל-CLI של ADK במהלך הפריסה
  • היא מגדירה את 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 דקות כי הוא כולל את אריזת הנציג ופריסה שלו בתשתית של 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 כוללת עכשיו:

‫✅ כל שלושת הסוכנים (קניות, מוכר, פרטי כניסה) פועלים בסביבת זמן ריצה מנוהלת
✅ לוגיקה מלאה של שרשרת פרטי כניסה (Intent → Cart → Payment mandates)
✅ מנגנון הסכמה מהמשתמש עם תהליך עבודה לאישור
✅ שמירה אוטומטית של הסשן באמצעות VertexAiSessionService
✅ תשתית להתאמה אוטומטית לעומס (automatic scaling) שמנוהלת על ידי Google
✅ שילוב של Cloud Trace ליכולת תצפית מלאה

שלב 4: בודקים את הנציג שנפרס

עדכון הסביבה

מוודאים שהקובץ .env כולל את מזהה מנוע הסוכן:

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

רשימת משימות לאימות

אחרי הבדיקה, צריך לוודא:

‫✅ הסוכן מגיב לשאילתות
✅ כל שלושת הסוכנים פועלים ברצף (שופינג ← Merchant ← פרטי כניסה)
✅ מנגנון ההסכמה מופעל (נדרש אישור)
✅ הסשן נמשך בין הבקשות
✅ אין שגיאות אימות
✅ אין זמן קצוב לתפוגה של החיבור

אם נתקלים בשגיאות:

  • מוודאים שמשתני הסביבה מוגדרים בצורה נכונה
  • מוודאים שממשקי ה-API מופעלים: gcloud services list --enabled
  • בודקים את היומנים של Agent Engine במסוף Vertex AI.
  • מוודאים שהקובץ agent_engine_app.py נמצא בתיקייה charity_advisor

שלב 5: פריסה ב-Cloud Run (אופציונלי)

מומלץ להשתמש ב-Agent Engine לפריסה יעילה בסביבת הייצור, אבל Cloud Run מציע יותר שליטה ותומך בממשק המשתמש של ADK באינטרנט. הקטע הזה הוא אופציונלי.

מתי כדאי להשתמש ב-Cloud Run

בחרו ב-Cloud Run אם אתם צריכים:

  • ממשק המשתמש של ADK באינטרנט לאינטראקציה עם המשתמשים
  • שליטה מלאה בסביבת הקונטיינר
  • הגדרות של מסד נתונים בהתאמה אישית
  • שילוב עם שירותי Cloud Run קיימים

הרצת הפריסה

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

מה ההבדל:

הסקריפט יבצע באופן אוטומטי את הפעולות הבאות:

  • יצירת קונטיינר של Docker עם קוד הסוכן
  • יצירת מסד נתונים של Cloud SQL PostgreSQL (אם צריך)
  • הגדרת החיבור למסד הנתונים
  • פריסה עם ממשק המשתמש של ADK באינטרנט מופעל

הפריסה נמשכת 10-15 דקות בגלל הקצאת המשאבים של Cloud SQL.

ניהול סשנים:

  • שימוש ב-DatabaseSessionService במקום ב-VertexAiSessionService
  • נדרשים פרטי כניסה למסד הנתונים ב-.env (או שנוצרים באופן אוטומטי)
  • המצב נשמר במסד הנתונים של PostgreSQL

תמיכה בממשק המשתמש:

  • ממשק המשתמש באינטרנט זמין בכתובת: https://charity-advisor-xyz.a.run.app

בדיקת הפריסה של Cloud Run

אם פרסתם ב-Cloud Run באמצעות --with_ui, אתם יכולים לבדוק ישירות בדפדפן:

  1. עוברים לכתובת ה-URL של השירות (שמופיעה בפלט של הפריסה).
  2. ממשק האינטרנט של ADK יופיע. בוחרים את הנציג מהתפריט הנפתח.
  3. כדי להתחיל תרומה לבדיקה:
   I want to donate $50 to a children's education charity
  1. צופים בתהליך ההפעלה:
    • ‫ShoppingAgent מוצא עמותות ושומר את הכוונה שלכם
    • ‫MerchantAgent יוצר את ייפוי הכוח לעגלת הקניות
    • ‫CredentialsProvider יוצר הרשאת תשלום ומבקש אישור
    • אחרי האישור, התשלום יעובד
  2. מוודאים שהתשובה כוללת:
    • המלצות על ארגוני צדקה
    • בקשת אישור
    • הודעת הצלחה אחרי אישור

פתרון בעיות

בעיות נפוצות

הבעיה: ERROR: GOOGLE_CLOUD_PROJECT is not set

הפתרון: מוודאים שבקובץ .env יש את מזהה הפרויקט הנכון:

GOOGLE_CLOUD_PROJECT=your-actual-project-id

הבעיה: קטגוריית ה-Staging לא נוצרה באופן אוטומטי

פתרון: הסקריפט אמור ליצור את הקטגוריה באופן אוטומטי. אם לא, יוצרים אותו באופן ידני:

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. ניראות (observability)

באנר

מעקב אחר תרשים

במודול 1 למדתם על בעיה בסיסית: כשסוכן AI מטפל בכסף, איך מוכיחים מה קרה?

משתמש יכול לטעון:

  • "אף פעם לא בחרתי בעמותה הזו!"
  • "לא אישרתי את התשלום הזה!"
  • "המערכת חייבה אותי בלי הסכמתי!"

במערכת AI מסורתית של קופסה שחורה, לא הייתה לכם דרך להוכיח אחרת. אבל מערכת התרומות האמינה שלכם שונה. במודול 8, פרסתם את האפליקציה עם הדגל --trace_to_cloud, מה שאומר שכל תרומה יוצרת עכשיו נתיב ביקורת מלא שמעיד על שינויים ב-Cloud Trace.

במודול הזה תלמדו איך לקרוא את העקבות האלה ולהשתמש בהם כראיות. נלמד אותך:

  • לנווט ב-Cloud Trace Explorer כדי למצוא מעקבים בסביבת הייצור
  • איך לקרוא את תצוגת ה-Waterfall כדי להבין את תהליך ההרצה
  • מאתרים את שרשרת פרטי הכניסה (כוונה ← עגלת קניות ← הרשאות תשלום)
  • איתור רגעי ההסכמה באמצעות הוכחה של חותמת זמן
  • שימוש במעקבים ליישוב סכסוכים
  • ייצוא של נתוני מעקב לצורכי תאימות וביקורת

זה מה שמבדיל בין מערכות מהימנות לבין מערכות יעילות אבל לא שקופות: היכולת להוכיח מה קרה בדיוק.

הסבר על מעקבים וטווחים

לפני שאתם צופים במעקבים ב-Cloud Trace, חשוב שתבינו מה אתם רואים.

מה זה Trace?

מעקב הוא ציר הזמן המלא של הטיפול של הנציג בבקשה אחת. הוא מתעד את כל מה שקורה מרגע שהמשתמש שולח שאילתה ועד שהתשובה הסופית מתקבלת.

כל מעקב מציג:

  • משך הזמן הכולל של הבקשה
  • כל הפעולות שבוצעו
  • איך הפעולות קשורות זו לזו (קשרי הורה-צאצא)
  • מתי כל פעולה התחילה והסתיימה
  • סטטוס הצלחה או כישלון

לסוכן הצדקה: מעקב אחד = תהליך תרומה שלם אחד, מ "אני רוצה לתרום" ועד "התשלום בוצע בהצלחה".

מה זה Span?

span מייצג יחידת עבודה אחת בתוך מעקב. אפשר לחשוב על טווחים כעל אבני הבניין של מעקב.

סוגי ספאם נפוצים במערכת התרומות:

סוג הטווח

מה הוא מייצג

דוגמה

agent_run

הפעלה של סוכן

ShoppingAgent.run, MerchantAgent.run

call_llm

בקשה למודל שפה

בקשה של gemini-2.5-flash לבחירת עמותה

execute_tool

הפעלת פונקציות של כלים

find_charities, create_payment_mandate

state_read

קריאה מזיכרון הסשן

מתבצע אחזור של intent_mandate מהמצב

state_write

כתיבה בזיכרון של הסשן

שמירת cart_mandate במצב

כל span מכיל:

  • שם: הפעולה שהשורה מייצגת
  • כמה זמן זה לקח (שעת התחלה ← שעת סיום)
  • מאפיינים: מטא-נתונים כמו קלט של כלים, תשובות של המודל, ספירת טוקנים
  • סטטוס: הצלחה (OK) או שגיאה (ERROR)
  • קשרי הורה-צאצא: אילו פעולות הפעילו פעולות אחרות

איך טווחים יוצרים מעקב

הטווחים מקוננים זה בתוך זה כדי להראות סיבתיות:

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

ההיררכיה הזו מראה בדיוק מה קרה ובאיזה סדר. אפשר לראות שהרשאת התשלום נוצרה אחרי הרשאת עגלת הקניות, שנוצרה אחרי שהמשתמש בחר עמותה.

שלב 1: פתיחת Cloud Trace Explorer

עכשיו נראה את המעקבים בפועל מהסוכן שנפרס.

  1. פותחים את מסוף Google Cloud: console.cloud.google.com
  2. בוחרים את הפרויקט בתפריט הנפתח שבחלק העליון (הוא אמור להיות כבר מסומן אם עבדתם בו).
  3. עוברים אל Cloud Trace Explorer:

מה אתם רואים

ב-Trace Explorer מוצגת רשימה של כל המעקבים מהפרויקט:

עמודה

מה מוצג

בקשה

שיטת ה-HTTP ונקודת הקצה (לבקשות API)

שעת ההתחלה

מתי הבקשה התחילה

זמן אחזור

משך הזמן הכולל של הבקשה

טווחים

מספר הפעולות במעקב

כל שורה מייצגת בקשה אחת מלאה לנציג שפרסתם.

יצירת מעקבים לבדיקה (אם צריך)

אם עדיין לא מופיעים מעקבים, יכול להיות שהרשימה ריקה כי:

  • עדיין לא נשלחו בקשות לנציג שפרסתם
  • המעקבים מופיעים תוך דקה או שתיים אחרי הבקשה

יצירת מעקב לבדיקה:

אם פרסתם ב-Cloud Run באמצעות ממשק המשתמש, היכנסו לכתובת ה-URL של השירות והשלימו תרומה בדפדפן.

אם פרסתם ב-Agent Engine, הריצו את סקריפט הבדיקה מיחידת לימוד 8:

python scripts/test_deployed_agent.py

ממתינים דקה או שתיים ומרעננים את הדף Cloud Trace Explorer. עכשיו אמורים להופיע מעקבים.

סינון המעקבים

כדי למצוא מעקבים ספציפיים, משתמשים באפשרויות הסינון שבחלק העליון:

  • טווח זמן: אם צריך, משנים את האפשרות "השעה האחרונה" ל "24 השעות האחרונות".
  • זמן אחזור מינימלי / זמן אחזור מקסימלי: סינון לפי בקשות איטיות
  • מסנן בקשות: חיפוש לפי פעולות ספציפיות (למשל, "DonationPipeline")

במודול הזה, התמקדו במעקבים עם משכי זמן ארוכים יותר (יותר מ-5 שניות), כי הם מייצגים תהליכי תרומה מלאים שבהם כל שלושת הסוכנים פועלים.

שלב 2: בודקים תהליך תרומה מלא

לוחצים על אחד מהמעקבים ברשימה כדי לפתוח את תצוגת המפל. זה המקום שבו תבלו את רוב הזמן בניתוח ההתנהגות של הנציג.

הסבר על תצוגת 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]

קריאת התרשים

כל עמודה מייצגת span:

  • מיקום אופקי: מתי הוא התחיל
  • משך: כמה זמן נמשכה הפעילות
  • כניסת פסקה: מציגה את יחסי ההיררכיה
  • צבע: בדרך כלל כחול למצב רגיל, אדום לשגיאות

תצפיות מרכזיות מהמעקב לדוגמה:

‫✅ משך זמן כולל: 8.2 שניות
✅ ביצוע רציף: ShoppingAgent סיים את הפעולה לפני ש-MerchantAgent התחיל
✅ ‫MerchantAgent סיים את הפעולה

לפני

CredentialsProvider started
✅ Consent was the longest operation: 3.0 seconds for create_payment_mandate (because it waited for user confirmation)
✅ LLM calls are visible: Each agent made one Gemini request
✅ Tool calls are captured: All six tools executed successfully

התצוגה החזותית הזו מראה מיד איפה הושקע זמן ובאיזה סדר בוצעו הפעולות.

לחיצה על טווח כדי לראות פרטים

לוחצים על ה-span של invocation (היחידה הלוגית הבסיסית למעקב בחלק העליון). בחלונית השמאלית יופיעו מאפיינים מפורטים:

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

המאפיינים האלה מספקים הקשר לגבי הבקשה כולה.

שלב 3: מאתרים את שרשרת פרטי הכניסה

המערכת המהימנה משתמשת בשרשרת פרטי כניסה כדי להוכיח את ההרשאה בכל שלב:

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

בואו נחפש כל הוראת קבע במעקב.

איך למצוא את IntentMandate

לוחצים על ה-span execute_tool: save_user_choice (מתחת ל-ShoppingAgent).

בחלונית המאפיינים יוצגו:

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

זה מוכיח:

  • ‫✅ המשתמש בחר באפשרות Save the Children
  • ‫✅ הסכום היה 50$
  • ‫✅ הבחירה תועדה בשעה 15:30:12 (זמן אוניברסלי מתואם)
  • ‫✅ החתימה נוצרה (בסביבת הייצור, החתימה תהיה קריפטוגרפית)

ה-IntentMandate נמצא עכשיו במצב סשן וזמין לנציגים הבאים.

איתור ה-CartMandate

לוחצים על ה-span של execute_tool: create_cart_mandate (בקטע MerchantAgent).

בחלונית המאפיינים:

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

זה מוכיח:

  • ‫✅ MerchantAgent קיבל את IntentMandate (הקלט מראה את זה)
  • ✅ נוצרה עגלת קניות עם המזהה "cart_7893"
  • ‫✅ החתימה של עגלת הקניות מפנה לחתימה של IntentMandate (קישור לשרשרת!)
  • ‫✅ נוצר ב-15:30:14 לפי שעון UTC (‏2.4 שניות אחרי הכוונה)

עכשיו CartMandate מפנה אל IntentMandate, וכך נוצרת השרשרת.

איך מוצאים את ה-PaymentMandate

לוחצים על ה-span 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, מחפשים את ה-spans הארוכים ביותר בערימה האנכית. אלה צווארי הבקבוק בביצועים.

מהמעקב לדוגמה שלנו:

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% מהזמן הכולל. למה?

מרחיבים את ה-span של CredentialsProvider:

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

העיכוב של 3.0 שניות הוא צפוי וטוב – זה הזמן שבו המשתמש מתלבט לפני שהוא מאשר. זו לא בעיה בביצועים, אלא הוכחה להסכמה מודעת.

מעקב אחרי העלויות של LLM

לוחצים על קטע call_llm כלשהו כדי לראות את השימוש בטוקנים:

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

אפשר להשתמש בזה כדי:

  • מעקב אחרי העלות לכל בקשה (טוקנים × תמחור המודל)
  • זיהוי הנחיות ארוכות שלא לצורך
  • השוואה בין ביצועי המודלים (Flash לעומת Pro)
  • אופטימיזציה של זמן האחזור לעומת האיכות

חישוב לדוגמה:

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

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

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

התצוגה המפורטת הזו עוזרת לכם לקבל החלטות מבוססות-נתונים לגבי בחירת המודל.

השוואה בין נתוני מעקב שונים

מסננים לפי כמה מעקבים ומשווים בין משכי הזמן:

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

תובנה: רוב ההבדלים נובעים מהזמן שלוקח למשתמשים להחליט, ולא מביצועי המערכת. ההרצה של הסוכן הראשי (ללא הסכמה) נמשכת כ-5 שניות.

זה אומר שהמערכת פועלת בצורה מהימנה.

במערכות ייצור, כדאי להגדיר התראות כדי לזהות בעיות לפני שהמשתמשים מתלוננים.

התראה על שיעורי שגיאות גבוהים

יצירת התראה כשב->5% מהמעקבים יש שגיאות:

  1. עוברים אל Cloud Monitoring.
  2. לוחצים על "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 כדי למצוא נתוני מעקב בסביבת הייצור
✅ לקרוא תצוגות של תרשימי מפל כדי לראות את תהליך ההפעלה המלא
✅ לעקוב אחרי שרשרת פרטי הכניסה דרך IntentMandate‏ ← CartMandate‏ ← PaymentMandate ✅ להשתמש בנתוני מעקב כהוכחה ליישוב סכסוכים
✅ לנתח את הביצועים כדי לזהות צווארי בקבוק
✅ לעקוב אחרי העלויות של מודל ה-LLM ברמה מפורטת

ההבדל שזה יוצר

נשווה בין שתי מערכות שמטפלות באותה תלונה: "אף פעם לא אישרתי את זה!":

מערכת ללא ניראות (observability)

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

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

מערכת עם Cloud Trace

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

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

זה הכוח של נתיבי האחריות. אתם עוברים מ "תסמכו עלינו" ל "בואו נראה לכם בדיוק מה קרה".

המאמרים הבאים

עכשיו השלמתם את החלק הטכני העיקרי של פיתוח סוכנים מהימנים:

✅ מודול 1-6: עיצוב ארכיטקטורה אמינה (תפקידים, אישורים, הסכמה)
✅ מודול 7: תהליכי עבודה מורכבים מתוזמרים (SequentialAgent)
✅ מודול 8: פריסה עם יכולת תצפית מופעלת
✅ מודול 9: לימוד קריאת ושימוש בנתיבים של אחריות

הארכיטקטורה שבניתם – הפרדת תפקידים, שרשראות של פרטי כניסה, מנגנוני הסכמה, יכולת תצפית מלאה – עוברת ישירות למערכות ייצור שמטפלות בכסף אמיתי, בנתונים אמיתיים ובהשלכות אמיתיות.

10. המסע שלך קדימה

מה שבניתם

התחלתם את הסדנה הזו עם שאלה: "איך בונים סוכני AI שאפשר לסמוך עליהם עם כסף?"

עכשיו יש לכם את התשובה.

איפה התחלתם (מודול 3):

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

איפה אתם נמצאים עכשיו (מודול 10):

  • ‫✅ שלושה נציגים ייעודיים עם הפרדת תפקידים
  • ‫✅ שלושה אישורים ניתנים לאימות (כוונה ← עגלת קניות ← הרשאות תשלום)
  • ‫✅ שרשרת פרטי כניסה מלאה עם אימות תפוגה בכל שלב
  • ‫✅ מנגנון הסכמה מפורשת עם הוכחה של חותמת זמן
  • ‫✅ פריסה בסביבת ייצור ב-Agent Engine עם יכולת תצפית
  • ‫✅ מעקב מלא אחרי האחריותיות ב-Cloud Trace
  • ‫✅ ראיות פורנזיות ליישוב סכסוכים

הפער בין הסדנה לייצור

המערכת שלכם מדגימה את הארכיטקטורה והתבניות הנכונות, אבל משתמשת בפישוטים לימודיים שצריך לשדרג כדי להשתמש בכסף אמיתי ובמשתמשים אמיתיים.

הנה פירוט של מה שפישטנו ומה שנדרש כדי לעבור לסביבת הייצור:

רכיב

הטמעה בסדנה

דרישות הפקה

חתימות

גיבובי SHA-256‏ (SIG_abc123) להדגמה

חתימות קריפטוגרפיות אמיתיות באמצעות PKI או JWT עם מפתחות פרטיים

עיבוד תשלומים

החזרות מדומות (הדגל simulation: True)

שילוב עם ממשקי API אמיתיים לתשלומים (Stripe, ‏PayPal, ‏Square)

אימות משתמשים

אמון משתמע (לא נדרשת התחברות)

‫OAuth 2.0,‏ WebAuthn או ניהול סשנים

ניהול סודות

משתני סביבה בקובץ .env

Google Secret Manager או Cloud KMS עם הצפנה

מסד נתונים של ארגוני צדקה

קובץ JSON מדומה עם 9 ארגוני צדקה

שילוב של ממשק API בזמן אמת (IRS Tax Exempt Organization Search, ‏ Charity Navigator API)

טיפול בשגיאות

בלוק try-catch בסיסי עם הודעות שגיאה

לוגיקה לניסיון נוסף עם השהיה מעריכית לפני ניסיון חוזר (exponential backoff), מפסקי זרם, תורים של הודעות שלא נמסרו (dead letter queues)

בדיקות

אימות ידני באמצעות סקריפטים

חבילת מקרים מקיפה לבדיקת יחידה/שילוב/E2E עם CI/CD

שמירת מצב הסשן

בזיכרון (מקומי) או אוטומטי (Agent Engine)

מסד נתונים בסביבת ייצור עם גיבויים ותוכנית התאוששות מאסון (DR)

הגבלת הקצב של יצירת הבקשות

אין (סביבה חינוכית)

הגבלת קצב של יצירת בקשות לכל משתמש, ויסות נתונים (throttling) על סמך כתובת IP, זיהוי ניצול לרעה

תבניות ארכיטקטורה עיקריות שלמדתם

התבניות שלמדתם בסדנה הזו הן תבניות של סביבת ייצור. אל תפקפקו בהם.

הפרדת תפקידים (עיקרון מס' 1 של AP2)

לכל סוכן יש משימה ברורה אחת והוא רואה רק את מה שהוא צריך. אם סוכן אחד נפרץ, התוקף לא יכול לגשת לנתונים של סוכנים אחרים. כך מצטמצם רדיוס הפיצוץ.

מערכות ייצור שמשתמשות בזה: עיבוד תשלומים, תהליכי עבודה של מסמכים, שרשראות אישורים, טפסים עם כמה שלבים עם שערי אימות.

פרטי כניסה שניתנים לאימות (עיקרון מס' 2 של AP2)

לכל פרטי כניסה יש מועד תפוגה, הם מפנים לפרטי הכניסה הקודמים וצריך לאמת אותם לפני השלב הבא. כך נוצרת שרשרת ביקורת שמעידה על שיבוש.

ערך ההפקה: הוכחה מלאה למה שקרה, מתי ובאיזה סדר. חיוני ליישוב סכסוכים ולעמידה בתקנות.

חותמת זמן שמוכיחה שהמשתמש אישר את הפעולה. אי אפשר להתנגד לה.

ערך ייצור: דרישה משפטית לעסקאות פיננסיות. הגנה על המשתמש ועל החברה.

תזמור רציף (תבנית ADK)

אוכף את סדר ההרצה הנכון. מונע דילוג על שלבים. מבטיח שכל נציג יראה את הפלט של הנציג הקודם.

ערך הייצור: מושלם למערכות שבהן האדם שבתהליך מצפה לתוצאות מיידיות. התבנית הזו מתאימה לתהליכי תרומה, תהליכי תשלום ושרשראות אישורים.

ניראות מלאה (OpenTelemetry + Cloud Trace)

כל החלטה, קריאת API לכלי, רגע של הסכמה והעברת פרטי כניסה מתועדים באופן אוטומטי.

ערך ההפקה: ראיות פורנזיות למחלוקות. נתוני אופטימיזציה של הביצועים. נתיבי ביקורת של תאימות. ניפוי באגים מדויק של בעיות בסביבת הייצור.

מקורות מידע להמשך הלמידה

מסמכי תיעוד של ADK:

‫AP2 ותקנים קשורים:

שירותי Google Cloud:

משאבים לניקוי

כדי להימנע מחיובים שוטפים, צריך למחוק את הפריסה:

‫Agent Engine: פועלים לפי השלבים במסמכי התיעוד של Agent Engine.

‫Cloud Run (אם נפרס):

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

קטגוריות אחסון:

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

המסע שלך ממשיך

התחלתם עם שאלה פשוטה וקיבלתם תשובה מלאה. למדתם את התבניות הבסיסיות ליצירת סוכני AI מהימנים. הדפוסים האלה רלוונטיים לכל תחום שבו סוכני AI מטפלים בפעולות רגישות – עסקאות פיננסיות, החלטות בתחום הבריאות, מסמכים משפטיים, פעולות בשרשרת האספקה.

העקרונות עוברים. מודל האמון עובד.

עכשיו אתם יכולים ליצור משהו מהימן! ❤️

באנר