שילוב של סוכני Vertex AI עם Google Workspace

1. לפני שמתחילים

99afae2505f696fb.png

מה זה Vertex AI?

‫Vertex AI היא פלטפורמת הפיתוח המאוחדת של Google Cloud, שמאפשרת לפתח, לפרוס ולהתאים לעומס (scaling) אפליקציות וסוכני AI ברמה שמתאימה לארגונים. היא מספקת למפתחים ולמדעני נתונים את הכלים המתוחכמים שדרושים כדי לתכנן Agentic Workflows בהתאמה אישית, שמשולבים באופן עמוק בתשתית בקנה מידה גלובלי.

  • גישה ל-Model Garden: בוחרים מתוך יותר מ-150 מודלים בסיסיים, כולל כל משפחת Gemini, מודלים של צד שלישי ומודלים ייעודיים בקוד פתוח, כדי למצוא את המודל המתאים למשימות ספציפיות של הנציג.
  • תכנון תזמור מורכב: Vertex AI מספק את המסגרת לתכנון סוכנים אוטונומיים שמשתמשים בהסקת מסקנות כדי לתכנן, לבצע משימות בכמה שלבים ולקרוא לממשקי API חיצוניים.
  • עיגון ברמה שמתאימה לארגונים: אפשר לקשר את הנציגים לנתונים עסקיים עדכניים, כולל RAG (יצירת מידע מבוסס-אחזור) עם ביצועים גבוהים, כדי למנוע הזיות ולהבטיח דיוק עובדתי.
  • ‫DevOps: שילוב חלק של פיתוח הסוכנים בתהליכי CI/CD קיימים, באמצעות ערכות SDK, ממשקי API וכלי הערכה מתקדמים למדידת הביצועים והבטיחות של הסוכנים בקנה מידה נרחב.
  • אבטחה ברמה תעשייתית: ב-Vertex AI, נתוני הלקוחות שמשמשים לאימון או לעיגון נשארים פרטיים, מוצפנים ותואמים לדרישות הגלובליות לגבי מיקום אחסון הנתונים.
  • תשתית אופטימלית: אפשר להרחיב בקלות את עומסי העבודה של הסוכנים באשכולות ה-TPU וה-GPU המובילים של Google, וכך להבטיח ביצועים עם זמן אחזור קצר גם באפליקציות הגלובליות הכי תובעניות.

127f2ed7d484722c.png

מה זה Google Workspace?

‫Google Workspace הוא אוסף של פתרונות מבוססי-ענן לפרודוקטיביות ולשיתוף פעולה, שמיועדים לאנשים פרטיים, לבתי ספר ולעסקים:

  • תקשורת: שירותי אימייל מקצועיים (Gmail), שיחות ועידה בווידאו (Meet) והעברת הודעות בצוות (Chat).
  • יצירת תוכן: כלים לכתיבת מסמכים (Docs), ליצירת גיליונות אלקטרוניים (Sheets) ולעיצוב מצגות (Slides).
  • ארגון: יומנים משותפים (יומן Google) ורישום הערות דיגיטליות (Keep).
  • אחסון: מקום מרכזי בענן לשמירה ולשיתוף של קבצים באופן מאובטח (Drive).
  • ניהול: אמצעי בקרה לאדמינים לניהול משתמשים והגדרות אבטחה (מסוף Admin ב-Workspace).

אילו סוגים של שילובים בהתאמה אישית?

‫Google Workspace ו-Vertex AI יוצרים לולאת משוב יעילה שבה Workspace מספק נתונים בזמן אמת והקשר לשיתוף פעולה, ו-Vertex AI מספק את המודלים, את החשיבה האקטיבית ואת התיאום שנדרשים כדי להפוך תהליכי עבודה חכמים לאוטומטיים.

  • קישוריות חכמה: מאגרי נתונים, ממשקי API ושרתי MCP (בניהול Google ובהתאמה אישית) מאפשרים לסוכנים לגשת בצורה מאובטחת וחלקה לנתוני Workspace ולבצע פעולות בשם המשתמשים.
  • סוכנים בהתאמה אישית: באמצעות כלים לעיצוב בלי צורך בתכנות או מסגרות לפיתוח קוד, צוותים יכולים ליצור סוכנים מיוחדים שמבוססים על נתונים ופעולות ב-Workspace שמנוהלים על ידי אדמינים.
  • שילוב מובנה: תוספים ל-Workspace מגשרים על הפער בין מערכות AI לבין אפליקציות כמו Chat ו-Gmail, באמצעות רכיבים ייעודיים של ממשק המשתמש או תהליכים ברקע. כך הסוכנים יכולים לעזור למשתמשים בדיוק איפה שהם נמצאים, באופן מיידי ובהתאם להקשר.

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

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

אם אתם רוצים לבצע את כל השלבים בסביבה שלכם, תצטרכו:

מה תפַתחו

ב-Codelab הזה נבנה שלושה פתרונות עם סוכני Vertex AI שמשולבים באופן הדוק ב-Google Workspace. הם ידגימו דפוסי ארכיטקטורה שאפשר להשתמש בהם כדי לקיים אינטראקציה עם נתונים, פעולות וממשקי משתמש.

אפליקציית חיפוש מבוסס-Vertex AI

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

  • מודל: Gemini.
  • נתונים ופעולות: מאגרי נתונים של Vertex AI ל-Google Workspace (יומן, Gmail, ‏Drive).
  • מארח הסוכן: חיפוש מבוסס-Vertex AI.
  • ממשק משתמש: ווידג'ט אינטרנט של חיפוש מבוסס-Vertex AI.

d276ff8e2b9d0ddf.png

סוכן בהתאמה אישית

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

  • מודל: Gemini.
  • נתונים ופעולות: מאגרי נתונים של Vertex AI ל-Google Workspace (יומן, Gmail, ‏Drive), שרת Model Context Protocol‏ (MCP) של חיפוש מבוסס-Vertex AI בניהול Google, פונקציית כלי בהתאמה אישית לשליחת הודעות צ'אט ב-Google Chat (באמצעות Google Chat API).
  • כלים ליצירת סוכנים: ערכה לפיתוח סוכנים (ADK).
  • מארח הסוכן: Vertex AI Agent Engine.
  • ‫ממשק משתמש: ADK Web.

145f47f45332e6be.png293ec4d3e2bb6a0.png

תוסף Agent ל-Google Workspace

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

  • מודל: Gemini.
  • נתונים ופעולות: מאגרי נתונים של Vertex AI ל-Google Workspace (יומן, Gmail, ‏Drive), שרת Model Context Protocol‏ (MCP) של חיפוש מבוסס-Vertex AI בניהול Google, פונקציית כלי בהתאמה אישית לשליחת הודעות צ'אט ב-Google Chat (באמצעות Google Chat API).
  • כלים ליצירת סוכנים: ערכה לפיתוח סוכנים (ADK).
  • מארח הסוכן: Vertex AI Agent Engine.
  • ממשק משתמש: תוסף של Google Workspace ל-Chat ול-Gmail (אפשר להרחיב אותו בקלות ליומן, ל-Drive, ל-Docs, ל-Sheets ול-Slides).
  • תוסף ל-Google Workspace: ‏Apps Script, ממשקי Vertex AI Agent Engine API, הקשר (הודעת Gmail שנבחרה).

172da43f310a0579.png840b494aa5eaa1ef.png

מה תלמדו

  • נקודות השילוב בין חיפוש מבוסס-Vertex AI ל-Google Workspace שמאפשרות נתונים ופעולות.
  • האפשרויות ליצירת סוכנים בהתאמה אישית שמתארחים ב-Vertex AI.
  • הדרכים שבהן המשתמשים יכולים לגשת לסוכנים, כמו ווידג'ט האינטרנט של חיפוש מבוסס-Vertex AI ואפליקציות של Google Workspace.

גישה קלה ל-Codelab הזה

vRcm5FeCAx4ZxxM.png

2. הגדרה

לפני שיוצרים פתרונות, צריך להפעיל את הגדרות האפליקציות של Vertex AI בפרויקט, להפעיל את ממשקי ה-API הנדרשים וליצור את מאגרי הנתונים של Vertex AI Workspace.

בדיקת המושגים

אפליקציית Vertex AI

אפליקציית Vertex AI היא פתרון מנוהל מקצה לקצה ב-Google Cloud, שמשלב מודלים של למידת מכונה (כמו סוכני AI גנרטיבי או מנועי חיפוש) עם נתונים ארגוניים וכלים מיוחדים כדי לבצע משימות מורכבות כמו חיפוש סמנטי, יצירת תוכן או אינטראקציה אוטומטית עם לקוחות.

מאגר נתונים של Vertex AI

מאגר נתונים ב-Vertex AI הוא ישות שמכילה את הנתונים שהועברו ממקור נתונים של צד ראשון כמו Google Workspace או מאפליקציות של צד שלישי כמו Jira או Shopify. מאגרי נתונים שמכילים נתונים מאפליקציות של צד שלישי נקראים גם מחברי נתונים.

הפעלת ההגדרות של אפליקציות Vertex AI

מפעילים את ההגדרות של Vertex AI Applications כדי לאפשר יצירת סוכנים.

פותחים את מסוף Google Cloud בכרטיסייה חדשה ופועלים לפי השלבים הבאים:

  1. בוחרים את הפרויקט הרצוי.
  2. בשדה החיפוש של Google Cloud, עוברים אל AI Applications.

  1. קוראים את התנאים, מאשרים אותם ולוחצים על המשך והפעלת ה-API.
  2. נכנסים להגדרות.
  3. בכרטיסייה Authentication, עורכים את global.

93b0cc6ed63fba0c.png

  1. בוחרים באפשרות Google Identity ולוחצים על שמירה.

5c01b4cbeebaa93b.png

הפעלת ממשקי ה-API

כדי להשתמש במאגרי הנתונים של Vertex AI Workspace, צריך להפעיל את ממשקי ה-API הבאים:

  1. במסוף Google Cloud, מפעילים את ממשקי ה-API של יומן Google, ‏Gmail ואנשי קשר:

3877dcaa56624d0b.png

  1. לוחצים על תפריט ☰ > ממשקי API ושירותים > ממשקי API ושירותים מופעלים ומוודאים ש-Google Calendar API, ‏Gmail API ו-People API מופיעים ברשימה.

.

יצירת מאגרי נתונים

יוצרים את מאגר הנתונים ב-Google Drive:

  1. במסוף Google Cloud, נכנסים לדף AI Applications ואז ל-מאגרי נתונים.

  1. לוחצים על ‎+ Create data store.
  2. בקטע מקור, מתחת ל-Google Drive, לוחצים על בחירה.

6939363368bde36d.png

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

5044243322acec9e.png

  1. בקטע Configuration, מגדירים את Data connector name ל-drive, קוראים את החיובים שעשויים לחול, מאשרים אותם ולוחצים על Continue.

1f5deb1aeecee983.png

  1. בקטע תמחור, בוחרים את מודל התמחור הרצוי ולוחצים על יצירה. ב-Codelab הזה מומלץ להשתמש בתמחור כללי.
  2. המערכת תפנה אתכם אוטומטית לדף Data Stores, שבו תוכלו לראות את מאגר הנתונים החדש שנוסף.

יוצרים את מאגר הנתונים של יומן Google:

  1. לוחצים על ‎+ Create data store.
  2. בקטע Source (מקור), מחפשים את יומן Google ולוחצים על Select (בחירה).
  3. בקטע פעולות, לוחצים על דילוג.
  4. בקטע Configuration, מגדירים את שם מחבר הנתונים לערך calendar.
  5. לוחצים על יצירה.
  6. המערכת תפנה אתכם אוטומטית לדף Data Stores, שבו תוכלו לראות את מאגר הנתונים החדש שנוסף.

יוצרים את מאגר הנתונים של Google Gmail:

  1. לוחצים על + מאגר נתונים חדש.
  2. במקור, מחפשים את Google Gmail ולוחצים על בחירה.
  3. בקטע פעולות, לוחצים על דילוג.
  4. בקטע Configuration, מגדירים את שם מחבר הנתונים לערך gmail.
  5. לוחצים על יצירה.
  6. המערכת תפנה אתכם אוטומטית לדף Data Stores, שבו תוכלו לראות את מאגר הנתונים החדש שנוסף.

3. אפליקציית חיפוש מבוסס-Vertex AI

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

  • מודל: Gemini.
  • נתונים ופעולות: מאגרי נתונים של Vertex AI ל-Google Workspace (יומן, Gmail, ‏Drive).
  • מארח הסוכן: חיפוש מבוסס-Vertex AI.
  • ממשק משתמש: ווידג'ט אינטרנט של חיפוש מבוסס-Vertex AI.

בדיקת המושגים

אפליקציית חיפוש מבוסס-Vertex AI

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

ווידג'ט אינטרנט של חיפוש מבוסס-Vertex AI

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

גרסת טרום-השקה (Preview) של חיפוש מבוסס-Vertex AI

גרסת טרום-ההשקה של חיפוש מבוסס-Vertex AI היא סביבת בדיקה מובנית במסוף Google Cloud, שמאפשרת למפתחים לאמת את הגדרות החיפוש ואת התשובות הגנרטיביות לפני שהם פורסים את אותן הגדרות בווידג'ט אינטרנט של חיפוש מבוסס-Vertex AI שמוכן לייצור.

בדיקת ארכיטקטורת הפתרון

1f337dc91da74391.png

יצירת אפליקציה

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

במסוף Cloud, פותחים את AI Applications > Apps ופועלים לפי השלבים הבאים:

  1. לוחצים על + יצירת אפליקציה.
  2. בקטע סוג, מתחת לאפשרות חיפוש בהתאמה אישית (כללי), לוחצים על יצירה.

9714a5fff49b5e1b.png

  1. בקטע Configuration, מסמנים את האפשרויות Enterprise edition features ו-Generative Responses אחרי שבודקים את המחירים ומאשרים אותם.
  2. מגדירים את App name ל-codelab.
  3. המערכת יוצרת מזהה על סמך השם ומציגה אותו מתחת לשדה. מעתיקים את המזהה.
  4. מגדירים את שם החברה לערך Codelab.
  5. מגדירים את Multi-region לערך global (Global).
  6. לוחצים על המשך.

327702cd837cbb18.png

  1. בקטע נתונים, בוחרים את מאגרי הנתונים Drive,‏ Gmail ויומן, ואז לוחצים על המשך.

5745607f3c43d5c0.png

  1. בקטע תמחור, בוחרים את מודל התמחור הרצוי ולוחצים על יצירה. ב-Codelab הזה מומלץ להשתמש בתמחור כללי.
  2. האפליקציה נוצרת ואתם מופנים באופן אוטומטי אל AI Applications > Apps > codelab > App overview.
  3. עוברים אל מאגרי נתונים מקושרים.
  4. אחרי כמה דקות, הסטטוס של כל מאגרי הנתונים המחוברים אמור להיות Active.

d53ed9d9d1ced955.png

הגדרת ווידג'ט לאתר

להגדיר את המראה וההתנהגות של ווידג'ט חיפוש Google.

  1. עוברים אל Configurations (הגדרות).
  2. בכרטיסייה ממשק משתמש, מגדירים את סוג החיפוש לחיפוש עם שאלות המשך, ואז לוחצים על שמירה ופרסום.

af1ca3bd78e1cb4f.png

להורדת האפליקציה

בודקים את אפליקציית החיפוש ישירות במסוף Google Cloud.

  1. עוברים אל Preview (תצוגה מקדימה), והווידג'ט לאתר מוצג.
  2. בצ'אט, מקלידים Do I have any meetings today? ולוחצים על enter.
  3. בצ'אט, מקלידים Did I receive an email on March 1st 2026? ולוחצים על enter.
  4. בצ'אט, מקלידים Give me the title of the latest Drive file I created ולוחצים על enter.

d276ff8e2b9d0ddf.png

4. סוכן בהתאמה אישית

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

  • מודל: Gemini.
  • נתונים ופעולות: מאגרי נתונים של Vertex AI ל-Google Workspace (יומן, Gmail, ‏Drive), שרת Model Context Protocol‏ (MCP) של חיפוש מבוסס-Vertex AI בניהול Google, פונקציית כלי בהתאמה אישית לשליחת הודעות צ'אט ב-Google Chat (באמצעות Google Chat API).
  • כלים ליצירת סוכנים: ערכה לפיתוח סוכנים (ADK).
  • מארח הסוכן: Vertex AI Agent Engine.
  • ‫ממשק משתמש: ADK Web.

בדיקת המושגים

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

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

thought Model Context Protocol (MCP)

‫Model Context Protocol‏ (MCP) הוא תקן פתוח שנועד לאפשר שילוב חלק ומאובטח בין אפליקציות AI לבין מקורות נתונים או כלים שונים באמצעות ממשק אוניברסלי מסוג Plug and Play.

כלי פונקציות

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

ADK Web

‫ADK web הוא ממשק המשתמש המובנה למפתחים שמגיע עם ADK SDK כדי להקל על הפיתוח וניפוי הבאגים.

בדיקת ארכיטקטורת הפתרון

f14251cca6a19b1f.png

בדיקת קוד המקור

agent.py

הקוד הבא מבצע אימות מול Vertex AI, מאתחל את הכלים של Vertex AI Search MCP ו-Chat API ומגדיר את ההתנהגות של הנציג.

  1. אימות: מאחזר את ACCESS_TOKEN ממשתני הסביבה כדי לאמת קריאות ל-MCP וקריאות ל-API.
  2. הגדרת הכלים: הפעלת vertexai_mcp, ערכת כלים שמקשרת לשרת Model Context Protocol‏ (MCP) של חיפוש מבוסס-Vertex AI, והכלי send_direct_message. כך הסוכן יכול לחפש במאגרי הנתונים המקושרים ולשלוח הודעות צ'אט ב-Google Chat.
  3. הגדרת הנציג: מגדירה את root_agent באמצעות המודל gemini-2.5-flash. ההוראות מנחות את הנציג לתת עדיפות לשימוש בכלי החיפוש לאחזור מידע ובכלי send_direct_message לפעולות, וכך למעשה מבססות את הנציג על הנתונים של הארגון.
...
MODEL = "gemini-2.5-flash"

# Access token for authentication
ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")
if not ACCESS_TOKEN:
    raise ValueError("ACCESS_TOKEN environment variable must be set")

VERTEXAI_SEARCH_TIMEOUT = 15.0

def get_project_id():
    """Fetches the consumer project ID from the environment natively."""
    _, project = google.auth.default()
    if project:
        return project
    raise Exception(f"Failed to resolve GCP Project ID from environment.")

def find_serving_config_path():
    """Dynamically finds the default serving config in the engine."""
    project_id = get_project_id()
    engines = discoveryengine_v1.EngineServiceClient().list_engines(
        parent=f"projects/{project_id}/locations/global/collections/default_collection"
    )
    for engine in engines:
        # engine.name natively contains the numeric Project Number
        return f"{engine.name}/servingConfigs/default_serving_config"
    raise Exception(f"No Discovery Engines found in project {project_id}")

def send_direct_message(email: str, message: str) -> dict:
    """Sends a Google Chat Direct Message (DM) to a specific user by email address."""
    chat_client = chat_v1.ChatServiceClient(
        credentials=Credentials(token=ACCESS_TOKEN)
    )

    # 1. Setup the DM space or find existing one
    person = chat_v1.User(
        name=f"users/{email}",
        type_=chat_v1.User.Type.HUMAN
    )
    membership = chat_v1.Membership(member=person)
    space_req = chat_v1.Space(space_type=chat_v1.Space.SpaceType.DIRECT_MESSAGE)
    setup_request = chat_v1.SetUpSpaceRequest(
        space=space_req,
        memberships=[membership]
    )
    space_response = chat_client.set_up_space(request=setup_request)
    space_name = space_response.name
    
    # 2. Send the message
    msg = chat_v1.Message(text=message)
    message_request = chat_v1.CreateMessageRequest(
        parent=space_name,
        message=msg
    )
    message_response = chat_client.create_message(request=message_request)
    
    return {"status": "success", "message_id": message_response.name, "space": space_name}

vertexai_mcp = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url="https://discoveryengine.googleapis.com/mcp",
        timeout=VERTEXAI_SEARCH_TIMEOUT,
        sse_read_timeout=VERTEXAI_SEARCH_TIMEOUT,
        headers={"Authorization": f"Bearer {ACCESS_TOKEN}"}
    ),
    tool_filter=['search']
)

# Answer nicely the following user queries:
#  - Please find my meetings for today, I need their titles and links
#  - What is the latest Drive file I created?
#  - What is the latest Gmail message I received?
#  - Please send the following message to someone@example.com: Hello, this is a test message.

root_agent = LlmAgent(
    model=MODEL,
    name='enterprise_ai',
    instruction=f"""
        You are a helpful assistant that always uses the Vertex AI MCP search tool to answer the user's message, unless the user asks you to send a message to someone.
        If the user asks you to send a message to someone, use the send_direct_message tool to send the message.
        You MUST unconditionally use the Vertex AI MCP search tool to find answer, even if you believe you already know the answer or believe the Vertex AI MCP search tool does not contain the data.
        The Vertex AI MCP search tool accesses the user's data through datastores including Google Drive, Google Calendar, and Gmail.
        Only use the Vertex AI MCP search tool with servingConfig and query parameters, do not use any other parameters.
        Always use the servingConfig {find_serving_config_path()} while using the Vertex AI MCP search tool.
    """,
    tools=[vertexai_mcp, FunctionTool(send_direct_message)]
)

הורדת קוד המקור

כדי להתחיל, מורידים את הקוד לדוגמה לסביבה המקומית.

  1. מורידים את מאגר ה-GitHub הזה.

  1. בטרמינל, פותחים את הספרייה solutions/enterprise-ai-agent-local.

הפעלת ממשקי API

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

  1. במסוף Google Cloud, מפעילים את ממשקי ה-API של Vertex AI,‏ Cloud Resource Manager ו-Google Chat:

60bae4065338c5bf.png

  1. לוחצים על תפריט ☰ > ממשקי API ושירותים > ממשקי API ושירותים מופעלים ומוודאים ש-Vertex AI API, ‏Cloud Resource Manager API ו-Google Chat API מופיעים ברשימה.

.

הפתרון דורש הגדרה של מסך הסכמה:

  1. במסוף Google Cloud, לוחצים על תפריט ☰ > פלטפורמת Google Auth ‏> מיתוג.

  1. לוחצים על שנתחיל?
  2. בקטע App Information, מגדירים את App name ל-Codelab .
  3. בקטע User support email, בוחרים כתובת אימייל לתמיכה שאליה משתמשים יפנו אם יש להם שאלות לגבי ההסכמה שלהם.
  4. לוחצים על Next.
  5. בקטע Audience, לוחצים על Internal.
  6. לוחצים על Next.
  7. בקטע Contact Information, מזינים כתובת אימייל שאליה אפשר לשלוח התראות על שינויים בפרויקט.
  8. לוחצים על הבא.
  9. בקטע Finish, קוראים את המדיניות של Google בנושא נתוני משתמשים בשירותי API. אם אתם מסכימים, סמנו את התיבה I agree to the Google API Services: User Data Policy.
  10. לוחצים על המשך ואז על יצירה.

bb53eeb45c51d301.png

  1. ההגדרה נשמרת ואתם מופנים אוטומטית אל Google Auth Platform > Overview.

למידע נוסף, אפשר לעיין במדריך המלא בנושא הגדרת הסכמה ל-OAuth.

יצירת פרטי כניסה של לקוח OAuth

יוצרים לקוח OAuth חדש של אפליקציה למחשב כדי לאמת את המשתמש בסביבה מקומית:

  1. במסוף Google Cloud, לוחצים על תפריט ☰ > פלטפורמת Google Auth ‏> Clients.

  1. לוחצים על ‎+ Create client.
  2. ב-Application type, בוחרים באפשרות אפליקציה למחשב.
  3. מגדירים את Name לערך codelab.
  4. לוחצים על יצירה. פרטי הכניסה החדשים שנוצרו מופיעים.
  5. לוחצים על Download JSON ושומרים את הקובץ בשם client_secret.json בספרייה solutions/enterprise-ai-agent-local.

c1c9bc2f8c14dd6c.png

הפעלת חיפוש מבוסס-Vertex AI MCP

  1. בטרמינל, מריצים את הפקודה:
gcloud beta services mcp enable discoveryengine.googleapis.com \
     --project=$(gcloud config get-value project)

הגדרת אפליקציית Chat

מגדירים את הפרטים הבסיסיים של אפליקציית Google Chat.

  1. במסוף Google Cloud, מחפשים את Google Chat API בשדה החיפוש של Google Cloud, לוחצים על Google Chat API, לוחצים על ניהול ואז על הגדרה.

  1. מגדירים את שם האפליקציה ואת התיאור ל-Vertex AI.
  2. מגדירים את כתובת ה-URL של הדמות ל-https://developers.google.com/workspace/add-ons/images/quickstart-app-avatar.png.
  3. מבטלים את הבחירה באפשרות הפעלת תכונות אינטראקטיביות ולוחצים על השבתה בתיבת הדו-שיח שמופיעה.
  4. בוחרים באפשרות Log errors to Logging.
  5. לוחצים על שמירה.

952e7ebcb945f1b2.png

הרצת הסוכן ב-ADK Web

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

  1. בטרמינל, פותחים את הספרייה solutions/enterprise-ai-agent-local ומריצים את הפקודה:
# 1. Authenticate with all the required scopes
gcloud auth application-default login \
  --client-id-file=client_secret.json \
   --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/chat.spaces,https://www.googleapis.com/auth/chat.messages

# 2. Configure environment
export ACCESS_TOKEN=$(gcloud auth application-default print-access-token)
export GOOGLE_GENAI_USE_VERTEXAI=1
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
export GOOGLE_CLOUD_LOCATION=us-central1

# 3. Create and activate a new virtual environment
python3 -m venv .venv
source .venv/bin/activate

# 4. Install poetry and project dependencies
pip install poetry
poetry install

# 5. Start ADK Web
adk web

95fc30883ce3d56f.png

רוצה לנסות את הסוכן?

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

  1. בדפדפן האינטרנט, פותחים את האתר של ADK.
  2. בצ'אט, מקלידים Please find my meetings for today, I need their titles and links ולוחצים על enter.
  3. הסוכן עונה עם רשימה של אירועים ביומן (בהתאם לחשבון של המשתמש).
  4. בצ'אט, מקלידים Please send a Chat message to someone@example.com with the following text: Hello! ולוחצים על enter.
  5. הנציג עונה בהודעת אישור.

145f47f45332e6be.png293ec4d3e2bb6a0.png

5. סוכן כתוסף ל-Google Workspace

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

  • מודל: Gemini.
  • נתונים ופעולות: מאגרי נתונים של Vertex AI ל-Google Workspace (יומן, Gmail, ‏Drive), שרת Model Context Protocol‏ (MCP) של חיפוש מבוסס-Vertex AI בניהול Google, פונקציית כלי בהתאמה אישית לשליחת הודעות צ'אט ב-Google Chat (באמצעות Google Chat API).
  • כלים ליצירת סוכנים: ערכה לפיתוח סוכנים (ADK).
  • מארח הסוכן: Vertex AI Agent Engine.
  • ממשק משתמש: תוסף של Google Workspace ל-Chat ול-Gmail (אפשר להרחיב אותו בקלות ליומן, ל-Drive, ל-Docs, ל-Sheets ול-Slides).
  • תוסף ל-Google Workspace: ‏Apps Script, ממשקי Vertex AI Agent Engine API, הקשר (הודעת Gmail שנבחרה).

בדיקת המושגים

תוסף ל-Google Workspace

תוסף ל-Google Workspace הוא אפליקציה בהתאמה אישית שמרחיבה אפליקציה אחת או יותר של Google Workspace ‏(Gmail, ‏Chat, יומן, Docs, ‏Drive, ‏Meet, ‏Sheets ו-Slides).

Apps Script

‫Apps Script היא פלטפורמת JavaScript מבוססת-ענן שמופעלת על ידי Google Drive, ומאפשרת לכם לשלב משימות במוצרי Google ולהפוך אותן לאוטומטיות.

מסגרת הכרטיסים של Google Workspace

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

בדיקת ארכיטקטורת הפתרון

f2fd048ba298f431.png

בדיקת קוד המקור

Agent

agent.py

הקוד הבא מבצע אימות מול Vertex AI, מאתחל את הכלים של Vertex AI Search MCP ו-Chat API ומגדיר את ההתנהגות של הנציג.

  1. אימות: הפונקציה משתמשת בפונקציית עזר _get_access_token_from_context כדי לאחזר את אסימון האימות (CLIENT_AUTH_NAME) שהלקוח מוסיף. הטוקן הזה חיוני כדי להפעיל בצורה מאובטחת שירותים במורד הזרם, כמו חיפוש מבוסס-Vertex AI MCP וכלים של Google Chat.
  2. הגדרת הכלים: הפעלת vertexai_mcp, ערכת כלים שמקשרת לשרת Model Context Protocol‏ (MCP) של חיפוש מבוסס-Vertex AI, והכלי send_direct_message. כך הסוכן יכול לחפש במאגרי הנתונים המקושרים ולשלוח הודעות צ'אט ב-Google Chat.
  3. הגדרת הנציג: מגדירה את root_agent באמצעות המודל gemini-2.5-flash. ההוראות מנחות את הנציג לתת עדיפות לשימוש בכלי החיפוש לאחזור מידע ובכלי send_direct_message לפעולות, וכך למעשה מבססות את הנציג על הנתונים של הארגון.
...
MODEL = "gemini-2.5-flash"

# Client injects a bearer token into the ToolContext state.
# The key pattern is "CLIENT_AUTH_NAME_<random_digits>".
# We dynamically parse this token to authenticate our MCP and API calls.
CLIENT_AUTH_NAME = "enterprise-ai"

VERTEXAI_SEARCH_TIMEOUT = 15.0

def get_project_id():
    """Fetches the consumer project ID from the environment natively."""
    _, project = google.auth.default()
    if project:
        return project
    raise Exception(f"Failed to resolve GCP Project ID from environment.")

def find_serving_config_path():
    """Dynamically finds the default serving config in the engine."""
    project_id = get_project_id()
    engines = discoveryengine_v1.EngineServiceClient().list_engines(
        parent=f"projects/{project_id}/locations/global/collections/default_collection"
    )
    for engine in engines:
        # engine.name natively contains the numeric Project Number
        return f"{engine.name}/servingConfigs/default_serving_config"
    raise Exception(f"No Discovery Engines found in project {project_id}")

def _get_access_token_from_context(tool_context: ToolContext) -> str:
    """Helper method to dynamically parse the intercepted bearer token from the context state."""
    escaped_name = re.escape(CLIENT_AUTH_NAME)
    pattern = re.compile(fr"^{escaped_name}_\d+$")
    # Handle ADK varying state object types (Raw Dict vs ADK State)
    state_dict = tool_context.state.to_dict() if hasattr(tool_context.state, 'to_dict') else tool_context.state
    matching_keys = [k for k in state_dict.keys() if pattern.match(k)]
    if matching_keys:
        return state_dict.get(matching_keys[0])
    raise Exception(f"No bearer token found in ToolContext state matching pattern {pattern.pattern}")

def auth_header_provider(tool_context: ToolContext) -> dict[str, str]:
    token = _get_access_token_from_context(tool_context)
    return {"Authorization": f"Bearer {token}"}

def send_direct_message(email: str, message: str, tool_context: ToolContext) -> dict:
    """Sends a Google Chat Direct Message (DM) to a specific user by email address."""
    chat_client = chat_v1.ChatServiceClient(
        credentials=Credentials(token=_get_access_token_from_context(tool_context))
    )

    # 1. Setup the DM space or find existing one
    person = chat_v1.User(
        name=f"users/{email}",
        type_=chat_v1.User.Type.HUMAN
    )
    membership = chat_v1.Membership(member=person)
    space_req = chat_v1.Space(space_type=chat_v1.Space.SpaceType.DIRECT_MESSAGE)
    setup_request = chat_v1.SetUpSpaceRequest(
        space=space_req,
        memberships=[membership]
    )
    space_response = chat_client.set_up_space(request=setup_request)
    space_name = space_response.name
    
    # 2. Send the message
    msg = chat_v1.Message(text=message)
    message_request = chat_v1.CreateMessageRequest(
        parent=space_name,
        message=msg
    )
    message_response = chat_client.create_message(request=message_request)
    
    return {"status": "success", "message_id": message_response.name, "space": space_name}

vertexai_mcp = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url="https://discoveryengine.googleapis.com/mcp",
        timeout=VERTEXAI_SEARCH_TIMEOUT,
        sse_read_timeout=VERTEXAI_SEARCH_TIMEOUT
    ),
    tool_filter=['search'],
    # The auth_header_provider dynamically injects the bearer token from the ToolContext
    # into the MCP call for authentication.
    header_provider=auth_header_provider
)

# Answer nicely the following user queries:
#  - Please find my meetings for today, I need their titles and links
#  - What is the latest Drive file I created?
#  - What is the latest Gmail message I received?
#  - Please send the following message to someone@example.com: Hello, this is a test message.

root_agent = LlmAgent(
    model=MODEL,
    name='enterprise_ai',
    instruction=f"""
        You are a helpful assistant that always uses the Vertex AI MCP search tool to answer the user's message, unless the user asks you to send a message to someone.
        If the user asks you to send a message to someone, use the send_direct_message tool to send the message.
        You MUST unconditionally use the Vertex AI MCP search tool to find answer, even if you believe you already know the answer or believe the Vertex AI MCP search tool does not contain the data.
        The Vertex AI MCP search tool accesses the user's data through datastores including Google Drive, Google Calendar, and Gmail.
        Only use the Vertex AI MCP search tool with servingConfig and query parameters, do not use any other parameters.
        Always use the servingConfig {find_serving_config_path()} while using the Vertex AI MCP search tool.
    """,
    tools=[vertexai_mcp, FunctionTool(send_direct_message)]
)

לקוח

appsscript.json

ההגדרות הבאות מגדירות את הטריגרים וההרשאות של התוסף.

  1. מגדיר את התוסף: הוא מציין ל-Workspace שהפרויקט הזה הוא תוסף גם ל-Chat וגם ל-Gmail.
  2. טריגרים לפי הקשר: ב-Gmail, מוגדר contextualTrigger שמפעיל את onAddonEvent בכל פעם שמשתמש פותח הודעת אימייל. כך התוסף יכול "לראות" את תוכן האימייל.
  3. הרשאות: רשימה של oauthScopes שנדרשות כדי להפעיל את התוסף, כמו הרשאות לקרוא את האימייל הנוכחי, להריץ את הסקריפט ולהתחבר לשירותים חיצוניים (כמו ממשקי Vertex AI API).
...
"addOns": {
    "common": {
      "name": "Vertex AI",
      "logoUrl": "https://developers.google.com/workspace/add-ons/images/quickstart-app-avatar.png"
    },
    "chat": {},
    "gmail": {
      "contextualTriggers": [
        {
          "unconditional": {},
          "onTriggerFunction": "onAddonEvent"
        }
      ]
    }
  },
  "oauthScopes": [
   "https://www.googleapis.com/auth/script.external_request",
   "https://www.googleapis.com/auth/cloud-platform",
   "https://www.googleapis.com/auth/gmail.addons.execute",
   "https://www.googleapis.com/auth/gmail.addons.current.message.readonly"
 ]
...

Chat.gs

הקוד הבא מטפל בהודעות צ'אט נכנסות ב-Google Chat.

  1. קבלת הודעות: הפונקציה onMessage היא נקודת הכניסה לאינטראקציות עם הודעות.
  2. ניהול ההקשר: הסקריפט שומר את space.name (המזהה של מרחב ב-Chat) במאפייני המשתמש. כך, כשהנציג מוכן להשיב, הוא יודע בדיוק לאיזו שיחה לשלוח את ההודעה.
  3. העברת הטיפול לנציג: הוא קורא ל-requestAgent ומעביר את ההודעה של המשתמש ללוגיקה המרכזית שמטפלת בתקשורת עם ה-API.
...
// Service that handles Google Chat operations.

// Handle incoming Google Chat message events, actions will be taken via Google Chat API calls
function onMessage(event) {
  if (isInDebugMode()) {
    console.log(`MESSAGE event received (Chat): ${JSON.stringify(event)}`);
  }
  // Extract data from the event.
  const chatEvent = event.chat;
  setChatConfig(chatEvent.messagePayload.space.name);

  // Request AI agent to answer the message
  requestAgent(chatEvent.messagePayload.message);
  // Respond with an empty response to the Google Chat platform to acknowledge execution
  return null; 
}

// --- Utility functions ---

// The Chat direct message (DM) space associated with the user
const SPACE_NAME_PROPERTY = "DM_SPACE_NAME"

// Sets the Chat DM space name for subsequent operations.
function setChatConfig(spaceName) {
  const userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty(SPACE_NAME_PROPERTY, spaceName);
  console.log(`Space is set to ${spaceName}`);
}

// Retrieved the Chat DM space name to sent messages to.
function getConfiguredChat() {
  const userProperties = PropertiesService.getUserProperties();
  return userProperties.getProperty(SPACE_NAME_PROPERTY);
}

// Finds the Chat DM space name between the Chat app and the given user.
function findChatAppDm(userName) {
  return Chat.Spaces.findDirectMessage(
    { 'name': userName },
    {'Authorization': `Bearer ${getAddonCredentials().getAccessToken()}`}
  ).name;
}

// Creates a Chat message in the configured space.
function createMessage(message) {
  const spaceName = getConfiguredChat();
  console.log(`Creating message in space ${spaceName}...`);
  return Chat.Spaces.Messages.create(
    message,
    spaceName,
    {},
    {'Authorization': `Bearer ${getAddonCredentials().getAccessToken()}`}
  ).name;
}

Sidebar.gs

הקוד הבא יוצר את סרגל הצד של Gmail ומתעד את ההקשר של האימייל.

  1. יצירת ממשק המשתמש: הפונקציה createSidebarCard יוצרת את הממשק החזותי באמצעות שירות הכרטיסים של Workspace. הוא יוצר פריסה פשוטה עם אזור להזנת טקסט וכפתור "שליחת הודעה".
  2. תיעוד ההקשר של האימייל: ב-handleSendMessage, הקוד בודק אם המשתמש מסתכל כרגע על אימייל (event.gmail.messageId). אם כן, הוא מאחזר באופן מאובטח את הנושא ואת גוף האימייל ומוסיף אותם להנחיה של המשתמש.
  3. הצגת התוצאה: אחרי שהנציג עונה, הקוד מעדכן את הכרטיס בסרגל הצד כדי להציג את התשובה.
...
// Service that handles Gmail operations.

// Triggered when the user opens the Gmail Add-on or selects an email.
function onAddonEvent(event) {
  // If this was triggered by a button click, handle it
  if (event.parameters && event.parameters.action === 'send') {
    return handleSendMessage(event);
  }

  // Otherwise, just render the default initial sidebar
  return createSidebarCard();
}

// Creates the standard Gmail sidebar card consisting of a text input and send button.
// Optionally includes an answer section if a response was generated.
function createSidebarCard(optionalAnswerSection) {
  const card = CardService.newCardBuilder();
  const actionSection = CardService.newCardSection();

  // Create text input for the user's message
  const messageInput = CardService.newTextInput()
    .setFieldName("message")
    .setTitle("Message")
    .setMultiline(true);

  // Create action for sending the message
  const sendAction = CardService.newAction()
    .setFunctionName('onAddonEvent')
    .setParameters({ 'action': 'send' });

  const sendButton = CardService.newTextButton()
    .setText("Send message")
    .setTextButtonStyle(CardService.TextButtonStyle.FILLED)
    .setOnClickAction(sendAction);

  actionSection.addWidget(messageInput);
  actionSection.addWidget(CardService.newButtonSet().addButton(sendButton));

  card.addSection(actionSection);

  // Attach the response at the bottom if we have one
  if (optionalAnswerSection) {
    card.addSection(optionalAnswerSection);
  }

  return card.build();
}

// Handles clicks from the Send message button.
function handleSendMessage(event) {
  const commonEventObject = event.commonEventObject || {};
  const formInputs = commonEventObject.formInputs || {};
  const messageInput = formInputs.message;

  let userMessage = "";
  if (messageInput && messageInput.stringInputs && messageInput.stringInputs.value.length > 0) {
    userMessage = messageInput.stringInputs.value[0];
  }

  if (!userMessage || userMessage.trim().length === 0) {
    return CardService.newActionResponseBuilder()
      .setNotification(CardService.newNotification().setText("Please enter a message."))
      .build();
  }

  let finalQueryText = `USER MESSAGE TO ANSWER: ${userMessage}`;

  // If we have an email selected in Gmail, append its content as context
  if (event.gmail && event.gmail.messageId) {
    try {
      GmailApp.setCurrentMessageAccessToken(event.gmail.accessToken);
      const message = GmailApp.getMessageById(event.gmail.messageId);

      const subject = message.getSubject();
      const bodyText = message.getPlainBody() || message.getBody();

      finalQueryText += `\n\nEMAIL THE USER HAS OPENED ON SCREEN:\nSubject: ${subject}\nBody:\n---\n${bodyText}\n---`;
    } catch (e) {
      console.error("Could not fetch Gmail context: " + e);
      // Invalidate the token explicitly so the next prompt requests the missing scopes
      ScriptApp.invalidateAuth();

      CardService.newAuthorizationException()
        .setResourceDisplayName("Enterprise AI")
        .setAuthorizationUrl(ScriptApp.getAuthorizationUrl())
        .throwException();
    }
  }

  try {
    const response = queryAgent({ text: finalQueryText });

    // We leverage the 'showdown' library to parse the LLM's Markdown output into HTML
    // We also substitute markdown listings with arrows and adjust newlines for clearer rendering in the sidebar
    let displayedText = substituteListingsFromMarkdown(response.text);
    displayedText = new showdown.Converter().makeHtml(displayedText).replace(/\n/g, '\n\n');

    const textParagraph = CardService.newTextParagraph();
    textParagraph.setText(displayedText);

    const answerSection = CardService.newCardSection()
      .addWidget(textParagraph);

    const updatedCard = createSidebarCard(answerSection);

    return CardService.newActionResponseBuilder()
      .setNavigation(CardService.newNavigation().updateCard(updatedCard))
      .build();

  } catch (err) {
    return CardService.newActionResponseBuilder()
      .setNotification(CardService.newNotification().setText("Error fetching response: " + err.message))
      .build();
  }
}
...

AgentHandler.gs

הקוד הבא מתזמר את הקריאה ל-API אל Vertex AI.

  1. ניהול הקריאה ל-API: queryAgent הוא הגשר בין התוסף לבין Vertex AI Agent Engine. היא יוצרת בקשה שכוללת את השאילתה של המשתמש ואת אסימון האימות במצב.
  2. העברת התשובה בסטרימינג: מכיוון שלפעמים לוקח זמן עד שהסוכן משיב, הוא משתמש ב-API של streamQuery עם אירועים שנשלחים מהשרת (SSE). הקוד אוסף את התשובה בחלקים ומשחזר את התשובה המלאה.
...
// Service that handles Vertex AI Agent operations.

// Submits a query to the AI agent and returns the response string synchronously
function queryAgent(input) {
 let systemPrompt = "SYSTEM PROMPT START Do not respond with tables but use bullet points instead." +
   " Do not ask the user follow-up questions or converse with them as history is not kept in this interface." +
   " SYSTEM PROMPT END\n\n";

 const requestPayload = {
   "class_method": "async_stream_query",
   "input": {
     "user_id": "vertex_ai_add_on",
     "message": { "role": "user", "parts": [{ "text": systemPrompt + input.text }] },
     "state_delta": {
       "enterprise-ai_999": `${ScriptApp.getOAuthToken()}`
     }
   }
 };

 const responseContentText = UrlFetchApp.fetch(
   `https://${getLocation()}-aiplatform.googleapis.com/v1/${getReasoningEngine()}:streamQuery?alt=sse`,
   {
     method: 'post',
     headers: { 'Authorization': `Bearer ${ScriptApp.getOAuthToken()}` },
     contentType: 'application/json',
     payload: JSON.stringify(requestPayload),
     muteHttpExceptions: true
   }
 ).getContentText();
  if (isInDebugMode()) {
   console.log(`Response: ${responseContentText}`);
 }

 const events = responseContentText.split('\n').map(s => s.replace(/^data:\s*/, '')).filter(s => s.trim().length > 0);
 console.log(`Received ${events.length} agent events.`);

 let author = "default";
 let answerText = "";
 for (const eventJson of events) {
   if (isInDebugMode()) {
     console.log("Event: " + eventJson);
   }
   const event = JSON.parse(eventJson);

   // Retrieve the agent responsible for generating the content
   author = event.author;
  
   // Ignore events that are not useful for the end-user
   if (!event.content) {
     console.log(`${author}: internal event`);
     continue;
   }

   // Handle text answers
   const parts = event.content.parts || [];
   const textPart = parts.find(p => p.text);
   if (textPart) {
     answerText += textPart.text;
   }
 }
 return { author: author, text: answerText };
}
...

פריסת נציג ב-Vertex AI Agent Engine

  1. במסוף, פותחים את הספרייה solutions/enterprise-ai-agent מהמקורות שהורדתם בשלבים הקודמים, ואז מריצים את הפקודה:
# 1. Create and activate a new virtual environment
deactivate
python3 -m venv .venv
source .venv/bin/activate

# 2. Install poetry and project dependencies
pip install poetry
poetry install

# 3. Deploy the agent
adk deploy agent_engine \
  --project=$(gcloud config get-value project) \
  --region=us-central1 \
  --display_name="Enterprise AI" \
  enterprise_ai

eafd2f9c4fbf305.png

  1. כשמופיעה השורה Deploying to agent engine...‎ ביומנים, פותחים טרמינל חדש ומריצים את הפקודה הבאה כדי להוסיף את ההרשאות הנדרשות ל-Vertex AI Reasoning Engine Service Agent:
# 1. Get the current Project ID
PROJECT_ID=$(gcloud config get-value project)

# 2. Extract the Project Number for that ID
PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)')

# 3. Construct the Service Account name
SERVICE_ACCOUNT="service-${PROJECT_NUMBER}@gcp-sa-aiplatform-re.iam.gserviceaccount.com"

# 4. Apply the IAM policy binding
gcloud projects add-iam-policy-binding $PROJECT_ID \
     --member="serviceAccount:$SERVICE_ACCOUNT" \
     --role="roles/discoveryengine.viewer"
  1. מחכים שהפקודה adk deploy תסתיים, ואז מעתיקים את שם המשאב של הנציג החדש שנפרס מפלט הפקודה בירוק.

d098fe1347d6581b.png

הפעלת חשבון שירות

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

במסוף Google Cloud, מבצעים את הפעולות הבאות:

  1. לוחצים על Menu ☰ > IAM & Admin > Service Accounts > + Create service account.

  1. מגדירים את Service account name לערך vertexai-add-on.

46be0eb53f416c59.png

  1. לוחצים על סיום. תועברו לדף Service accounts, שבו תוכלו לראות את חשבון השירות שיצרתם.

f002fef61c71ed8.png

  1. בוחרים את חשבון השירות החדש שנוצר ואז את הכרטיסייה Keys.
  2. לוחצים על Add key ואז על Create new key.
  3. בוחרים באפשרות JSON ולוחצים על יצירה.

7b140535d9e1af44.png

  1. תיבת הדו-שיח תיסגר וזוג המפתחות הציבורי/פרטי החדש שיצרתם יורד באופן אוטומטי לסביבה המקומית שלכם כקובץ JSON.

יצירה והגדרה של פרויקט Apps Script

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

  1. לוחצים על הכפתור הבא כדי לפתוח את הפרויקט Enterprise AI add on ב-Apps Script:

.

  1. לוחצים על סקירה כללית > יצירת עותק.
  2. בפרויקט Apps Script, לוחצים על הגדרות הפרויקט > עריכת מאפייני הסקריפט > הוספת מאפיין סקריפט כדי להוסיף מאפייני סקריפט.
  3. מגדירים את REASONING_ENGINE_RESOURCE_NAME לשם המשאב של סוכן ה-AI ב-Vertex AI שהעתקתם בשלבים הקודמים. הפורמט שלו הוא:
projects/<PROJECT_NUMBER>/locations/us-central1/reasoningEngines/<AGENT_ID>
  1. מגדירים את APP_SERVICE_ACCOUNT_KEY למפתח ה-JSON מקובץ חשבון השירות שהורדתם בשלבים הקודמים.
  2. לוחצים על שמירת מאפייני הסקריפט.

פריסה ב-Gmail וב-Chat

פורסים את התוסף כדי לבדוק אותו ישירות ב-Gmail וב-Google Chat.

בפרויקט Apps Script, פועלים לפי השלבים הבאים:

  1. לוחצים על Deploy > Test deployments (פריסה > פריסות לבדיקה) ואז על Install (התקנה). היא זמינה עכשיו ב-Gmail.
  2. לוחצים על העתקה בקטע מזהה Head Deployment.

b0cba69eef271850.png

במסוף Google Cloud, מבצעים את הפעולות הבאות:

  1. מחפשים את Google Chat API בשדה החיפוש של Google Cloud, לוחצים על Google Chat API, לוחצים על ניהול ואז על הגדרה.

  1. לוחצים על הפעלת תכונות אינטראקטיביות.
  2. מבטלים את הבחירה באפשרות הצטרפות למרחבים משותפים ולשיחות קבוצתיות.
  3. בקטע הגדרות חיבור, בוחרים באפשרות Apps Script.
  4. מגדירים את Deployment ID (מזהה הפריסה) ל-Head Deployment ID (מזהה הפריסה הראשי) שהועתק בשלבים הקודמים.
  5. בקטע הרשאות גישה, בוחרים באפשרות האפליקציה הזו ל-Chat תהיה זמינה לאנשים ולקבוצות ספציפיים בדומיין שלך ב-Workspace ומזינים את כתובת האימייל שלכם.
  6. לוחצים על שמירה.

6ea187ccb90a0e49.png

אני רוצה לנסות את התוסף

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

פותחים את Google Chat בכרטיסייה חדשה ופועלים לפי השלבים הבאים:

  1. פותחים צ'אט אישי עם האפליקציה Vertex AI ב-Chat.

495632314dec5a5d.png

  1. לוחצים על הגדרה ומבצעים את תהליך האימות.
  2. מקלידים What are my meetings for today? ולוחצים על enter. אפליקציית הצ'אט של Vertex AI אמורה להשיב עם התוצאות.

172da43f310a0579.png

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

  1. שולחים לעצמכם אימייל עם הנושא We need to talk וגוף ההודעה Are you available today between 8 and 9 AM?.
  2. פותחים את הודעת האימייל החדשה שהתקבלה.
  3. פותחים את סרגל הצד של התוסף Vertex AI.
  4. מגדירים את ההודעה לערך Do I have any meeting conflicts?
  5. לוחצים על שליחת הודעה.
  6. התשובה מוצגת אחרי הכפתור.

840b494aa5eaa1ef.png

6. הסרת המשאבים

מחיקת פרויקט ב-Google Cloud

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

במסוף Google Cloud, מבצעים את הפעולות הבאות:

  1. לוחצים על תפריט ☰ > IAM ואדמין > הגדרות.

  1. לוחצים על כיבוי.
  2. מזינים את מזהה הפרויקט.
  3. לוחצים על כיבוי בכל זאת.

3b9492d97f771b2c.png

7. מזל טוב

מעולה! פיתחתם פתרונות שמשלבים את Vertex AI ו-Google Workspace כדי לעזור לעובדים.

מה השלב הבא?

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

  • להשתמש בכלים למפתחים שמבוססים על AI, כמו Gemini CLI ו-Antigravity.
  • לשלב עם מסגרות וכלים אחרים של סוכנים, כמו MCP בהתאמה אישית, בקשות להפעלת פונקציות בהתאמה אישית וממשקי משתמש גנרטיביים.
  • לשלב מודלי AI אחרים, כולל מודלים בהתאמה אישית, שמתארחים בפלטפורמות ייעודיות כמו Vertex AI.
  • לשלב עם נציגים אחרים, שמתארחים בפלטפורמות ייעודיות כמו Dialogflow או על ידי צדדים שלישיים דרך Cloud Marketplace.
  • לפרסם נציגים ב-Cloud Marketplace כדי לעזור לצוותים, לארגונים או למשתמשים ציבוריים.

מידע נוסף

יש הרבה מקורות מידע זמינים למפתחים, כמו סרטונים ב-YouTube, אתרי תיעוד, דוגמאות קוד ומדריכים: