1. بناء الثقة لتعزيز الكرم

لحظة الإلهام
يهتزّ هاتفك. ترى خبرًا عن برنامج ناجح لمحو الأمية يساعد الأطفال في المجتمعات المحرومة على تعلم القراءة. تشعر برغبة قوية في المساهمة. تفتح المتصفّح وتبحث عن "تبرّعات لبرنامج محو الأمية لدى الأطفال".

تظهر مئات النتائج.
تنقر على الرابط الأول. يظهر الموقع الإلكتروني بشكل احترافي. تنتقل إلى أسفل الصفحة للاطّلاع على بياناتها المالية. "التكاليف الإدارية: %28". توقّفت مؤقتًا. 72 سنتًا فقط من كل دولار تتبرّع به سيتم تخصيصها لتمويل البرنامج. هل هذا جيد؟ لست متأكدًا.
تجربة مؤسسة أخرى لم تسمع عنها من قبل. هل هي شرعية؟ يؤدي البحث السريع إلى متاهة من المعلومات. تعثر على سلسلة رسائل على Reddit من عامين حيث يدعي أحد المستخدمين، "إنها عملية احتيال، لم يذهب تبرعي إلى أي مكان". ويدافع عنها شخص آخر بحماس قائلاً: "إنّها تعمل على أرض الواقع". الغموض يشل الحركة.
بعد ثلاثين دقيقة، تجد نفسك غارقًا في متاهة من المراجعات المتضاربة وتقييمات الكفاءة وسجلات دائرة الإيرادات الداخلية الأمريكية، ولم تتبرّع بعد. فقد تم استبدال الشرارة الأولية للكرم باحتكاك البحث. تبقى علامة التبويب مفتوحة لبضعة أيام، كتذكير بسيط بنية حسنة، إلى أن تغلقها في النهاية.
هذا ليس فشلاً شخصيًا، بل هو فشل في النظام
هذه التجربة عالمية. الرغبة في العطاء وفيرة، لكن العملية مليئة بالعقبات التي تسبب التردد والشك:
- ❌ صعوبة البحث: تتطلّب كل مؤسسة خيرية إجراء بحث خاص بها.
- ❌ التحقّق من الموثوقية: من الصعب التمييز بين المؤسسات الفعّالة للغاية والمؤسسات غير الفعّالة أو حتى عمليات الاحتيال الصريحة.
- ❌ شلل التحليل: يؤدي العدد الهائل من الخيارات إلى الإرهاق الناتج عن اتّخاذ القرارات.
- ❌ فقدان الزخم: يتلاشى الدافع العاطفي للعطاء مع تزايد العبء اللوجستي.
وهذا الاحتكاك له تكلفة مذهلة في العالم الحقيقي. وفقًا لتقرير Giving USA 2024، فإنّ التبرعات الفردية في الولايات المتحدة هائلة، حيث قدّم المتبرعون الأفراد ما يقرب من 374 مليار دولار أمريكي في عام 2023 وحده. ومع ذلك، تُظهر الأبحاث أنّ العوائق التي تحول دون التبرّع، بما في ذلك تكاليف البحث والضغوط النفسية والقيود الزمنية، تقلّل بشكل كبير من المبالغ التي تصل إلى القضايا الخيرية. أظهرت دراسات شملت ملايين المتبرّعين أنّ حتى العقبات الصغيرة في عملية التبرّع على الإنترنت تمنع الأشخاص من تحقيق نواياهم الخيرية.
يمثّل ذلك مليارات الدولارات من التبرّعات المقصودة التي لا تصل أبدًا إلى القضايا التي تحتاج إليها.
The Vision
تخيَّل تجربة مختلفة. بدلاً من جلسة بحث مدتها 30 دقيقة، يمكنك ببساطة قول:
"أريد التبرّع بمبلغ 50 دولار أمريكي لبرنامج محو الأمية للأطفال. ابحث لي عن مؤسسة خيرية معتمَدة وفعّالة وحاصلة على تقييم عالٍ".
وفي غضون ثوانٍ، ستحصل على ردّ يعزّز ثقتك:
هذا هو الوعد الذي يقدّمه وكيل الذكاء الاصطناعي للعطاء. ولتحقيق هذه الرؤية، علينا حلّ مشكلة أساسية: عندما يتعامل وكيل ذكاء اصطناعي مستقل مع الأموال، لا تكون الثقة خيارًا، بل هي الأساس بأكمله.
- كيف يمكننا إثبات ما سمح به المستخدم؟
- من المسؤول في حال حدوث خطأ؟
- كيف يمكننا منح المتبرّعين والمؤسسات الخيرية وشبكات الدفع الثقة للمشاركة؟
مهمتك اليوم
في ورشة العمل هذه، ستنشئ هذا الوكيل الموثوق به من خلال الجمع بين تقنيتَين فعّالتَين:
حزمة تطوير الوكلاء (ADK) من Google | بروتوكول Agent Payments Protocol (AP2) | |
Role | مصنع لإنشاء وكلاء ذكاء اصطناعي جاهزين للاستخدام | المخطط المعماري لتعزيز الثقة في معاملات الذكاء الاصطناعي |
ما يوفّره | • إطار عمل لتنسيق عمل الوكلاء المتعدّدين | • حدود الأمان المستندة إلى الأدوار |
مزيد من المعلومات |
ما ستقوم بإنشائه
بنهاية ورشة العمل هذه، ستكون قد أنشأت:
✅ نظام متعدد الوكلاء بأدوار متخصّصة:
- وكيل تسوّق يعثر على مؤسسات خيرية تم التحقّق منها
- وكيل تاجر ينشئ عروض تبرّعات ملزمة
- مقدّم بيانات اعتماد يعالج الدفعات بأمان
- منسِّق ينظّم العملية بأكملها
✅ ثلاثة أنواع من بيانات الاعتماد القابلة للتحقّق:
- IntentMandate: "أريد العثور على مؤسسة خيرية تعليمية"
- CartMandate: "$50 to Room to Read, signed by merchant"
- PaymentMandate: "Process via simulated payment"
✅ الأمان على جميع المستويات:
- حدود الثقة المستندة إلى الأدوار
- موافقة المستخدم الصريحة
✅ مسار تدقيق كامل:
- كل قرار يمكن تتبُّعه
- كل موافقة يتم تسجيلها
- كل عملية تسليم مرئية
🔒 ملاحظة مهمة: هذه بيئة تعلُّم آمنة
هل أنت مستعد لكسب ثقة العملاء؟
في الوحدة التالية، سنُعدّ بيئة التطوير وننشئ أول وكيل ذكاء اصطناعي. ستكتشف بسرعة سبب عدم موثوقية الوكلاء البسيطين، ثم ستقضي بقية ورشة العمل في تعلُّم كيفية حلّ هذه المشكلة.
لنبدأ بفهم المشكلة بشكل مباشر.
2. جارٍ إعداد مساحة العمل
أساس الوكلاء الموثوقين
قبل أن نتمكّن من إنشاء وكيل AI Giving Agent، علينا إعداد بيئة تطوير نظيفة ومتّسقة ومُعدّة بشكل صحيح. هذه الوحدة هي خطوة مركّزة لضمان توفّر جميع الأدوات والخدمات اللازمة.
يعني إكمال هذا الإعداد بنجاح أنّه يمكنك التركيز بالكامل على العمل الممتع المتمثّل في إنشاء منطق الوكيل في الوحدات القادمة، بدون القلق بشأن مشاكل الإعداد.
الوصول إلى Cloud Shell
أولاً، سنفتح Cloud Shell، وهي وحدة طرفية مستندة إلى المتصفّح ومثبَّتة مسبقًا مع حزمة تطوير البرامج (SDK) في Google Cloud وأدوات أساسية أخرى.
انقر على تفعيل Cloud Shell في أعلى Google Cloud Console (وهو رمز الوحدة الطرفية في شريط التنقّل في أعلى يسار الصفحة).

للعثور على رقم تعريف مشروعك على Google Cloud، اتّبِع الخطوات التالية:
- افتح Google Cloud Console: https://console.cloud.google.com
- اختَر المشروع الذي تريد استخدامه في ورشة العمل هذه من القائمة المنسدلة للمشاريع في أعلى الصفحة.
- يظهر رقم تعريف مشروعك في بطاقة "معلومات المشروع" على لوحة البيانات

بعد فتح Cloud Shell، تأكَّد من مصادقة هويتك:
# Check that you are logged in
gcloud auth list
من المفترض أن يظهر حسابك على أنّه (ACTIVE).
إعداد مشروعك
لنبدأ الآن بإعداد مشروعك على Google Cloud وتفعيل واجهات برمجة التطبيقات اللازمة.
ضبط رقم تعريف المشروع
# 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)"
تفعيل واجهات برمجة التطبيقات المطلوبة
يحتاج الوكلاء إلى الوصول إلى العديد من خدمات Google Cloud:
gcloud services enable \
aiplatform.googleapis.com \
secretmanager.googleapis.com \
cloudtrace.googleapis.com
قد يستغرق هذا من دقيقة إلى دقيقتين. وسترى ما يلي:
Operation "operations/..." finished successfully.
ما توفّره واجهات برمجة التطبيقات هذه:
- aiplatform.googleapis.com: للوصول إلى نماذج Gemini من أجل استدلال الوكيل
- secretmanager.googleapis.com: مساحة تخزين آمنة لمفاتيح واجهة برمجة التطبيقات (أفضل ممارسة في مرحلة الإنتاج)
- cloudtrace.googleapis.com: إمكانية تتبّع البيانات لمسار المساءلة
استنساخ الرمز الأوّلي
احصل على مستودع ورشة العمل الذي يتضمّن جميع رموز النماذج والموارد:
git clone https://github.com/ayoisio/adk-ap2-charity-agents
cd adk-ap2-charity-agents
git checkout codelab
لنتحقّق مما لدينا:
ls -la
من المفترض أن يظهر لك ما يلي:
charity_advisor/- حيث سننشئ الوكلاء والأدواتscripts/- نصوص برمجية مساعدة للاختبار والتحقّقdeploy.sh- نص برمجي مساعد للنشر-
setup.py: نص برمجي مساعد لتثبيت الوحدة .env.template- ملف متغيرات البيئة
إعداد بيئة Python
سننشئ الآن بيئة Python معزولة لمشروعنا.
إنشاء بيئة افتراضية وتفعيلها
# Create the virtual environment
python3 -m venv venv
# Activate it
source venv/bin/activate
✅ التحقّق: من المفترض أن يظهر الآن في الطلب البادئة (venv).
تثبيت التبعيات
pip install -r charity_advisor/requirements.txt
pip install -e .
يؤدي ذلك إلى تثبيت ما يلي:
- google-adk: إطار عمل Agent Development Kit
- google-cloud-aiplatform: دمج Vertex AI وGemini
- ap2: حزمة تطوير البرامج (SDK) لبروتوكول Agent Payments (من 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
- ✅ واجهات برمجة التطبيقات المطلوبة مفعَّلة
- ✅ تم تثبيت مكتبتَي ADK وAP2
- ✅ رمز النموذج جاهز للتعديل
في الوحدة التالية، ستنشئ أول وكيل ذكاء اصطناعي باستخدام بضعة أسطر من الرموز البرمجية وستكتشف سبب عدم موثوقية الوكلاء البسيطين عند التعامل مع المعاملات المالية.
3- وكيلك الأول واكتشاف فجوة الثقة

من الفكرة إلى التفاعل
في الوحدة السابقة، أعددنا بيئة التطوير. الآن، يبدأ العمل المثير. سننشئ أول وكيل لنا ونشغّله ونمنحه أولى إمكاناته، وبذلك سنكتشف التحديات الأساسية التي يجب حلّها لجعله جديرًا بالثقة.
هذه الوحدة هي الصورة "قبل"، أي اللحظة التي تكشف عن سبب حاجة إنشاء وكلاء موثوقين إلى أكثر من مجرد منح نموذج لغوي كبير إمكانية الوصول إلى الأدوات.
الخطوة 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: كتابة تعليمات الوكيل
التعليمات هي "الوصف الوظيفي" للوكيل، فهي تخبر النموذج اللغوي الكبير متى وكيف يستخدم أدواته. لنكتب تعليمات توجّه الوكيل للبحث عن معلومات حول المؤسسات الخيرية.
👉 البحث:
# 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: التحقّق من الوكيل الكامل
لنتأكّد من أنّ كل شيء جاهز قبل إجراء الاختبار.
👉 Your complete
charity_advisor/simple_agent/agent.py
من المفترض أن يظهر الملف الآن على النحو التالي:
"""
A simple agent that can research charities using Google Search.
"""
from google.adk.agents import Agent
from google.adk.tools import google_search
simple_agent = Agent(
name="SimpleAgent",
model="gemini-2.5-flash",
instruction="""You are a helpful research assistant. When a user asks you to find information about charities,
use the google_search tool to find the most relevant and up-to-date results from the web.
Synthesize the search results into a helpful summary.""",
tools=[google_search]
)
الخطوة 6: اختبار الوكيل - الكشف عن ثغرات الثقة
بعد الانتهاء من ضبط إعدادات الوكيل بالكامل، لنختبره ونحلّل سلوكه. هنا نكتشف سبب عدم موثوقية الوكلاء البسيطين عند التعامل مع القرارات المالية.
الاختبار 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
للخروج عند الانتهاء من الاختبار.
تمثيل الفجوتَين بيانيًا
ما تعلمته للتو
في هذه الوحدة، نجحت في إنشاء أول وكيل ذكاء اصطناعي وتجهيزه. وبذلك، تكون قد كشفت عن التحديين الأساسيين لبناء نظام جدير بالثقة.
المفاهيم الرئيسية التي تم إتقانها
✅ فئة الوكيل:
- المكوّن الأساسي في ADK
- يجمع بين استدلال النموذج اللغوي الكبير (العقل) والأدوات (اليدين)
- تم ضبطه باستخدام النموذج والتعليمات والأدوات
✅ البنية المستندة إلى المجلدات:
- يتم حفظ كل وكيل في مجلده الخاص
- يبحث ADK عن
agent_folder/agent.py - الجري مع
adk run agent_folder
✅ قائمة الأدوات:
- تحديد إمكانات بالذكاء الاصطناعي الوكيل
- يحدّد النموذج اللغوي الكبير متى وكيف يستخدم الأدوات
- يمكن أن تحتوي على أدوات متعددة لإجراءات مختلفة
✅ الطلب الإرشادي:
- توجّه سلوك الوكيل مثل الوصف الوظيفي
- تحدّد الدور والمشغّلات والإجراءات وتنسيق الناتج
- مهمة لاستخدام الأدوات بشكل موثوق
✅ مشكلة الثقة:
- فجوة في الاكتشاف: مصادر غير موثوقة وجودة متفاوتة
- فجوة التنفيذ: لا تتوفّر إمكانات آمنة أو موافقة أو سجلّ تدقيق
الخطوات التالية
في الوحدة التالية، سنبدأ في إنشاء الحل من خلال تنفيذ بنية AP2 المستندة إلى الأدوار.
لننشئ الوكيل الأول ونرى كيف يتم فصل الأدوار.
4. إنشاء "وكيل التسوّق" - الاستكشاف المستند إلى الأدوار

أساس الثقة: الفصل بين الأدوار
في الوحدة الأخيرة، اكتشفت أنّ الوكيل البسيط والعام يفشل في جبهتَين: لا يمكنه توفير عملية استكشاف موثوقة، ولا يمكنه تنفيذ معاملات آمنة. سنبدأ الآن في حلّ هذه المشاكل من خلال تنفيذ المبدأ الأول من "بروتوكول دفعات الوكلاء": البنية المستندة إلى الأدوار.
قبل كتابة أي رمز، لنتعرّف على أهمية هذا المبدأ.
مبدأ AP2: فصل الأدوار
مشكلة الوكلاء الذين "ينفّذون كل المهام"
تخيّل أنّك توظّف شخصًا واحدًا ليكون مستشارك المالي ومحاسبك ووسيطك الاستثماري. هل هو مناسب؟ نعم. هل هو آمن؟ قطعًا لا وستكون لديهم:
- أهدافك الاستثمارية (دور المستشار)
- الوصول إلى حساباتك (دور المحاسب)
- تفويض بنقل أموالك (دور الوسيط)
إذا تم اختراق هذا الشخص أو ارتكب خطأ، فكل شيء في خطر.
حلّ AP2: وكيل واحد، مهمة واحدة
يطبّق AP2 مبدأ فصل الاهتمامات لإنشاء حدود الثقة:
أهمية ذلك:
- ✅ نطاق تأثير محدود: في حال اختراق Shopping Agent، لن يتمكّن المهاجم من الوصول إلى بيانات اعتماد الدفع
- ✅ الخصوصية: لا يطّلع مزوّد بيانات الاعتماد على محادثة التسوّق
- ✅ الامتثال: يسهُل استيفاء متطلبات معيار أمان بيانات قطاع بطاقات الدفع (PCI-DSS) عند عزل بيانات الدفع
- ✅ المساءلة: تحديد المسؤولية بوضوح لكل خطوة
كيفية تواصل الوكلاء: الحالة كدفتر ملاحظات مشترك
بما أنّ الوكلاء لا يمكنهم الوصول مباشرةً إلى بيانات بعضهم البعض، فإنّهم يتواصلون من خلال الحالة المشتركة. يمكنك اعتباره لوح معلومات يمكن لجميع الوكلاء الكتابة عليه والقراءة منه:
# Shopping Agent writes:
state["intent_mandate"] = {
"natural_language_description": "Donate $50 to Room to Read",
"merchants": ["Room to Read"],
"intent_expiry": "2024-11-07T15:32:16Z",
"amount": 50.0
}
# Merchant Agent reads:
intent = state["intent_mandate"]
charity_name = intent["merchants"][0]
amount = intent["amount"]
# Creates CartMandate based on IntentMandate...
# Credentials Provider reads:
cart_mandate = state["cart_mandate"]
# Processes payment...
هذه هي الطريقة التي نحافظ بها على حدود الثقة مع إتاحة التعاون.
وكيلنا الأول: "وكيل التسوّق"
تكون مسؤولية "وكيل التسوّق" بسيطة ومحدّدة:
- استخدِم أداة
find_charitiesللاستعلام عن قاعدة بياناتنا الموثوقة - عرض الخيارات للمستخدم
- استخدِم أداة
save_user_choiceلإنشاء IntentMandate وحفظه في الحالة - التسليم إلى الوكيل التالي (التاجر)
انتهيت! لا حاجة إلى معالجة الدفعات أو إنشاء سلة تسوّق، بل يكفي استكشاف المنتجات وتسليمها.
لننشئها خطوة بخطوة.
الخطوة 1: إضافة مساعد التحقّق من صحة الإدخال
عند إنشاء أدوات الإنتاج، يُعدّ التحقّق من صحة الإدخال أمرًا بالغ الأهمية. لننشئ دالة مساعِدة تتحقّق من صحة بيانات المؤسسة الخيرية قبل حفظها في الحالة.
👉 فتح
charity_advisor/tools/charity_tools.py
ستظهر لك دالة find_charities (مكتملة) في أعلى الصفحة. انتقِل للأسفل للعثور على:
# MODULE_4_STEP_1_ADD_VALIDATION_HELPER
👉 استبدِل هذا السطر الواحد بما يلي:
def _validate_charity_data(charity_name: str, charity_ein: str, amount: float) -> tuple[bool, str]:
"""
Validates charity selection data before saving to state.
This helper function performs basic validation to ensure data quality
before it gets passed to other agents in the pipeline.
Args:
charity_name: Name of the selected charity
charity_ein: Employer Identification Number (should be format: XX-XXXXXXX)
amount: Donation amount in USD
Returns:
(is_valid, error_message): Tuple where is_valid is True if all checks pass,
and error_message contains details if validation fails
"""
# Validate charity name
if not charity_name or not charity_name.strip():
return False, "Charity name cannot be empty"
# Validate EIN format (should be XX-XXXXXXX)
if not charity_ein or len(charity_ein) != 10 or charity_ein[2] != '-':
return False, f"Invalid EIN format: {charity_ein}. Expected format: XX-XXXXXXX"
# Validate amount
if amount <= 0:
return False, f"Donation amount must be positive, got: ${amount}"
if amount > 1_000_000:
return False, f"Donation amount exceeds maximum of $1,000,000: ${amount}"
# All checks passed
return True, ""
الخطوة 2: إضافة IntentMandate Creation Helper
لننشئ الآن المساعد الذي ينشئ بنية IntentMandate في AP2. هذا أحد بيانات الاعتماد الثلاثة القابلة للتحقّق في 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: إنشاء أداة State Handoff Tool باستخدام IntentMandate
لننشئ الآن الأداة التي تنشئ IntentMandate وتحفظها في الحالة.
👉 في الملف نفسه، انتقِل للأسفل إلى
save_user_choice
. البحث:
# MODULE_4_STEP_3_COMPLETE_SAVE_TOOL
👉 استبدِل هذا السطر الواحد بما يلي:
# Validate inputs before creating IntentMandate
is_valid, error_message = _validate_charity_data(charity_name, charity_ein, amount)
if not is_valid:
logger.error(f"Validation failed: {error_message}")
return {"status": "error", "message": error_message}
# Create AP2 IntentMandate using our updated helper function
intent_mandate = _create_intent_mandate(charity_name, charity_ein, amount)
# Write the IntentMandate to shared state for the next agent
tool_context.state["intent_mandate"] = intent_mandate
logger.info(f"Successfully created IntentMandate and saved to state")
logger.info(f"Intent ID: {intent_mandate['intent_id']}")
logger.info(f"Intent expires: {intent_mandate['intent_expiry']}")
# Return success confirmation
return {
"status": "success",
"message": f"Created IntentMandate: ${amount:.2f} donation to {charity_name} (EIN: {charity_ein})",
"intent_id": intent_mandate["intent_id"],
"expiry": intent_mandate["intent_expiry"]
}
الخطوة 4: إضافة Display Formatting Helper
قبل إنشاء الوكيل، لنضِف دالة مساعدة أخرى تنسّق بيانات المؤسسات الخيرية لعرضها بطريقة سهلة الاستخدام.
👉 انتقِل إلى الأسفل للعثور على:
# 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: التحقّق من الوكيل الكامل
لنتأكّد من أنّ كل شيء متصل بشكل صحيح.
👉 Your complete
charity_advisor/shopping_agent/agent.py
يجب أن يظهر الآن على النحو التالي:
"""
Shopping Agent - Finds charities from a trusted database and saves the user's choice.
This agent acts as our specialized "Research Analyst."
"""
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.charity_tools import find_charities, save_user_choice
shopping_agent = Agent(
name="ShoppingAgent",
model="gemini-2.5-pro",
description="Finds and recommends vetted charities from a trusted database, then creates an IntentMandate capturing the user's donation intent.",
instruction="""You are a research specialist helping users find verified charities.
Your workflow:
1. When the user describes what cause they want to support (e.g., "education", "health", "environment"),
use the find_charities tool to search our vetted database.
2. Present the results clearly. The tool returns formatted charity information that you should
show to the user.
3. When the user selects a charity and specifies an amount, use the save_user_choice tool
to create an IntentMandate and record their decision. You MUST call save_user_choice with:
- charity_name: The exact name of the chosen charity
- charity_ein: The EIN of the chosen charity
- amount: The donation amount in dollars (as a number, not a string)
4. After successfully saving, inform the user:
- That you've created an IntentMandate (mention the intent ID if provided)
- When the intent expires
- That you're passing their request to the secure payment processor
IMPORTANT BOUNDARIES:
- Your ONLY job is discovery and creating the IntentMandate
- You do NOT process payments
- You do NOT see the user's payment methods
- You do NOT create cart offers (that's the Merchant Agent's job)
- After calling save_user_choice, your work is done
WHAT IS AN INTENTMANDATE:
An IntentMandate is a structured record of what the user wants to do. It includes:
- Natural language description ("Donate $50 to Room to Read")
- Which merchants can fulfill it
- When the intent expires
- Whether user confirmation is required
This is the first of three verifiable credentials in our secure payment system.
If the user asks you to do anything related to payment processing, politely explain that
you don't have that capability and that their request will be handled by the appropriate
specialist agent.""",
tools=[
FunctionTool(func=find_charities),
FunctionTool(func=save_user_choice)
]
)
✅ ممتاز. لقد أنشأت وكيلًا متوافقًا مع AP2 بجودة إنتاجية عالية يتضمّن ما يلي:
- التحقّق من صحة البيانات المدخَلة
- إنشاء IntentMandate بشكل صحيح باستخدام نماذج AP2 Pydantic
- الناتج المنسَّق
- حدود واضحة للأدوار
- التعليمات التفصيلية
- معالجة الأخطاء
الخطوة 9: اختبار Shopping Agent
لنتأكّد من أنّ الوكيل يعمل بشكل صحيح، وينشئ تفويضات 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 (رقم تعريف صاحب العمل: 77-0479905)
⭐ التقييم: 4.9/5.0
💰 الكفاءة: تذهب %88 من الأموال إلى البرامج
📋 المهمة: تهدف إلى تغيير حياة ملايين الأطفال في المجتمعات ذات الدخل المنخفض من خلال التركيز على محو الأمية والمساواة بين الجنسين في التعليم.
Teach For America (رقم تعريف صاحب العمل: 13-3541913)
⭐ التقييم: 4.7/5.0
💰 الكفاءة: تذهب %81 من الأموال إلى البرامج
📋 المهمة: تعمل على توسيع نطاق الفرص التعليمية للأطفال الذين يواجهون صعوبات.
Tech Education Alliance (رقم تعريف صاحب العمل: 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 ID: intent_774795905_1730927536
- المبلغ: 50.00 دولار أمريكي (أو ما يعادله بالعملة المحلية) لمؤسسة Room to Read (رقم تعريف صاحب العمل: 77-0479905)
- Expires: 2024-11-07T15:32:16Z (in 1 hour)
يُسجِّل IntentMandate هذا نية التبرّع ويتضمّن قيودًا لضمان معالجة المعاملة بأمان. سأرسل الآن هذه المعلومات إلى الجهة المسؤولة عن معالجة المعاملات الآمنة لإنشاء عرض رسمي وإكمال تبرّعك.
وراء الكواليس، حدثت عدة أمور:
- تم التحقّق من صحة الإدخالات من قِبل "
_validate_charity_data()" - استخدم
_create_intent_mandate()نموذج AP2 Pydantic لإنشاء البنية:
# Created and validated via Pydantic
intent_mandate_model = IntentMandate(
user_cart_confirmation_required=True,
natural_language_description="Donate $50.00 to Room to Read",
merchants=["Room to Read"],
skus=None,
requires_refundability=False,
intent_expiry="2024-11-07T15:32:16Z"
)
# Converted to dict and extended with custom fields
intent_mandate_dict = intent_mandate_model.model_dump()
intent_mandate_dict.update({
"charity_ein": "77-0479905",
"amount": 50.0,
"currency": "USD"
})
- كتبت الأداة IntentMandate فقط في الحالة المشتركة:
state["intent_mandate"] = intent_mandate_dict
- تم إرسال رسالة نجاح مع تفاصيل الطلب إلى نموذج لغوي كبير
- أنشأ النموذج اللغوي الكبير رسالة المستخدم النهائية
أصبح 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 الرسمية للتحقّق من الصحة
- التقاط منظَّم لنية المستخدم
- يتضمّن تاريخ انتهاء الصلاحية لأغراض الأمان (يمنع هجمات إعادة التشغيل)
- تحدّد القيود (التجّار، وإمكانية ردّ الأموال، والتأكيد)
- وصف بلغة طبيعية للمستخدمين
- يمكن معالجتها آليًا للوكلاء
- تم التحقّق من صحة النموذج قبل تحويله إلى قاموس
✅ تحديد الذكرى على أنّها مشترَكة:
-
tool_context.stateهو "المفكرة" التي يمكن لجميع موظفي الدعم الوصول إليها - الكتابة في الحالة = إتاحة بيانات الاعتماد القابلة للتحقّق
- القراءة من الحالة = استخدام بيانات الاعتماد والتحقّق من صحتها
- تستخرج الوكلاء اللاحقون ما يحتاجون إليه من بيانات الاعتماد
✅ FunctionTool:
- تحوّل دوال Python إلى أدوات يمكن استدعاؤها من خلال النماذج اللغوية الكبيرة
- يعتمد على السلاسل النصية البرمجية وتلميحات الأنواع لفهم النموذج اللغوي الكبير
- تتم معالجة الطلب تلقائيًا
- قابلية تركيب الأدوات: أدوات صغيرة مركّزة > أدوات متكاملة
✅ تعليمات لموظفي الدعم:
- إرشادات مفصّلة حول سير العمل
- حدود واضحة ("لا...")
- مواصفات المَعلمات لمنع حدوث أخطاء
- التعريفات الفنية (ما هو IntentMandate)
- التعامل مع الحالات القصوى (ما يجب قوله عندما...)
الخطوات التالية
في الوحدة التالية، سننشئ وكيل التاجر لتلقّي IntentMandate وإنشاء بيانات الاعتماد الثانية القابلة للتحقّق: CartMandate.
أنشأ "وكيل Shopping" تفويض IntentMandate يتضمّن نية المستخدم مع تاريخ انتهاء الصلاحية. نحتاج الآن إلى وكيل لقراءة بيانات الاعتماد هذه، والتحقّق من عدم انتهاء صلاحيتها، وإنشاء عرض رسمي موقَّع ينص على ما يلي: "أنا، التاجر، سألتزم بهذا السعر وسأُسلّم هذه السلع".
لننشئ Merchant Agent ونطّلِع على بيانات اعتماد AP2 الثانية أثناء العمل.
5- إنشاء Merchant Agent - العروض الملزمة وCartMandate

من الاستكشاف إلى الالتزام
في الوحدة السابقة، أنشأتم Shopping Agent، وهو وكيل متخصّص يعثر على المؤسسات الخيرية المعتمَدة وينشئ 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"
}
لكن هذه مجرد نية المستخدم. قبل معالجة أي دفعة، نحتاج إلى ما يلي:
- بنية عرض رسمية تفهمها أنظمة الدفع
- مستند يثبت أنّ التاجر سيلتزم بهذا السعر
- التزام ملزم لا يمكن تغييره في منتصف المعاملة
- التحقّق من عدم انتهاء صلاحية الغرض
هذه هي مهمة وكيل التاجر.
ما هو 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: طرق الدفع المقبولة
- التفاصيل: السلع والمجموع
- options: Shipping, payer info requirements
3. merchant_authorization: توقيع تشفير
توقيعات التجّار: إثبات الالتزام
توقيع التاجر مهم جدًا. ويثبت ذلك:
- هذا العرض مقدَّم من تاجر معتمَد
- يلتزم التاجر بهذا السعر الدقيق
- لم يتم التلاعب بالعرض منذ إنشائه
في مرحلة الإنتاج، سيكون هذا توقيعًا مشفّرًا باستخدام PKI (البنية الأساسية للمفتاح العام) أو JWT (رموز JSON المميّزة للويب). في ورشة العمل التعليمية هذه، سنحاكي هذه العملية باستخدام تجزئة SHA-256.
# Production (real signature):
signature = sign_with_private_key(cart_data, merchant_private_key)
# Workshop (simulated signature):
cart_hash = hashlib.sha256(cart_json.encode()).hexdigest()
signature = f"SIG_{cart_hash[:16]}"
مهمتنا: إنشاء Merchant Agent
سيقوم وكيل التاجر بما يلي:
- قراءة IntentMandate من الحالة (ما كتبه "وكيل التسوّق")
- التحقّق من عدم انتهاء صلاحية الطلب
- استخرِج اسم المؤسسة الخيرية والمبلغ والتفاصيل الأخرى
- إنشاء بنية PaymentRequest متوافقة مع W3C باستخدام نماذج AP2 Pydantic
- Wrap it in AP2's CartMandate with expiry
- إضافة توقيع تاجر محاكاة
- كتابة 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 ونغلّفها في AP2 CartMandate باستخدام نماذج Pydantic.
👉 البحث:
# MODULE_5_STEP_3C_CREATE_CARTMANDATE_STRUCTURE
👉 استبدِل هذا السطر الواحد بما يلي:
# 5. Build the nested Pydantic models for the CartMandate
timestamp = datetime.now(timezone.utc)
cart_id = f"cart_{hashlib.sha256(f'{charity_name}{timestamp.isoformat()}'.encode()).hexdigest()[:12]}"
cart_expiry = timestamp + timedelta(minutes=15)
payment_request_model = PaymentRequest(
method_data=[PaymentMethodData(
supported_methods="CARD",
data={"supported_networks": ["visa", "mastercard", "amex"], "supported_types": ["debit", "credit"]}
)],
details=PaymentDetailsInit(
id=f"order_{cart_id}",
display_items=[PaymentItem(
label=f"Donation to {charity_name}",
amount=PaymentCurrencyAmount(currency="USD", value=amount) # Pydantic v2 handles float -> str conversion
)],
total=PaymentItem(
label="Total Donation",
amount=PaymentCurrencyAmount(currency="USD", value=amount)
)
),
options=PaymentOptions(request_shipping=False)
)
cart_contents_model = CartContents(
id=cart_id,
cart_expiry=cart_expiry.isoformat(),
merchant_name=charity_name,
user_cart_confirmation_required=False,
payment_request=payment_request_model
)
# MODULE_5_STEP_3D_ADD_SIGNATURE_AND_SAVE
الخطوة 3 د: إضافة التوقيع وحفظه في الحالة
أخيرًا، لنوقّع CartMandate باستخدام نموذج Pydantic ونحفظه في الحالة للوكيل التالي.
👉 البحث:
# MODULE_5_STEP_3D_ADD_SIGNATURE_AND_SAVE
👉 استبدِل هذا السطر الواحد بما يلي:
# 6. Generate signature from the validated Pydantic model
signature = _generate_merchant_signature(cart_contents_model)
# 7. Create the final CartMandate model, now including the signature
cart_mandate_model = CartMandate(
contents=cart_contents_model,
merchant_authorization=signature
)
# 8. Convert the final model to a dictionary for state storage and add the custom timestamp
cart_mandate_dict = cart_mandate_model.model_dump(mode='json')
cart_mandate_dict["timestamp"] = timestamp.isoformat()
# 9. Write the final dictionary to state
tool_context.state["cart_mandate"] = cart_mandate_dict
logger.info(f"CartMandate created successfully: {cart_id}")
return {
"status": "success",
"message": f"Created signed CartMandate {cart_id} for ${amount:.2f} donation to {charity_name}",
"cart_id": cart_id,
"cart_expiry": cart_expiry.isoformat(),
"signature": signature
}
الخطوة 4: إنشاء Merchant Agent - استيراد المكوّنات
لننشئ الآن الوكيل الذي سيستخدم هذه الأداة.
👉 فتح
charity_advisor/merchant_agent/agent.py
سيظهر لك نموذج يحتوي على علامات العناصر النائبة. لنبدأ باستيراد ما نحتاجه.
👉 البحث:
# MODULE_5_STEP_4_IMPORT_COMPONENTS
👉 استبدِل هذا السطر الواحد بما يلي:
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.merchant_tools import create_cart_mandate
الخطوة 5: كتابة تعليمات وكيل التاجر
لنكتب الآن التعليمات التي توضّح للوكيل متى وكيف يستخدم أداته.
👉 البحث:
# 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 Agent
👉 البحث:
# MODULE_5_STEP_6_ADD_TOOLS
tools=[],
👉 استبدِل هذين السطرَين بما يلي:
tools=[
FunctionTool(func=create_cart_mandate)
],
الخطوة 7: التحقّق من وكيل التاجر الكامل
لنتأكّد من توصيل كل الأسلاك بشكل صحيح.
👉 Your complete
charity_advisor/merchant_agent/agent.py
يجب أن يظهر الآن على النحو التالي:
"""
Merchant Agent - Creates W3C-compliant CartMandates with merchant signatures.
This agent acts as our "Contract Creator."
"""
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.merchant_tools import create_cart_mandate
merchant_agent = Agent(
name="MerchantAgent",
model="gemini-2.5-flash",
description="Creates formal, signed CartMandates for charity donations following W3C PaymentRequest standards.",
tools=[
FunctionTool(func=create_cart_mandate)
],
instruction="""You are a merchant specialist responsible for creating formal, signed offers (CartMandates).
Your workflow:
1. Read the IntentMandate from shared state.
The IntentMandate was created by the Shopping Agent and contains:
- merchants: List of merchant names
- amount: Donation amount
- charity_ein: Tax ID
- intent_expiry: When the intent expires
2. Use the create_cart_mandate tool to create a W3C PaymentRequest-compliant CartMandate.
This tool will:
- Validate the IntentMandate hasn't expired (CRITICAL security check)
- Extract the charity name and amount from the IntentMandate
- Create a structured offer with payment methods, transaction details, and merchant info
- Generate a merchant signature to prove authenticity
- Save the CartMandate to state for the payment processor
3. After creating the CartMandate, inform the user:
- That you've created a formal, signed offer
- The cart ID
- When the cart expires (15 minutes)
- That you're passing it to the secure payment processor
IMPORTANT BOUNDARIES:
- Your ONLY job is creating signed CartMandates from valid IntentMandates
- You do NOT process payments
- You do NOT see the user's payment methods or credentials
- You do NOT interact with payment networks
- You MUST validate that the IntentMandate hasn't expired before creating a cart
- After calling create_cart_mandate, your work is done
WHAT IS A CARTMANDATE:
A CartMandate is a binding commitment that says:
"I, the merchant, commit to accepting $X for this charity donation, and I prove it with my signature."
This commitment is structured using the W3C PaymentRequest standard and includes:
- Payment methods accepted (card, bank transfer)
- Transaction details (amount, charity name)
- Cart expiry (15 minutes from creation)
- Merchant signature (proof of commitment)
This is the second of three verifiable credentials in our secure payment system."""
)
✅ نقطة التحقّق: لديك الآن وكيل Merchant Agent كامل مع إنشاء AP2 CartMandate بشكل صحيح باستخدام نماذج Pydantic.
الخطوة 8: اختبار Merchant Agent
لنتحقّق الآن من أنّ الوكيل ينشئ 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 متداخلة داخل
- انتهاء صلاحية سلة التسوّق (أقصر من مدة نية الشراء)
- توقيع التاجر على الالتزام المُلزِم
- التحقّق من صحة بيانات النموذج يضمن الامتثال للمواصفات
✅ التحقّق من انتهاء الصلاحية:
- جارٍ قراءة IntentMandate من الحالة
- جارٍ التحقّق من صحة البنية باستخدام
IntentMandate.model_validate() - تحليل الطوابع الزمنية بتنسيق ISO 8601
- مقارنة بالوقت الحالي
- ميزة أمان تمنع المعالجة القديمة
✅ Merchant Signature:
- يُثبت الأصالة والالتزام
- تم إنشاؤه من نموذج Pydantic تم التحقّق منه
- يستخدم
model_dump(mode='json')للتمثيل الأساسي - تمت المحاكاة باستخدام SHA-256 لأغراض تعليمية
- يستخدم الإنتاج PKI/JWT
- يوقّع نموذج المحتوى، وليس القواميس
✅ واجهة برمجة التطبيقات PaymentRequest من W3C:
- تم الإنشاء باستخدام نموذج PaymentRequest Pydantic من AP2
- المعيار المتّبع في المجال لبيانات الدفع
- مدمجة داخل بنية AP2
- يحتوي على method_data وdetails وoptions
- إتاحة إمكانية التشغيل التفاعلي
✅ سلسلة بيانات الاعتماد مع النماذج:
- Shopping ← IntentMandate (تم التحقّق منه)
- يقرأ التاجر IntentMandate ← CartMandate (يتم التحقّق من صحة كلا النموذجَين)
- سيقرأ مقدّم بيانات الاعتماد CartMandate ← PaymentMandate
- تتحقّق كل خطوة من بيانات الاعتماد السابقة باستخدام Pydantic
✅ التطوير المستند إلى النماذج:
- التحقّق من صحة البيانات المدخَلة من خلال
model_validate() - إنشاء آمن للأنواع
- التسلسل التلقائي من خلال
model_dump() - أنماط جاهزة للاستخدام في مرحلة الإنتاج
الخطوات التالية
في الوحدة التالية، سننشئ موفّر بيانات الاعتماد لمعالجة الدفعات بأمان.
أنشأ وكيل التاجر عرضًا ملزمًا له تاريخ انتهاء صلاحية باستخدام نماذج AP2. نحتاج الآن إلى وكيل لقراءة CartMandate والحصول على موافقة المستخدم وتنفيذ عملية الدفع.
لننشئ مزوّد بيانات الاعتماد ونُكمل سلسلة بيانات اعتماد AP2.
6. إنشاء موفّر بيانات الاعتماد - تنفيذ الدفع الآمن

من العرض الملزم إلى تنفيذ الدفع
في الوحدة 5، أنشأت Merchant Agent، وهو وكيل متخصص يقرأ IntentMandates، ويتحقّق من عدم انتهاء صلاحيتها، وينشئ CartMandates ملزمة بتوقيعات التجّار. نحتاج الآن إلى وكيل لتلقّي CartMandate وتنفيذ الدفعة الفعلية.
هنا يأتي دور المبدأ الثالث والأخير من AP2: تنفيذ الدفع الآمن من خلال PaymentMandate.
AP2 Principle: PaymentMandate & Payment Execution
أهمية دور مزوّد بيانات الاعتماد
في الوحدة 5، أنشأ وكيل التاجر CartMandate وحفظه في الحالة:
state["cart_mandate"] = {
"contents": {
"id": "cart_abc123",
"cart_expiry": "2025-11-07:15:47:16Z",
"payment_request": {
"details": {
"total": {
"amount": {"currency": "USD", "value": "50.00"}
}
}
}
},
"merchant_authorization": "SIG_a3f7b2c8"
}
ولكن هذا مجرد عرض ملزم. قبل تنفيذ الدفعة، نحتاج إلى:
- التحقّق من عدم انتهاء صلاحية سلة التسوّق
- موافقة المستخدم على متابعة الدفع
- بيانات اعتماد تسمح بتنفيذ الدفعات
- معالجة الدفعات الفعلية (أو المحاكاة لورشة العمل)
هذه هي وظيفة موفِّر بيانات الاعتماد.
ما هو PaymentMandate؟
PaymentMandate هو مصطلح AP2 للإذن النهائي الذي يسمح بتنفيذ الدفعة. وهو مستند الاعتماد الثالث والأخير القابل للتحقّق منه في سلسلة AP2.
يمكنك التفكير في بيانات الاعتماد الثلاثة كعملية توقيع عقد:
- IntentMandate: "أنا مهتم بشراء هذا" (خطاب نوايا)
- CartMandate: "أنا، التاجر، أعرض البيع بهذا السعر" (عرض أسعار مكتوب)
- PaymentMandate: "أفوّضك بتحصيل الرسوم من طريقة الدفع الخاصة بي" (عقد موقَّع)
ولا يمكن تنفيذ الدفع إلا بعد توفّر بيانات الاعتماد الثلاثة.
بنية PaymentMandate
يتّبع 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: وقت إنشاء التفويض
مهمتنا: إنشاء مزوّد بيانات الاعتماد
سيؤدي مزوّد بيانات الاعتماد إلى:
- قراءة CartMandate من الحالة (ما كتبه Merchant Agent)
- التحقّق من عدم انتهاء صلاحية سلة التسوّق باستخدام نماذج AP2 Pydantic
- استخراج تفاصيل الدفع من البنية المتداخلة
- إنشاء PaymentMandate بموافقة المستخدم باستخدام نماذج AP2
- محاكاة معالجة الدفعات (في مرحلة الإنتاج، يتم استدعاء واجهة برمجة تطبيقات الدفعات الحقيقية)
- كتابة PaymentMandate ونتيجة الدفع في الحالة
لننشئها خطوة بخطوة.
الخطوة 1: إضافة مساعد التحقّق من انتهاء صلاحية سلة التسوّق
أولاً، لننشئ دالة مساعدة تتحقّق من عدم انتهاء صلاحية CartMandate، تمامًا كما تحقّقنا من انتهاء صلاحية IntentMandate في الوحدة 5.
👉 فتح
charity_advisor/tools/payment_tools.py
لنضِف عملية التحقّق من تاريخ انتهاء الصلاحية:
👉 البحث:
# MODULE_6_STEP_1_ADD_CART_EXPIRY_VALIDATION_HELPER
👉 استبدِل هذا السطر الواحد بما يلي:
def _validate_cart_expiry(cart: CartMandate) -> tuple[bool, str]:
"""
Validates that the CartMandate hasn't expired.
This is a critical security check - expired carts should not be processed.
Args:
cart: The Pydantic CartMandate model to validate.
Returns:
(is_valid, error_message): Tuple indicating if cart is still valid.
"""
try:
expiry_str = cart.contents.cart_expiry
expiry_time = datetime.fromisoformat(expiry_str.replace('Z', '+00:00'))
now = datetime.now(timezone.utc)
if expiry_time < now:
return False, f"CartMandate expired at {expiry_str}"
time_remaining = expiry_time - now
logger.info(f"CartMandate valid. Expires in {time_remaining.total_seconds():.0f} seconds")
return True, ""
except (ValueError, TypeError, AttributeError) as e:
return False, f"Invalid cart_expiry format or structure: {e}"
الخطوة 2: إضافة PaymentMandate Creation Helper
لننشئ الآن دالة مساعدة تنشئ بنية PaymentMandate باستخدام نماذج AP2 Pydantic الرسمية.
👉 البحث:
# MODULE_6_STEP_2_ADD_PAYMENT_MANDATE_CREATION_HELPER
👉 استبدِل هذا السطر الواحد بما يلي:
def _create_payment_mandate(cart: CartMandate, consent_granted: bool) -> dict:
"""
Creates a PaymentMandate using the official AP2 Pydantic models.
It links to the CartMandate and includes user consent status.
Args:
cart: The validated Pydantic CartMandate model being processed.
consent_granted: Whether the user has consented to the payment.
Returns:
A dictionary representation of the final, validated PaymentMandate.
"""
timestamp = datetime.now(timezone.utc)
# Safely extract details from the validated CartMandate model
cart_id = cart.contents.id
merchant_name = cart.contents.merchant_name
total_item = cart.contents.payment_request.details.total
# Create the nested PaymentResponse model for the mandate
payment_response_model = PaymentResponse(
request_id=cart_id,
method_name="CARD", # As per the simulated flow
details={"token": "simulated_payment_token_12345"}
)
# Create the PaymentMandateContents model
payment_mandate_contents_model = PaymentMandateContents(
payment_mandate_id=f"payment_{hashlib.sha256(f'{cart_id}{timestamp.isoformat()}'.encode()).hexdigest()[:12]}",
payment_details_id=cart_id,
payment_details_total=total_item,
payment_response=payment_response_model,
merchant_agent=merchant_name,
timestamp=timestamp.isoformat()
)
# Create the top-level PaymentMandate model
# In a real system, a user signature would be added to this model
payment_mandate_model = PaymentMandate(
payment_mandate_contents=payment_mandate_contents_model
)
# Convert the final Pydantic model to a dictionary for state storage
final_dict = payment_mandate_model.model_dump(mode='json')
# Add any custom/non-standard fields required by the codelab's logic to the dictionary
# The spec does not have these fields, but your original code did. We add them
# back to ensure compatibility with later steps.
final_dict['payment_mandate_contents']['user_consent'] = consent_granted
final_dict['payment_mandate_contents']['consent_timestamp'] = timestamp.isoformat() if consent_granted else None
final_dict['agent_present'] = True
return final_dict
الخطوة 3 (أ): إنشاء توقيع الأداة وإعدادها
لنبدأ الآن في إنشاء الأداة الرئيسية بشكل تدريجي. أولاً، توقيع الدالة والإعداد الأولي.
👉 البحث:
# MODULE_6_STEP_3A_CREATE_TOOL_SIGNATURE
👉 استبدِل هذا السطر الواحد بما يلي:
async def create_payment_mandate(tool_context: Any) -> Dict[str, Any]:
"""
Creates a PaymentMandate and simulates payment processing using Pydantic models.
This tool now reads the CartMandate from state, parses it into a validated model,
and creates a spec-compliant PaymentMandate.
"""
logger.info("Tool called: Creating PaymentMandate and processing payment")
# MODULE_6_STEP_3B_VALIDATE_CARTMANDATE
الخطوة 3 (ب): التحقّق من صحة CartMandate
لنضِف الآن المنطق لقراءة CartMandate والتحقّق من صحته باستخدام نماذج AP2 Pydantic، والتحقّق من انتهاء الصلاحية.
👉 البحث:
# MODULE_6_STEP_3B_VALIDATE_CARTMANDATE
👉 استبدِل هذا السطر الواحد بما يلي:
# 1. Read CartMandate dictionary from state
cart_mandate_dict = tool_context.state.get("cart_mandate")
if not cart_mandate_dict:
logger.error("No CartMandate found in state")
return { "status": "error", "message": "No CartMandate found. Merchant Agent must create cart first." }
# 2. Parse dictionary into a validated Pydantic model
try:
cart_model = CartMandate.model_validate(cart_mandate_dict)
except Exception as e:
logger.error(f"Could not validate CartMandate structure: {e}")
return {"status": "error", "message": f"Invalid CartMandate structure: {e}"}
# 3. Validate that the cart hasn't expired using the Pydantic model
is_valid, error_message = _validate_cart_expiry(cart_model)
if not is_valid:
logger.error(f"CartMandate validation failed: {error_message}")
return {"status": "error", "message": error_message}
# MODULE_6_STEP_3C_EXTRACT_PAYMENT_DETAILS
الخطوة 3ج: استخراج تفاصيل الدفع من البنية المتداخلة
لننتقل الآن إلى نموذج CartMandate الذي تم التحقّق منه لاستخراج تفاصيل الدفع التي نحتاجها.
👉 البحث:
# MODULE_6_STEP_3C_EXTRACT_PAYMENT_DETAILS
👉 استبدِل هذا السطر الواحد بما يلي:
# 4. Safely extract data from the validated model
cart_id = cart_model.contents.id
merchant_name = cart_model.contents.merchant_name
amount_value = cart_model.contents.payment_request.details.total.amount.value
currency = cart_model.contents.payment_request.details.total.amount.currency
consent_granted = True # Assume consent for this codelab flow
# MODULE_6_STEP_3D_CREATE_PAYMENTMANDATE_AND_SIMULATE
الخطوة 3 د: إنشاء PaymentMandate ومحاكاة الدفع
أخيرًا، لننشئ PaymentMandate باستخدام المساعد المستند إلى Pydantic، ونحاكي معالجة الدفعات، ونحفظ كل شيء في الحالة.
👉 البحث:
# MODULE_6_STEP_3D_CREATE_PAYMENTMANDATE_AND_SIMULATE
👉 استبدِل هذا السطر الواحد بما يلي:
# 5. Create the spec-compliant PaymentMandate using the validated CartMandate model
payment_mandate_dict = _create_payment_mandate(cart_model, consent_granted)
# 6. Simulate payment processing
transaction_id = f"txn_{hashlib.sha256(f'{cart_id}{datetime.now(timezone.utc).isoformat()}'.encode()).hexdigest()[:16]}"
payment_result = {
"transaction_id": transaction_id,
"status": "completed",
"amount": amount_value,
"currency": currency,
"merchant": merchant_name,
"timestamp": datetime.now(timezone.utc).isoformat(),
"simulation": True
}
# 7. Write the compliant PaymentMandate dictionary and result to state
tool_context.state["payment_mandate"] = payment_mandate_dict
tool_context.state["payment_result"] = payment_result
logger.info(f"Payment processed successfully: {transaction_id}")
return {
"status": "success",
"message": f"Payment of {currency} {amount_value:.2f} to {merchant_name} processed successfully",
"transaction_id": transaction_id,
"payment_mandate_id": payment_mandate_dict["payment_mandate_contents"]["payment_mandate_id"]
}
الخطوة 4: إنشاء وكيل موفِّر بيانات الاعتماد - استيراد المكوّنات
لننشئ الآن الوكيل الذي يستخدم هذه الأداة.
👉 فتح
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: التحقّق من مزوّد بيانات الاعتماد الكامل
لنتأكّد من توصيل كل الأسلاك بشكل صحيح.
👉 Your complete
charity_advisor/credentials_provider/agent.py
يجب أن يظهر الآن على النحو التالي:
"""
Credentials Provider Agent - Handles payment processing with user consent.
This agent acts as our "Payment Processor."
"""
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from charity_advisor.tools.payment_tools import create_payment_mandate
credentials_provider = Agent(
name="CredentialsProvider",
model="gemini-2.5-flash",
description="Securely processes payments by creating PaymentMandates and executing transactions with user consent.",
tools=[
FunctionTool(func=create_payment_mandate)
],
instruction="""You are a payment specialist responsible for securely processing payments with user consent.
Your workflow:
1. Read the CartMandate from shared state.
The CartMandate was created by the Merchant Agent and has this structure:
- contents: AP2 wrapper containing:
- id: Cart identifier
- cart_expiry: When the cart expires
- merchant_name: Who is receiving payment
- payment_request: W3C PaymentRequest with transaction details
- merchant_authorization: Merchant's signature
2. Extract payment details from the nested structure:
- Navigate: cart_mandate["contents"]["payment_request"]["details"]["total"]["amount"]
- This gives you the currency and value
3. **IMPORTANT - Two-Turn Conversational Confirmation Pattern:**
Before calling create_payment_mandate, you MUST:
- Present the payment details clearly to the user
- Ask explicitly: "I'm ready to process a payment of $X to [Charity Name]. Do you want to proceed with this donation?"
- WAIT for the user's explicit confirmation (e.g., "yes", "proceed", "confirm")
- ONLY call create_payment_mandate AFTER receiving explicit confirmation
- If user says "no" or "cancel", DO NOT call the tool
4. After user confirms, use the create_payment_mandate tool to:
- Validate the CartMandate hasn't expired (CRITICAL security check)
- Create a PaymentMandate (the third AP2 credential)
- Simulate payment processing
- Record the transaction result
5. After processing, inform the user:
- That payment was processed successfully (this is a simulation)
- The transaction ID
- The amount and merchant
- That this completes the three-agent AP2 credential chain
IMPORTANT BOUNDARIES:
- Your ONLY job is creating PaymentMandates and processing payments
- You do NOT discover charities (that's Shopping Agent's job)
- You do NOT create offers (that's Merchant Agent's job)
- You MUST validate that the CartMandate hasn't expired before processing
- You MUST get explicit user confirmation before calling create_payment_mandate
- In production, this consent mechanism would be even more robust
WHAT IS A PAYMENTMANDATE:
A PaymentMandate is the final credential that authorizes payment execution. It:
- Links to the CartMandate (proving the merchant's offer)
- Records user consent
- Contains payment details extracted from the CartMandate
- Enables the actual payment transaction
This is the third and final verifiable credential in our secure payment system.
THE COMPLETE AP2 CREDENTIAL CHAIN:
1. Shopping Agent creates IntentMandate (user's intent)
2. Merchant Agent reads IntentMandate, creates CartMandate (merchant's binding offer)
3. You read CartMandate, get user confirmation, create PaymentMandate (authorized payment execution)
Each credential:
- Has an expiry time (security feature)
- Links to the previous credential
- Is validated before the next step
- Creates an auditable chain of trust"""
)
✅ نقطة التحقّق: لديك الآن "مقدّم بيانات اعتماد" (Credentials Provider) كامل مع قراءة CartMandate وإنشاء PaymentMandate بشكل صحيح باستخدام نماذج AP2 Pydantic.
الخطوة 8: اختبار "مزوّد بيانات الاعتماد"
لنتحقّق الآن من أنّ الوكيل يعالج الدفعات بشكل صحيح ويكمل سلسلة بيانات الاعتماد.
👉 في وحدة 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 الكاملة أثناء العمل.
كل وكيل:
- يقرأ بيانات الاعتماد من الحالة
- يتحقّق من صحة الرمز باستخدام نماذج Pydantic (التحقّق من البنية وتاريخ انتهاء الصلاحية)
- يتم إنشاء بيانات الاعتماد التالية باستخدام نماذج AP2
- يكتب في الحالة للوكيل التالي
ما أنشأته للتو
لقد أكملت بنجاح سلسلة بيانات الاعتماد المكوّنة من ثلاثة وكلاء في 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 - التعرّف على الفرق بين برنامج تضمين AP2 ومعيار W3C
- استخرِج merchant_name وamount وcurrency بأمان من النموذج
- يرصد Pydantic أخطاء البنية تلقائيًا
✅ التحقّق من انتهاء صلاحية سلة التسوّق:
- يقبل نموذج
CartMandatePydantic الذي تم التحقّق من صحته - القراءة من
cart.contents.cart_expiry(الوصول إلى السمات) - ميزة أمان تمنع معالجة سلة التسوّق القديمة
- المدة (15 دقيقة) أقصر من المدة المطلوبة (ساعة واحدة)
✅ محاكاة الدفع:
- نموذج تعليمي للجهة المسؤولة عن معالجة المعاملات
- إنشاء معرِّف المعاملة
- يسجّل payment_result في الحالة
- تم وضع علامة واضحة على أنّها محاكاة (simulation: True flag)
✅ سلسلة AP2 كاملة مع النماذج:
- ثلاثة وكلاء، وثلاث بيانات اعتماد، وثلاث عمليات تحقّق من Pydantic
- يتحقّق كل وكيل من بنية بيانات الاعتماد السابقة باستخدام النماذج
- يرتبط كل اعتماد بالاعتماد السابق لإنشاء سجلّ تدقيق
- تحافظ عمليات التسليم المستندة إلى الحالة على فصل الأدوار
- منع أخطاء الكتابة في السلسلة بأكملها
✅ التطوير المستند إلى النماذج:
- التحقّق من صحة البيانات المدخَلة من خلال
model_validate() - إنشاء نماذج متداخلة تمنع أخطاء الكتابة
- التسلسل التلقائي من خلال
model_dump(mode='json') - أنماط جاهزة للإنتاج من البداية
الخطوات التالية
في الوحدة التالية، سننشئ وكيل التنسيق الذي ينسّق عمل الوكلاء المتخصّصين الثلاثة.
لقد أنشأتم ثلاثة وكلاء متخصّصين فعّالين باستخدام نماذج AP2 Pydantic. والآن، لننشئ الموصّل الذي ينسّقها في تجربة تبرّع سلسة.
لننشئ الآن "المنسِّق" ونطّلِع على النظام الكامل أثناء عمله.
7. التنسيق: جمع كل المعلومات معًا
من المتخصّصين إلى التجربة السلسة
في الوحدات السابقة، أنشأتم ثلاثة وكلاء متخصّصين:
- وكيل التسوّق: يعثر على المؤسسات الخيرية وينشئ IntentMandate
- وكيل التاجر: ينشئ CartMandate من IntentMandate
- موفّر بيانات الاعتماد: ينشئ PaymentMandate ويعالج الدفعات
ينقسم هؤلاء الوكلاء بشكل طبيعي إلى مرحلتَين:
- المرحلة 1 (التسوّق): محادثة متعدّدة الجولات للعثور على مؤسسة خيرية واختيارها
- المرحلة 2 (المعالجة): التنفيذ الذري لإنشاء العرض والدفع
ولكن في الوقت الحالي، عليك تنظيم هذه المراحل يدويًا بنفسك.
هنا يأتي دور أنماط التنسيق في ADK.
المبدأ الثاني في AP: التنسيق يفرض حدود الثقة
أهمية التنسيق في مجال الأمان
لا تقتصر عملية التنسيق على توفير الراحة فحسب، بل تتعلّق أيضًا بفرض حدود الثقة من خلال البنية الأساسية.
بدون التنسيق:
# 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: منسّق الجذر (الوكيل الموجّه للمستخدمين)
- شخصية ودودة
- Delegates to shopping_agent for charity selection
- يتم التفويض إلى مسار المعالجة بعد إنشاء 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 (أ): إنشاء إعدادات الوكيل الجذر
لننشئ الآن الوكيل الموجّه للمستخدمين الذي ينسّق بين المرحلتَين. سننشئ هذا الوكيل في ثلاثة أجزاء: الإعداد (3A)، والتعليمات (3B)، والوكلاء الفرعيون (3C).
👉 البحث:
# MODULE_7_STEP_3A_CREATE_ROOT_AGENT_SETUP
👉 استبدِل هذا السطر الواحد بما يلي:
# Create the root orchestrator agent
# This is what users interact with directly
root_agent = Agent(
name="CharityAdvisor",
model="gemini-2.5-pro",
description="A friendly charity giving assistant that helps users donate to verified organizations.",
# MODULE_7_STEP_3B_WRITE_ROOT_AGENT_INSTRUCTION
الخطوة 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: التحقّق من النظام بالكامل
لنتأكّد من أنّ عملية التنسيق تتم بشكل صحيح.
👉 Your complete
charity_advisor/agent.py
يجب أن يظهر الآن على النحو التالي:
"""
Main orchestration: The donation processing pipeline and root orchestrator agent.
"""
from google.adk.agents import Agent, SequentialAgent
from charity_advisor.shopping_agent.agent import shopping_agent
from charity_advisor.merchant_agent.agent import merchant_agent
from charity_advisor.credentials_provider.agent import credentials_provider
# Create the donation processing pipeline
# This runs Merchant → Credentials in sequence AFTER charity is selected
donation_processing_pipeline = SequentialAgent(
name="DonationProcessingPipeline",
description="Creates signed offer and processes payment after charity is selected",
sub_agents=[
merchant_agent,
credentials_provider
]
)
# Create the root orchestrator agent
# This is what users interact with directly
root_agent = Agent(
name="CharityAdvisor",
model="gemini-2.5-flash",
description="A friendly charity giving assistant that helps users donate to verified organizations.",
instruction="""You are a helpful and friendly charity giving advisor.
Your workflow has TWO distinct phases:
PHASE 1: CHARITY SELECTION (delegate to shopping_agent)
When a user expresses interest in donating:
1. Delegate to shopping_agent immediately
2. The shopping_agent will:
- Search for charities matching their cause
- Present verified options with ratings
- Engage in conversation (user may ask questions, change their mind)
- Wait for user to select a specific charity and amount
- Create an IntentMandate when user decides
3. Wait for shopping_agent to complete
You'll know Phase 1 is complete when shopping_agent's response includes:
- "IntentMandate created" or "Intent ID: intent_xxx"
- Charity name and donation amount
PHASE 2: PAYMENT PROCESSING (delegate to DonationProcessingPipeline)
After shopping_agent completes:
1. Acknowledge the user's selection naturally:
"Perfect! Let me process your $X donation to [Charity]..."
2. Delegate to DonationProcessingPipeline
3. The pipeline will automatically:
- Create signed cart offer (MerchantAgent)
- Get consent and process payment (CredentialsProvider)
4. After pipeline completes, summarize the transaction
CRITICAL RULES:
- Phase 1 may take multiple conversation turns (this is normal)
- Only proceed to Phase 2 after IntentMandate exists
- Don't rush the user during charity selection
- Don't ask user to "proceed" between phases - transition automatically
EXAMPLE FLOW:
User: "I want to donate to education"
You: [delegate to shopping_agent]
Shopping: "Here are 3 education charities..." [waits]
User: "Tell me more about the first one"
Shopping: "Room to Read focuses on..." [waits]
User: "Great, I'll donate $50 to Room to Read"
Shopping: "IntentMandate created (ID: intent_123)..."
You: "Perfect! Processing your $50 donation to Room to Read..." [delegate to DonationProcessingPipeline]
Pipeline: [creates offer, gets consent, processes payment]
You: "Done! Your donation was processed successfully. Transaction ID: txn_456"
Your personality:
- Warm and encouraging
- Patient during charity selection
- Clear about educational nature
- Smooth transitions between phases""",
sub_agents=[
shopping_agent,
donation_processing_pipeline
]
)
الخطوة 5: تعزيز الأمان باستخدام عمليات الاستدعاء للتحقّق (اختياري، يمكنك الانتقال إلى الخطوة 7)

يضمن SequentialAgent ترتيب التنفيذ، ولكن ماذا لو:
- تعذُّر تنفيذ طلب "وكيل التسوّق" بدون إرسال إشعار (لم يتم إنشاء IntentMandate مطلقًا)
- مرور ساعة بين Shopping وMerchant (تنتهي صلاحية النية)
- تلف الحالة أو محوها
- يحاول أحد المستخدمين الاتصال بالتاجر مباشرةً، متجاوزًا Shopping
عمليات الاستدعاء تضيف إجراءات تنفيذية على مستوى البنية، فهي تتحقّق من المتطلبات الأساسية قبل أن يبدأ الوكيل حتى في طلب نموذج لغوي كبير. هذا هو مفهوم "الدفاع في العمق": تتحقّق الأدوات من صحة الطلبات أثناء التنفيذ، بينما تتحقّق عمليات الاستدعاء من صحتها قبل التنفيذ.
لنضِف عمليات استدعاء التحقّق من الصحة إلى وكيلَي Merchant وCredentials Provider.
الخطوة 5 (أ): إضافة Merchant Validation - Import Callback Types
أولاً، لنضِف عمليات الاستيراد اللازمة لعمليات الاستدعاء.
👉 فتح
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 (ب): إنشاء دالة التحقّق من صحة الطلب
لننشئ الآن دالّة رد اتصال تتحقّق من صحة 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 (ج): ربط معاودة الاتصال بوكيل التاجر
والآن، لنربط معاودة الاتصال بالوكيل.
👉 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 (أ): استيراد أنواع عمليات معاودة الاتصال
👉 فتح
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 (ب): إنشاء دالة التحقّق من سلة التسوّق
👉 في الهند
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 (ج): إرفاق دالة الاستدعاء بموفّر بيانات الاعتماد
👉 في الهند
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 من المتصفّح:
من رمز معاينة الويب (يشبه عينًا أو مربّعًا بداخله سهم) في شريط أدوات Cloud Shell (عادةً في أعلى يسار الصفحة)، انقر على تغيير المنفذ. في النافذة المنبثقة، اضبط المنفذ على 8000 وانقر على "تغيير ومعاينة" (Change and Preview). سيفتح Cloud Shell بعد ذلك علامة تبويب جديدة في المتصفّح تعرض واجهة مستخدم ADK على الويب.

👉 اختيار الوكيل من القائمة المنسدلة:
في واجهة مستخدم الويب الخاصة بـ ADK، ستظهر قائمة منسدلة في الأعلى. اختَر charity_advisor من القائمة.

ستظهر لك واجهة الويب الخاصة بـ ADK مع:
- لوحة المحادثة: في الجانب الأيمن، لإجراء المحادثة
- لوحة التتبّع: على يسار الصفحة، لتتبّع البيانات (سنستخدمها في الوحدة 9)
الاختبار 1: إكمال مسار التبرّع (الحالة العادية)
👉 في واجهة المحادثة، اكتب:
I want to donate to an education charity
شاهِد العملية الكاملة:


ما يحدث (يظهر في لوحة التتبُّع على يسار الصفحة):
1. يفوّض Advisor المهام إلى ShoppingAgent:
- يبحث ShoppingAgent عن مؤسسات خيرية تعليمية
- يعرض لك 3 خيارات تم التحقّق منها مع التفاصيل
2. تتفاعل مع ShoppingAgent (قد يستغرق ذلك عدة جولات):
User: "Tell me more about Room to Read"
Shopping: [explains mission and impact]
User: "I'll donate $50 to Room to Read"
3. ينشئ ShoppingAgent التفويض IntentMandate:
- إنشاء الطلب وتوقيعه
- عرض رسالة تأكيد تتضمّن معرّف Intent
4. انتقال المستشار إلى مرحلة المعالجة:
ممتاز. جارٍ معالجة تبرّعك بقيمة 50 دولار أمريكي لمؤسسة Room to Read...
5. يتم تفعيل DonationProcessingPipeline:
- تتحقّق معاودة الاتصال من التاجر من IntentMandate (✓ تم اجتيازها) ← جديد!
- ينشئ وكيل التاجر تفويض CartMandate مع توقيع
- Credentials callback validates CartMandate (✓ passed) ← NEW!
- يُعدّ مزوّد بيانات الاعتماد الدفعة
6- معالجة الدفعات:
- ينشئ مزوّد بيانات الاعتماد PaymentMandate
- محاكاة معالجة الدفعات
- عرض معرِّف المعاملة
7- ملخّصات Advisor:
ممتاز. تمت معالجة تبرّعك بنجاح. 🎉
التفاصيل:
- المبلغ: 50.00 دولار أمريكي (أو ما يعادلها بالعملة المحلية)
- المؤسسة الخيرية: Room to Read (رقم تعريف صاحب العمل: 77-0479905)
- معرِّف المعاملة: txn_a3f7b2c8d9e1f4a2
الاختبار 2: التحقّق من رصد حالات تعذُّر معاودة الاتصال (اختبار متقدّم اختياري)
هل تريد أن ترى عمليات الاستدعاء أثناء العمل في اكتشاف الأخطاء؟ يجب إتلاف الحالة يدويًا (تصحيح الأخطاء المتقدّم)، ولكن في مرحلة الإنتاج، ستلتقط عمليات الاستدعاء ما يلي:
- تعذُّر عمل أداة Shopping Agent ← حظر عمليات معاودة الاتصال بالتاجر: "خطأ: تعذّر إنشاء سلة التسوّق..."
- مرور ساعتين ← تحظر عمليات معاودة الاتصال من التاجر: "خطأ: انتهت صلاحية الطلب..."
- انتهاء صلاحية سلة التسوّق ← تحظر عمليات معاودة الاتصال لبيانات الاعتماد: "خطأ: انتهت صلاحية سلة التسوّق (الحدّ الأقصى 15 دقيقة)..."
يتم الآن فرض هذه الحالات الاستثنائية من الناحية الهيكلية من خلال عمليات الاستدعاء للتحقّق من الصحة.
ما أنشأته للتو
لقد نجحت في تنظيم ثلاثة وكلاء متخصّصين في نظام سلس وموثوق به مع التحقّق من البنية.
الخطوات التالية
لقد أكملت الآن الأساس الفني لإنشاء وكلاء موثوقين:
لقد أنشأت نظامًا كاملاً موثوقًا به يفرض سلسلة بيانات الاعتماد محليًا. والآن، لنتيح للمستخدمين الحقيقيين الوصول إليه من خلال نشره في قناة الإصدار العلني، ولنفعّل سجلّ المساءلة الذي يتيح استخدام الوحدة 9.
لننشر وكيلك المحصّن على Google Cloud.
8. النشر

اكتمل الآن نظام التبرّع الموثوق به من خلال ثلاثة وكلاء متخصّصين يعملون محليًا:
ولكنه يعمل فقط على جهاز التطوير الخاص بك. لجعل هذا النظام مفيدًا للمستخدمين الحقيقيين، ولتسجيل مسارات المساءلة التي تثبت الموثوقية، عليك نشره في بيئة الإنتاج.
توضّح لك هذه الوحدة كيفية نشر الوكيل على Google Cloud مع تفعيل إمكانية تتبّع البيانات من اليوم الأول. إنّ علامة --trace_to_cloud التي ستستخدمها أثناء عملية النشر هي التي تتيح تتبُّع المساءلة في الوحدة 9.
فهم خيارات النشر
تتيح حزمة ADK استخدام أهداف نشر متعددة. ولكل منها خصائص مختلفة من حيث التعقيد وإدارة الجلسات والتوسّع والتكلفة:
العامل | المحلية ( | Agent Engine | Cloud Run |
التعقيد | مبسَّط | منخفض | متوسط |
استمرار الجلسة | في الذاكرة فقط (يتم فقدانها عند إعادة التشغيل) | مُدارة من خلال Vertex AI (تلقائيًا) | Cloud SQL (PostgreSQL) أو في الذاكرة |
البنية الأساسية | بلا (جهاز المطوّر فقط) | مُدار بالكامل | حاوية + قاعدة بيانات اختيارية |
التشغيل على البارد | لا ينطبق | 100-500 ملي ثانية | 100-2000 ملي ثانية |
توسيع النطاق | مثيل واحد | تلقائي | تلقائي (إلى الصفر) |
نموذج التكلفة | مجاني (الحوسبة المحلية) | مستندة إلى الحوسبة | الطلبات + الفئة المجانية |
UI Support | نعم (مدمج) | لا (واجهة برمجة التطبيقات فقط) | نعم (من خلال علامة |
إعداد إمكانية تتبّع البيانات | عارض التتبُّع المحلي | تلقائي مع | يتطلب علامة |
مناسب لـ | التطوير والاختبار | وكلاء الإنتاج | وكلاء الإنتاج |
اقتراح: بالنسبة إلى نظام التبرّع الموثوق به هذا، ننصح باستخدام Agent Engine كعملية نشر أساسية في مرحلة الإنتاج لأنّه يوفّر ما يلي:
- بنية تحتية مُدارة بالكامل (لا حاجة إلى إدارة الحاويات)
- استمرارية الجلسة المضمّنة من خلال
VertexAiSessionService - التدرّج التلقائي بدون عمليات تشغيل باردة
- نشر بسيط (لا يتطلب معرفة بـ Docker)
- دمج Cloud Trace تلقائيًا
خيار إضافي: Google Kubernetes Engine (GKE)
بالنسبة إلى المستخدمين المتقدّمين الذين يحتاجون إلى التحكّم على مستوى Kubernetes أو الاتصال المخصّص بالشبكة أو تنسيق الخدمات المتعدّدة، يتوفّر نشر GKE. يوفّر هذا الخيار أقصى قدر من المرونة، ولكنّه يتطلّب المزيد من الخبرة التشغيلية (إدارة المجموعات والبيانات وحسابات الخدمة).
لا يتناول هذا الدرس التطبيقي حول الترميز عملية نشر GKE، ولكنّها موثّقة بالكامل في دليل نشر ADK GKE.
المتطلبات الأساسية
1. إعداد مشروع على السحابة الإلكترونية في Google Cloud
يجب أن يكون لديك مشروع على Google Cloud مع تفعيل الفوترة. إذا لم يكن لديك حساب:
- إنشاء مشروع: Google Cloud Console
- تفعيل الفوترة: تفعيل الفوترة
- دوِّن رقم تعريف المشروع (وليس اسم المشروع أو رقمه)
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. تفعيل واجهات برمجة التطبيقات المطلوبة
تتطلّب عملية النشر تفعيل عدة واجهات برمجة تطبيقات في Google Cloud. نفِّذ الأمر التالي لتفعيلها:
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: لإمكانية تتبّع البيانات والمساءلة
- Compute Engine API: لإدارة حسابات الخدمة
الخطوة 1: فهم البنية الأساسية للنشر
يتضمّن مشروعك نصًا برمجيًا موحّدًا للنشر (deploy.sh) يتعامل مع جميع أوضاع النشر.
👉 مراجعة نص النشر البرمجي (اختياري):
cat deploy.sh
يوفّر النص البرمجي ثلاثة أوضاع للنشر:
-
./deploy.sh local: التشغيل محليًا باستخدام مساحة تخزين في الذاكرة ./deploy.sh agent-engine- النشر في Vertex AI Agent Engine (يُنصح به)-
./deploy.sh cloud-run- النشر على Cloud Run باستخدام واجهة مستخدم اختيارية
طريقة عمل هذه الميزة:
بالنسبة إلى عملية نشر Agent Engine، ينفّذ النص البرمجي ما يلي:
adk deploy agent_engine \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
--staging_bucket=$STAGING_BUCKET \
--display_name="Charity Advisor" \
--trace_to_cloud \
charity_advisor
بالنسبة إلى عملية النشر في Cloud Run، يتم تنفيذ ما يلي:
adk deploy cloud_run \
--project=$GOOGLE_CLOUD_PROJECT \
--region=$GOOGLE_CLOUD_LOCATION \
--service_name="charity-advisor" \
--app_name="charity_advisor" \
--with_ui \
--trace_to_cloud \
charity_advisor
تُعدّ العلامة --trace_to_cloud مهمة لكلا نوعَي النشر، فهي تتيح دمج Cloud Trace مع سجلّ المساءلة الذي ستتعرّف عليه في الوحدة 9.
الخطوة 2: إعداد Agent Engine Wrapper
يتطلّب Agent Engine نقطة دخول محدّدة تغلّف وكيلك لبيئة التشغيل المُدارة. تم إنشاء هذا الملف لك.
👉 مراجعة
charity_advisor/agent_engine_app.py
:
"""Agent Engine application wrapper.
This file prepares the Charity Advisor agent for deployment to Vertex AI Agent Engine.
"""
from vertexai import agent_engines
from .agent import root_agent
# Wrap the agent in an AdkApp object for Agent Engine deployment
app = agent_engines.AdkApp(
agent=root_agent,
enable_tracing=True, # Enables Cloud Trace integration automatically
)
سبب الحاجة إلى هذا الملف:
- يتطلّب Agent Engine أن يكون الوكيل مضمّنًا في عنصر
AdkApp - تتيح المَعلمة
enable_tracing=Trueدمج Cloud Trace تلقائيًا - تتم الإشارة إلى هذا الغلاف من خلال واجهة سطر الأوامر في ADK أثناء عملية النشر
- يتم ضبط
VertexAiSessionServiceعلى الاحتفاظ بالجلسة تلقائيًا
الخطوة 3: النشر في Agent Engine (يُنصح به)
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 الآن ما يلي:
✅ الوكلاء الثلاثة (Shopping وMerchant وCredentials) يعملون في بيئة تشغيل مُدارة
✅ منطق سلسلة بيانات الاعتماد الكاملة (Intent → Cart → تفويضات الدفع)
✅ آلية الحصول على موافقة المستخدم مع سير عمل التأكيد
✅ الاحتفاظ التلقائي بالجلسة من خلال VertexAiSessionService
✅ بنية أساسية قابلة للتوسّع تلقائيًا تديرها Google
✅ التكامل مع Cloud Trace لإمكانية تتبّع البيانات بالكامل
الخطوة 4: اختبار الوكيل الذي تم نشره
تحديث بيئتك
يُرجى التأكّد من أنّ .env يتضمّن معرّف Agent Engine:
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
قائمة التحقّق
بعد الاختبار، تحقَّق مما يلي:
✅ يردّ الوكيل على طلبات البحث
✅ يتم تنفيذ الوكلاء الثلاثة بالتسلسل (Shopping ← Merchant ← Credentials)
✅ يتم تفعيل آلية الحصول على موافقة المستخدم (يُطلب التأكيد)
✅ تستمر الجلسة في جميع الطلبات
✅ لا توجد أخطاء في المصادقة
✅ لا توجد مهلات في الاتصال
في حال مواجهة أخطاء:
- يُرجى التأكّد من ضبط متغيّرات البيئة بشكلٍ صحيح
- تأكَّد من تفعيل واجهات برمجة التطبيقات:
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، يمكنك اختباره مباشرةً في المتصفّح:
- انتقِل إلى عنوان URL للخدمة (المتوفّر في مخرجات عملية النشر)
- ستظهر لك واجهة الويب الخاصة بـ ADK. اختَر وكيلك من القائمة المنسدلة.
- بدء مساهمة تجريبية:
I want to donate $50 to a children's education charity
- مراقبة مسار التنفيذ:
- يعثر ShoppingAgent على المؤسسات الخيرية ويحفظ نيتك
- ينشئ MerchantAgent تفويض سلة التسوّق
- ينشئ CredentialsProvider تفويضًا بتحصيل الدفعات ويطلب التأكيد
- بعد التأكيد، تتم معالجة الدفعة
- تأكَّد من أنّ الردّ يتضمّن ما يلي:
- اقتراحات المؤسسات الخيرية
- طلب تأكيد
- رسالة نجاح بعد الموافقة
تحديد المشاكل وحلّها
المشاكل الشائعة
المشكلة: 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
✅ مراجعة إعدادات برنامج تضمين Agent Engine
✅ نشر نظام التبرّع الموثوق به في Agent Engine (إجراء يُنصح به)
✅ تفعيل دمج Cloud Trace مع --trace_to_cloud
✅ التأكّد من إمكانية الوصول إلى الوكيل وعمله بشكل صحيح
✅ إنشاء الأساس لمسارات المساءلة في الوحدة 9
في الوحدة التالية، سنوضّح بالتفصيل ما تتيحه هذه العلامة: رؤية كاملة لكل مساهمة، وكل لحظة موافقة، وكل خطوة في سلسلة بيانات الاعتماد.
9. إمكانية تتبّع البيانات


في الوحدة 1، تعرّفت على مشكلة أساسية: عندما يتعامل وكيل الذكاء الاصطناعي مع الأموال، كيف يمكنك إثبات ما حدث؟
يمكن للمستخدم المطالبة بما يلي:
- "لم أختَر هذه المؤسسة الخيرية"
- "لم أسمح بإجراء هذه الدفعة"
- "تم تحصيل رسوم مني بدون موافقتي"
في نظام الذكاء الاصطناعي التقليدي الذي يعمل كصندوق أسود، لن يكون لديك طريقة لإثبات العكس. لكن نظام التبرّع الموثوق به مختلف. في الوحدة 8، نشرت التطبيق باستخدام العلامة --trace_to_cloud، ما يعني أنّ كل مساهمة تنشئ الآن سجلّ تدقيق كاملاً ومحميًا من التلاعب في Cloud Trace.
تعلّمك هذه الوحدة كيفية قراءة هذه الآثار واستخدامها كأدلة. سيتم شرح كيفية:
- التنقّل في Cloud Trace Explorer للعثور على آثار الإنتاج
- قراءة العرض الانحداري لطلبات الشبكة لفهم مسار التنفيذ
- العثور على سلسلة بيانات الاعتماد (النية ← سلة التسوّق ← تفويضات بتحصيل الدفعات)
- تحديد لحظات الموافقة باستخدام إثبات الطابع الزمني
- استخدام عمليات التتبُّع لحلّ النزاعات
- تصدير بيانات التتبُّع لأغراض الامتثال وعمليات التدقيق
هذا ما يميّز الأنظمة الموثوقة عن الأنظمة الفعّالة ولكن غير الواضحة: القدرة على إثبات ما حدث بدقة جنائية.
فهم عمليات التتبّع والامتدادات
قبل عرض بيانات التتبُّع في Cloud Trace، عليك فهم ما تبحث عنه.
ما هو "مسار التطوير"؟
التتبُّع هو المخطط الزمني الكامل لتعامل الوكيل مع طلب واحد. وهي تسجّل كل ما يحدث من لحظة إرسال المستخدم لطلب البحث إلى حين تقديم الردّ النهائي.
يعرض كل تتبُّع ما يلي:
- إجمالي مدة الطلب
- جميع العمليات التي تم تنفيذها
- كيفية ارتباط العمليات ببعضها (علاقات رئيسية-فرعية)
- وقت بدء كل عملية وانتهائها
- حالة النجاح أو الفشل
بالنسبة إلى وكيل المؤسسة الخيرية: تتبُّع واحد = مسار تبرُّع كامل من "أريد التبرّع" إلى "تم الدفع بنجاح".
ما هو Span؟
يمثّل النطاق وحدة عمل واحدة ضمن عملية تتبُّع. يمكنك اعتبار الامتدادات بمثابة اللبنات الأساسية للتتبُّع.
أنواع النطاقات الشائعة في نظام التبرّع:
نوع 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
لنلقِ نظرة الآن على عمليات التتبُّع الفعلية من الوكيل الذي تم نشره.
الانتقال إلى Cloud Trace
- افتح Google Cloud Console: console.cloud.google.com
- اختَر مشروعك من القائمة المنسدلة في أعلى الصفحة (من المفترض أن يكون محدّدًا مسبقًا إذا كنت تعمل عليه)
- انتقِل إلى Cloud Trace Explorer:
- في الشريط الجانبي الأيمن، انتقِل إلى قسم إمكانية تتبّع البيانات
- انقر على تتبُّع
- أو استخدِم الرابط المباشر: console.cloud.google.com/traces/list
ما الذي تنظر إليه؟
يعرض Trace Explorer قائمة بجميع عمليات التتبُّع من مشروعك:
العمود | ما يعرضه التقرير |
الطلب | طريقة HTTP ونقطة النهاية (لطلبات البيانات من واجهة برمجة التطبيقات) |
وقت البدء | وقت بدء الطلب |
وقت الاستجابة | إجمالي مدة الطلب |
Spans | عدد العمليات في التتبُّع |
يمثّل كل صف طلبًا واحدًا كاملاً إلى وكيلك المنشور.
إنشاء عمليات تتبُّع تجريبية (إذا لزم الأمر)
إذا لم تظهر لك أي آثار بعد، قد تكون القائمة فارغة للأسباب التالية:
- لم يتم إرسال أي طلبات إلى وكيلك الذي تم نشره بعد
- يستغرق ظهور عمليات التتبُّع من دقيقة إلى دقيقتَين بعد إرسال الطلب
إنشاء تتبُّع تجريبي:
إذا نشرت التطبيق على Cloud Run باستخدام واجهة المستخدم، انتقِل إلى عنوان URL الخاص بالخدمة وأكمِل عملية المساهمة في المتصفّح.
إذا نشرت التطبيق في Agent Engine، شغِّل النص البرمجي للاختبار من الوحدة 8:
python scripts/test_deployed_agent.py
انتظِر لمدة دقيقة أو دقيقتين، ثم أعِد تحميل صفحة Cloud Trace Explorer. من المفترض أن تظهر لك الآن عمليات التتبُّع.
فلترة بيانات التتبُّع
استخدِم خيارات الفلترة في أعلى الصفحة للعثور على عمليات تتبُّع محدّدة:
- النطاق الزمني: غيِّر من "آخر ساعة" إلى "آخر 24 ساعة" إذا لزم الأمر
- الحد الأدنى لوقت الاستجابة / الحد الأقصى لوقت الاستجابة: يمكنك الفلترة حسب الطلبات البطيئة
- فلتر الطلبات: البحث حسب عمليات محدّدة (مثل "DonationPipeline")
في هذه الوحدة، ركِّز على عمليات التتبّع ذات المدد الأطول (أكثر من 5 ثوانٍ)، لأنّها تمثّل عمليات مساهمة كاملة ينفّذها الوكلاء الثلاثة.
الخطوة 2: فحص عملية تبرع كاملة
انقر على أي تتبُّع في القائمة لفتح العرض الانحداري لطلبات الشبكة. هذا هو المكان الذي ستقضي فيه معظم وقتك في تحليل سلوك الوكيل.
فهم العرض الانحداري لطلبات الشبكة
"العرض الانحداري لطلبات الشبكة" هو مخطط Gantt يعرض المخطط الزمني الكامل للتنفيذ:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Timeline (horizontal = time) →
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
invocation ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 8.2s
agent_run: CharityAdvisor ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 8.1s
agent_run: DonationPipeline ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 7.9s
agent_run: ShoppingAgent ▓▓▓▓▓▓ 2.1s
call_llm: gemini-2.5-flash ▓▓▓▓ 1.2s
execute_tool: find_charities ▓▓ 0.5s
execute_tool: save_user_choice ▓ 0.3s
agent_run: MerchantAgent ▓▓▓ 1.8s
call_llm: gemini-2.5-flash ▓▓ 0.9s
execute_tool: create_cart_mandate ▓ 0.7s
agent_run: CredentialsProvider ▓▓▓▓▓▓▓▓ 4.0s
call_llm: gemini-2.5-flash ▓▓ 0.8s
execute_tool: create_payment_mandate ▓▓▓▓▓ 3.0s [CONSENT]
قراءة الرسم البياني
يمثّل كل شريط فترة زمنية:
- الموضع الأفقي: وقت بدء الحدث
- المدة: الوقت الذي استغرقه النشاط
- المسافة البادئة: تعرض العلاقات بين العناصر الرئيسية والفرعية
- اللون: عادةً ما يكون أزرق في الحالات العادية، وأحمر في حال حدوث أخطاء
الملاحظات الرئيسية من هذا التتبُّع النموذجي:
✅ المدة الإجمالية: 8.2 ثانية
✅ التنفيذ المتسلسل: اكتملت مهمة ShoppingAgent قبل بدء مهمة MerchantAgent
✅ اكتملت مهمة MerchantAgent
before
تم بدء CredentialsProvider
✅ الموافقة كانت أطول عملية: 3.0 ثوانٍ لـ create_payment_mandate (لأنّها انتظرت تأكيد المستخدم)
✅ طلبات النموذج اللغوي الكبير مرئية: قدّم كل وكيل طلبًا واحدًا إلى Gemini
✅ تم تسجيل طلبات الأدوات: تم تنفيذ جميع الأدوات الست بنجاح
يعرض لك هذا الرسم البياني على الفور الوقت المستغرَق وترتيب تنفيذ العمليات.
انقر على فترة زمنية للاطّلاع على التفاصيل
انقر على الفترة invocation (الفترة الجذرية في الأعلى). في اللوحة اليسرى، ستظهر لك سمات تفصيلية:
{
"http.method": "POST",
"http.status_code": 200,
"http.url": "https://charity-advisor-xyz.a.run.app/api/run",
"user_id": "test_user_123",
"session_id": "4857885913439920384",
"trace_id": "a1b2c3d4e5f6...",
"span_id": "1234567890abcdef"
}
توفّر هذه السمات سياقًا حول الطلب بأكمله.
الخطوة 3: العثور على سلسلة بيانات الاعتماد
يستخدم نظامك الموثوق به سلسلة بيانات اعتماد لإثبات التفويض في كل خطوة:
IntentMandate (User chose charity)
↓
CartMandate (Merchant created cart, signed IntentMandate)
↓
PaymentMandate (Payment provider created payment, signed CartMandate)
لنبحث عن كل تفويض في التتبُّع.
العثور على IntentMandate
انقر على النطاق execute_tool: save_user_choice (ضمن ShoppingAgent).
في لوحة السمات، سيظهر لك ما يلي:
{
"tool.name": "save_user_choice",
"tool.input.charity_name": "Save the Children",
"tool.input.amount": 50,
"tool.output.status": "success",
"tool.output.intent_mandate": {
"charity_name": "Save the Children",
"amount": 50,
"timestamp": "2024-11-08T15:30:12.345Z",
"signature": "a3f7b9c1d2e4..."
}
}
يثبت ذلك ما يلي:
- ✅ اختار المستخدم "Save the Children"
- ✅ المبلغ هو 50 دولار أمريكي
- ✅ تم تسجيل الاختيار في الساعة 15:30:12 بالتوقيت العالمي المنسق
- ✅ تم إنشاء التوقيع (في مرحلة الإنتاج، سيكون هذا التوقيع مشفّرًا)
أصبح IntentMandate الآن في حالة الجلسة ومتاحًا للوكلاء اللاحقين.
العثور على CartMandate
انقر على النطاق 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 بالتوقيت العالمي المنسق (بعد 2.4 ثانية من نية الشراء)
يشير CartMandate الآن إلى IntentMandate، ما يشكّل السلسلة.
العثور على PaymentMandate
انقر على الفترة الزمنية execute_tool: create_payment_mandate (ضمن CredentialsProvider).
في لوحة السمات:
{
"tool.name": "create_payment_mandate",
"tool.input.cart_mandate": {
"cart_id": "cart_7893",
"intent_signature": "a3f7b9c1d2e4...",
"cart_signature": "e8f2a9b3c7d1..."
},
"tool.confirmation_required": true,
"tool.confirmation_timestamp": "2024-11-08T15:30:17.891Z",
"tool.user_response": "CONFIRMED",
"tool.wait_duration_ms": 29168,
"tool.output.status": "success",
"tool.output.payment_mandate": {
"payment_id": "pay_9821",
"cart_signature": "e8f2a9b3c7d1...",
"payment_signature": "b4c9e2a7f8d3...",
"timestamp": "2024-11-08T15:30:47.059Z"
}
}
يثبت ذلك السلسلة الكاملة:
- ✅ تلقّى CredentialsProvider تفويض CartMandate (يظهر ذلك في الإدخال)
- ✅ تشير الدفعة إلى توقيع CartMandate (رابط السلسلة)
- ✅ كان التأكيد مطلوبًا (
confirmation_required: true) - ✅ أكّد المستخدم في الساعة 15:30:17 بالتوقيت العالمي المنسق
- ✅ انتظر النظام لمدة 29.2 ثانية حتى يتخذ المستخدم قرارًا
- ✅ تم إنشاء الدفعة بعد التأكيد (الطابع الزمني: 15:30:47)
تصوُّر السلسلة
يثبت التتبّع أنّ سلسلة بيانات الاعتماد تم تنفيذها بشكل صحيح:
15:30:12 UTC → IntentMandate created (signature: a3f7...)
↓
15:30:14 UTC → CartMandate created (references: a3f7...)
↓
15:30:17 UTC → User consent requested
↓
15:30:47 UTC → PaymentMandate created (references: e8f2...)
ويشير كل تفويض إلى توقيع التفويض السابق. وهذا مقاوم للتلاعب، إذ يمكنك التحقّق من السلسلة من خلال التأكّد من تطابق التوقيعات.
الخطوة 4: تحليل الأداء والمعوقات
لا يقتصر دور Cloud Trace على إثبات ما حدث، بل يوضّح لك أيضًا أين يتم قضاء الوقت لتتمكّن من تحسين الأداء.
تحديد المسار الحرج
في العرض الانحداري لطلبات الشبكة، ابحث عن أطول فترات في الحزمة العمودية. وتمثّل هذه المؤثِّرات السلبية على الأداء.
من تتبُّع المثال:
Total: 8.2 seconds
Breakdown:
- ShoppingAgent: 2.1s (26%)
- MerchantAgent: 1.8s (22%)
- CredentialsProvider: 4.0s (49%) ← Bottleneck
- Other overhead: 0.3s (3%)
إحصاءات مهمة: يمثّل CredentialsProvider نسبة %49 من إجمالي الوقت. لماذا؟
انتقِل إلى فترة CredentialsProvider:
CredentialsProvider: 4.0s
- call_llm: 0.8s (20%)
- create_payment_mandate: 3.0s (75%) ← User consent wait
- Other: 0.2s (5%)
يُعدّ التأخير لمدة 3 ثوانٍ متوقّعًا وجيدًا، فهو الوقت الذي يستغرقه المستخدم في التفكير قبل التأكيد. هذه ليست مشكلة في الأداء، بل هي دليل على الموافقة المدروسة.
تتبُّع تكاليف النماذج اللغوية الكبيرة
انقر على أيّ عنصر 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 من عمليات التتبُّع على أخطاء:
- انتقِل إلى Cloud Monitoring
- انقر على "التنبيه" ← "إنشاء سياسة"
- الإعداد:
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 ✅ استخدام الآثار كدليل لحلّ النزاعات
✅ تحليل الأداء لتحديد المؤثّرات السلبية
✅ تتبُّع تكاليف النماذج اللغوية الكبيرة على مستوى دقيق
التأثير الذي يحدثه ذلك
لِنقارن بين نظامَين يتعاملان مع الشكوى نفسها: "لم أسمح بهذا الإجراء":
نظام بدون إمكانية تتبّع البيانات
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. رحلتك نحو المستقبل
ما أنشأته
بدأنا ورشة العمل هذه بسؤال: "كيف يمكنني إنشاء وكلاء ذكاء اصطناعي يمكنني الوثوق بهم في التعامل مع الأموال؟"
لديك الآن الإجابة.
نقطة البداية (الوحدة 3):
simple_agent = Agent(
model="gemini-2.5-flash",
instruction="Find charities and donate",
tools=[google_search]
)
محتوى الوحدة الحالية (الوحدة 10):
- ✅ ثلاثة وكلاء متخصّصين بأدوار منفصلة
- ✅ ثلاث بيانات اعتماد يمكن التحقّق منها (النية ← سلة التسوّق ← تفويضات بتحصيل الدفعات)
- ✅ سلسلة بيانات اعتماد كاملة مع التحقّق من انتهاء الصلاحية في كل خطوة
- ✅ آلية الحصول على موافقة المستخدم الصريحة مع إثبات الطابع الزمني
- ✅ النشر في بيئة الإنتاج في Agent Engine مع إمكانية تتبّع البيانات
- ✅ مسار مساءلة كامل في Cloud Trace
- ✅ أدلة جنائية لحل النزاعات
الفرق بين ورشة العمل والإنتاج
يعرض نظامك البنية والأنماط الصحيحة، ولكنّه يستخدم تبسيطات تعليمية يجب ترقيتها لتناسب الأموال الحقيقية والمستخدمين الحقيقيين.
إليك ما تم تبسيطه وما يتطلبه الإنتاج:
المكوّن | تنفيذ ورشة العمل | متطلبات الإنتاج |
التوقيعات | تجزئات SHA-256 (عددها | توقيعات تشفير حقيقية باستخدام البنية التحتية للمفتاح العام (PKI) أو رمز JWT مع مفاتيح خاصة |
معالجة الدفعات | العائدات التي تمّت محاكاتها (العلامة | التكامل مع واجهات برمجة التطبيقات الخاصة بالدفع الفعلي (Stripe وPayPal وSquare) |
مصادقة المستخدم | الثقة الضمنية (لا يلزم تسجيل الدخول) | بروتوكول OAuth 2.0 أو WebAuthn أو إدارة الجلسات |
إدارة البيانات السرية | متغيرات البيئة في ملف | Google Secret Manager أو Cloud KMS مع التشفير |
قاعدة بيانات المؤسسات الخيرية | ملف JSON وهمي يحتوي على 9 مؤسسات خيرية | الربط المباشر بواجهة برمجة التطبيقات (أداة البحث عن المؤسسات المعفاة من الضرائب التابعة لدائرة الإيرادات الداخلية الأمريكية، واجهة برمجة التطبيقات Charity Navigator) |
معالجة الأخطاء | try-catch أساسية مع رسائل خطأ | منطق إعادة المحاولة باستخدام خوارزمية الرقود الأسي الثنائي، وقواطع الدائرة، وقوائم انتظار الرسائل غير الصالحة |
الاختبار | التحقّق يدويًا من خلال النصوص البرمجية | حزمة اختبارات شاملة للوحدات/الدمج/الاختبارات الشاملة مع التكامل المستمر/النشر المستمر |
استمرار الجلسة | في الذاكرة (محليًا) أو تلقائيًا (Agent Engine) | قاعدة بيانات إنتاجية مع نُسخ احتياطية وإمكانية استعادة البيانات في حالات الكوارث |
الحدّ من المعدّل | بلا (بيئة تعليمية) | حدود المعدّل لكل مستخدم، والتحكّم في معدّل نقل البيانات استنادًا إلى عنوان IP، ورصد إساءة الاستخدام |
الأنماط المعمارية الرئيسية التي أتقنتها
الأنماط التي تعلّمتها في ورشة العمل هذه هي أنماط إنتاج. لا تشكّك في قدراتهم.
فصل الأدوار (المبدأ الأول من AP2)
يؤدي كل وكيل مهمة واحدة واضحة، ويطّلع فقط على ما يحتاج إليه. إذا تم اختراق أحد الوكلاء، لن يتمكّن المهاجم من الوصول إلى بيانات الوكلاء الآخرين. يحدّ هذا من نطاق التأثير.
أنظمة الإنتاج التي تستخدم هذا النموذج: معالجة الدفعات، وسير عمل المستندات، وسلاسل الموافقة، والنماذج المتعدّدة الخطوات التي تتضمّن بوابات تحقّق
بيانات الاعتماد القابلة للتحقّق (المبدأ رقم 2 من AP2)
لكل بيانات اعتماد وقت انتهاء صلاحية، وتشير إلى بيانات الاعتماد السابقة، وتتطلّب التحقّق منها قبل الخطوة التالية. يؤدي ذلك إلى إنشاء سلسلة تدقيق واضحة للتلاعب.
قيمة الإنتاج: دليل كامل على ما حدث ومتى وبأي ترتيب. وهي ضرورية لحلّ النزاعات والامتثال التنظيمي.
الموافقة الصريحة (المبدأ رقم 3 من AP2)
طابع زمني يثبت موافقة المستخدم على الإجراء لا يمكن الاعتراض عليه.
قيمة الإنتاج: متطلبات قانونية للمعاملات المالية يحمي كلاً من المستخدم والشركة.
التنسيق التسلسلي (نمط ADK)
يفرض ترتيب التنفيذ الصحيح. يمنع تخطي الخطوات. يضمن هذا الخيار أن يرى كل وكيل مخرجات الوكيل السابق.
قيمة الإنتاج: مثالية للأنظمة التي تتطلّب مشاركة بشرية ويتوقّع المستخدمون فيها الحصول على نتائج فورية. هذا هو النمط المناسب لعمليات التبرّع والدفع وسلاسل الموافقة.
إمكانية تتبّع البيانات بالكامل (OpenTelemetry وCloud Trace)
يتم تلقائيًا تسجيل كل قرار، واستدعاء أداة، ولحظة موافقة، وعملية تسليم بيانات الاعتماد.
قيمة الإنتاج: أدلة جنائية للنزاعات بيانات تحسين الأداء سجلّات تدقيق الامتثال تصحيح أخطاء الإنتاج بدقة
مراجع للتعلُّم المتواصل
مستندات ADK:
AP2 والمعايير ذات الصلة:
خدمات Google Cloud:
موارد التنظيف
لتجنُّب تحصيل رسوم مستمرة، احذف عملية النشر:
Agent Engine: اتّبِع الخطوات الواردة في مستندات Agent Engine
Cloud Run (في حال نشره):
gcloud run services delete charity-advisor \
--region=$GOOGLE_CLOUD_LOCATION
مستودعات التخزين:
gsutil -m rm -r gs://$GOOGLE_CLOUD_PROJECT-staging
gsutil -m rm -r gs://$GOOGLE_CLOUD_PROJECT-artifacts
رحلتك مستمرة
لقد بدأت بسؤال بسيط وأنشأت إجابة كاملة. لقد أتقنت الأنماط الأساسية لوكلاء الذكاء الاصطناعي الموثوقين. تنتقل هذه الأنماط إلى أي مجال يتعامل فيه وكلاء الذكاء الاصطناعي مع عمليات حساسة، مثل المعاملات المالية وقرارات الرعاية الصحية والمستندات القانونية وعمليات سلسلة الإمداد.
مبادئ قابلة للنقل: ويعمل نموذج الثقة.
والآن، حان الوقت لإنشاء محتوى موثوق. ❤️
