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

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

99afae2505f696fb.png

מה זה Vertex AI?

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

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

127f2ed7d484722c.png

מה זה Google Workspace?

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

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

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

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

  • קישוריות חכמה: מאגרי נתונים, ממשקי API ושרתי MCP (מנוהלים על ידי Google ומותאמים אישית) שמנוהלים על ידי 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), שרת פרוטוקול הקשר (MCP) של מודל חיפוש Vertex AI שמנוהל על ידי Google, פונקציית כלי בהתאמה אישית לשליחת הודעות ב-Google Chat (באמצעות Google Chat API).
  • כלים לבניית סוכנים: ערכה לפיתוח סוכנים (ADK).
  • מארח הסוכן: Vertex AI Agent Engine.
  • ממשק משתמש: ADK Web.

145f47f45332e6be.png

293ec4d3e2bb6a0.png

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

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

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

172da43f310a0579.png

840b494aa5eaa1ef.png

מה תלמדו

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

2. הגדרה

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

מושגים שכדאי להכיר

אפליקציית Vertex AI

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

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

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

הפעלת ההגדרות של Vertex AI Applications

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

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

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

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

93b0cc6ed63fba0c.png

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

5c01b4cbeebaa93b.png

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

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

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

3877dcaa56624d0b.png

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

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

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

  1. במסוף Google Cloud, עוברים אל AI Applications (אפליקציות AI) ואז אל Data Stores (מאגרי נתונים).

  1. לוחצים על + יצירת מאגר נתונים.
  2. בקטע מקור, מתחת לGoogle Drive, לוחצים על בחירה.

6939363368bde36d.png

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

5044243322acec9e.png

  1. בקטע הגדרה, מגדירים את השם של מחבר הנתונים ל-drive, ולוחצים על המשך אחרי שבודקים ומאשרים את החיובים שעשויים לחול.

1f5deb1aeecee983.png

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

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

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

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

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

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

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

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

בדיקת מושגים

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

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

‫Vertex AI Search Web Widget

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

תצוגה מקדימה של חיפוש מבוסס-Vertex AI

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

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

1f337dc91da74391.png

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

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

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

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

9714a5fff49b5e1b.png

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

327702cd837cbb18.png

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

5745607f3c43d5c0.png

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

d53ed9d9d1ced955.png

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

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

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

af1ca3bd78e1cb4f.png

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

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

  1. עוברים אל תצוגה מקדימה, הווידג'ט לאתר מוצג.
  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), שרת פרוטוקול הקשר (MCP) של מודל חיפוש Vertex AI שמנוהל על ידי Google, פונקציית כלי בהתאמה אישית לשליחת הודעות ב-Google Chat (באמצעות Google Chat API).
  • כלים לבניית סוכנים: ערכה לפיתוח סוכנים (ADK).
  • מארח הסוכן: Vertex AI Agent Engine.
  • ממשק משתמש: ADK Web.

מושגים שכדאי להכיר

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

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

Model Context Protocol (MCP)

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

כלי הפונקציות

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

ADK Web

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

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

f14251cca6a19b1f.png

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

agent.py

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

  1. אימות: הוא מאחזר את ACCESS_TOKEN ממשתני הסביבה כדי לאמת את קריאות ה-API ואת MCP.
  2. Tools Setup (הגדרת כלים): הפעולה הזו מאתחלת את vertexai_mcp, ערכת כלים שמתחברת לשרת Model Context Protocol‏ (MCP) של Vertex AI Search, ואת הכלי 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 console, מפעילים את ממשקי ה-API של Vertex AI,‏ Cloud Resource Manager ו-Google Chat:

60bae4065338c5bf.png

  1. לוחצים על Menu ☰ > APIs & Services > Enabled APIs & Services ומוודאים ש-Vertex AI API,‏ Cloud Resource Manager API ו-Google Chat API מופיעים ברשימה.

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

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

  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 > לקוחות.

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

c1c9bc2f8c14dd6c.png

הפעלת Vertex AI Search MCP

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

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

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

  1. ב-Google Cloud Console, מחפשים את Google Chat API בשדה החיפוש של Google Cloud, לוחצים על Google Chat API, לוחצים על Manage ואז על Configuration.

  1. מגדירים את שם האפליקציה ואת התיאור לערך Vertex AI.
  2. מגדירים את כתובת ה-URL של האווטאר ל-https://developers.google.com/workspace/add-ons/images/quickstart-app-avatar.png.
  3. מבטלים את הסימון של הפעלת תכונות אינטראקטיביות ואז לוחצים על השבתה בתיבת הדו-שיח המודאלית שמופיעה.
  4. בוחרים באפשרות Log errors to Logging (רישום שגיאות ב-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.png

293ec4d3e2bb6a0.png

5. נציג כתוסף ל-Google Workspace

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

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

  1. אימות: הפונקציה משתמשת בפונקציית עזר _get_access_token_from_context כדי לאחזר את אסימון האימות (CLIENT_AUTH_NAME) שהלקוח מזריק. האסימון הזה חיוני כדי לבצע קריאות מאובטחות לשירותים במורד הזרם, כמו Vertex AI Search MCP וכלי Google Chat.
  2. Tools Setup (הגדרת כלים): הפעולה הזו מאתחלת את vertexai_mcp, ערכת כלים שמתחברת לשרת Model Context Protocol‏ (MCP) של Vertex AI Search, ואת הכלי 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 APIs).
...
"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. Receives Messages: הפונקציה 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 Card Service. הוא יוצר פריסה פשוטה עם אזור להזנת טקסט ולחצן 'שליחת הודעה'.
  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

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

  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 };
}
...

Deploy Agent in 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:
# 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

Initiate service account

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

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

  1. לוחצים על תפריט ☰ > IAM & Admin > Service Accounts > + Create service account (תפריט ☰ > IAM ואדמין > חשבונות שירות > + יצירת חשבון שירות).

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

46be0eb53f416c59.png

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

f002fef61c71ed8.png

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

7b140535d9e1af44.png

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

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

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

  1. כדי לפתוח את פרויקט Apps Script של התוסף Enterprise AI, לוחצים על הלחצן הבא:

  1. לוחצים על סקירה כללית > יצירת עותק.
  2. בפרויקט Apps Script, לוחצים על Project Settings (הגדרות הפרויקט) > Edit script properties (עריכת מאפייני הסקריפט) > Add script property (הוספת מאפיין סקריפט) כדי להוסיף מאפייני סקריפט.
  3. מגדירים את REASONING_ENGINE_RESOURCE_NAME לשם משאב הסוכן של 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. מגדירים את מזהה הפריסה למזהה הפריסה של תג head שהועתק בשלבים הקודמים.
  5. בקטע חשיפה, בוחרים באפשרות הפיכת אפליקציית הצ'אט הזו לזמינה לאנשים ולקבוצות ספציפיים בדומיין שלכם ב-Workspace ומזינים את כתובת האימייל.
  6. לוחצים על שמירה.

6ea187ccb90a0e49.png

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

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

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

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

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. לוחצים על Shut down anyway (כיבוי בכל זאת).

3b9492d97f771b2c.png

7. מזל טוב

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

מה השלב הבא?

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

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

מידע נוסף

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