ผสานรวมเอเจนต์ Vertex AI กับ Google Workspace

1. ก่อนเริ่มต้น

99afae2505f696fb.png

Vertex AI คืออะไร

Vertex AI เป็นแพลตฟอร์มการพัฒนาแบบครบวงจรของ Google Cloud สำหรับการสร้าง การติดตั้งใช้งาน และการปรับขนาด AI Agent และแอปพลิเคชันระดับองค์กร โดยมอบเครื่องมือที่ซับซ้อนแก่นักพัฒนาซอฟต์แวร์และนักวิทยาศาสตร์ข้อมูล ซึ่งจำเป็นต่อการออกแบบเวิร์กโฟลว์แบบเป็น Agent ที่กำหนดเองซึ่งผสานรวมกับโครงสร้างพื้นฐานระดับโลกอย่างลึกซึ้ง

  • เข้าถึง Model Garden: เลือกจากโมเดลพื้นฐานกว่า 150 รายการ ซึ่งรวมถึงโมเดลตระกูล Gemini ทั้งหมด โมเดลของบุคคลที่สาม และโมเดลโอเพนซอร์สเฉพาะทาง เพื่อค้นหาโมเดลที่เหมาะกับงานของเอเจนต์ที่เฉพาะเจาะจง
  • ออกแบบการจัดกลุ่มที่ซับซ้อน: Vertex AI มีเฟรมเวิร์กในการออกแบบเอเจนต์อัตโนมัติที่ใช้การให้เหตุผลเพื่อวางแผน ดำเนินการงานแบบหลายขั้นตอน และเรียกใช้ API ภายนอก
  • การอ้างอิงระดับองค์กร: เชื่อมต่อเอเจนต์กับข้อมูลทางธุรกิจแบบเรียลไทม์ รวมถึง RAG (Retrieval-Augmented Generation) ที่มีประสิทธิภาพสูง เพื่อกำจัดอาการหลอนและรับประกันความถูกต้องของข้อเท็จจริง
  • DevOps: ผสานรวมการพัฒนาเอเจนต์เข้ากับไปป์ไลน์ CI/CD ที่มีอยู่ได้อย่างราบรื่นด้วย SDK, API และเครื่องมือประเมินที่แข็งแกร่งเพื่อวัดประสิทธิภาพและความปลอดภัยของเอเจนต์ในวงกว้าง
  • ความปลอดภัยระดับอุตสาหกรรม: Vertex AI ช่วยให้มั่นใจได้ว่าข้อมูลลูกค้าที่ใช้ในการฝึกหรือการอ้างอิงจะยังคงเป็นส่วนตัว เข้ารหัส และเป็นไปตามข้อกำหนดด้านการพำนักอาศัยทั่วโลก
  • โครงสร้างพื้นฐานที่เพิ่มประสิทธิภาพ: ปรับขนาดภาระงานของเอเจนต์ได้อย่างง่ายดายในคลัสเตอร์ TPU และ GPU ระดับโลกของ Google เพื่อให้มั่นใจว่ามีประสิทธิภาพที่มีเวลาในการตอบสนองต่ำแม้สำหรับแอปพลิเคชันระดับโลกที่มีความต้องการสูงสุด

127f2ed7d484722c.png

Google Workspace คืออะไร

Google Workspace คือชุดโซลูชันด้านประสิทธิภาพการทำงานและการทำงานร่วมกันบนระบบคลาวด์ที่ออกแบบมาสำหรับบุคคล โรงเรียน และธุรกิจ

  • การสื่อสาร: บริการอีเมลแบบมืออาชีพ (Gmail), การประชุมทางวิดีโอ (Meet) และการรับส่งข้อความของทีม (Chat)
  • การสร้างเนื้อหา: เครื่องมือสำหรับเขียนเอกสาร (เอกสาร), สร้างสเปรดชีต (ชีต) และออกแบบงานนำเสนอ (สไลด์)
  • การจัดระเบียบ: ปฏิทินที่ใช้ร่วมกัน (ปฏิทิน) และการจดบันทึกดิจิทัล (Keep)
  • พื้นที่เก็บข้อมูล: พื้นที่เก็บข้อมูลระบบคลาวด์ส่วนกลางสำหรับบันทึกและแชร์ไฟล์อย่างปลอดภัย (ไดรฟ์)
  • การจัดการ: การควบคุมดูแลระบบเพื่อจัดการผู้ใช้และการตั้งค่าความปลอดภัย (คอนโซลผู้ดูแลระบบ Workspace)

การผสานรวมที่กำหนดเองประเภทใด

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

  • การเชื่อมต่ออัจฉริยะ: ที่เก็บข้อมูล, API และเซิร์ฟเวอร์ MCP (ที่ Google จัดการและที่กำหนดเอง) ที่ Google จัดการช่วยให้ตัวแทนเข้าถึงข้อมูล Workspace ได้อย่างปลอดภัยและราบรื่น รวมถึงดำเนินการในนามของผู้ใช้
  • เอเจนต์ที่กำหนดเอง: ทีมสามารถสร้างเอเจนต์เฉพาะทางที่อิงตามข้อมูลและการดำเนินการใน Workspace ที่ผู้ดูแลระบบควบคุมได้โดยใช้ดีไซเนอร์แบบไม่ต้องเขียนโค้ดหรือเฟรมเวิร์กแบบเขียนโค้ด
  • การผสานรวมดั้งเดิม: ส่วนเสริม Workspace ช่วยเชื่อมช่องว่างระหว่างระบบ AI กับแอปพลิเคชันต่างๆ เช่น Chat และ Gmail ไม่ว่าจะผ่านคอมโพเนนต์ UI เฉพาะหรือกระบวนการเบื้องหลัง ซึ่งช่วยให้ตัวแทนสามารถพบปะผู้ใช้ได้ทุกที่ทุกเวลาเพื่อรับความช่วยเหลือที่รวดเร็วและรับรู้บริบท

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

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

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

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

ใน Codelab นี้ เราจะสร้างโซลูชัน 3 รายการด้วยเอเจนต์ Vertex AI ที่ผสานรวมกับ Google Workspace อย่างใกล้ชิด โดยจะแสดงรูปแบบสถาปัตยกรรมที่ใช้โต้ตอบกับข้อมูล การดำเนินการ และ UI ได้

แอป Vertex AI Search

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

  • โมเดล: Gemini
  • ข้อมูลและการดำเนินการ: ที่เก็บข้อมูล Vertex AI สำหรับ Google Workspace (ปฏิทิน, Gmail, ไดรฟ์)
  • โฮสต์ของ Agent: Vertex AI Search
  • UI: วิดเจ็ตเว็บของ Vertex AI Search

d276ff8e2b9d0ddf.png

เอเจนต์ที่กำหนดเอง

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

  • โมเดล: Gemini
  • ข้อมูลและการดำเนินการ: ที่เก็บข้อมูล Vertex AI สำหรับ Google Workspace (ปฏิทิน, Gmail, ไดรฟ์), เซิร์ฟเวอร์ Context Protocol (MCP) ของโมเดลการค้นหา Vertex AI ที่ Google จัดการ, ฟังก์ชันเครื่องมือที่กำหนดเองเพื่อส่งข้อความ Google Chat (ผ่าน Google Chat API)
  • เครื่องมือสร้าง Agent: Agent Development Kit (ADK)
  • โฮสต์ของ Agent: Vertex AI Agent Engine
  • UI: ADK Web

145f47f45332e6be.png

293ec4d3e2bb6a0.png

เอเจนต์เป็นส่วนเสริมของ Google Workspace

เอเจนต์นี้ช่วยให้ผู้ใช้ค้นหาข้อมูลสำหรับ Workspace ในภาษาที่เป็นธรรมชาติได้ภายในบริบทของ UI ของแอป Workspace โดยจะอิงตามองค์ประกอบต่อไปนี้

  • โมเดล: Gemini
  • ข้อมูลและการดำเนินการ: ที่เก็บข้อมูล Vertex AI สำหรับ Google Workspace (ปฏิทิน, Gmail, ไดรฟ์), เซิร์ฟเวอร์ Context Protocol (MCP) ของโมเดลการค้นหา Vertex AI ที่ Google จัดการ, ฟังก์ชันเครื่องมือที่กำหนดเองเพื่อส่งข้อความ Google Chat (ผ่าน Google Chat API)
  • เครื่องมือสร้าง Agent: Agent Development Kit (ADK)
  • โฮสต์ของ Agent: Vertex AI Agent Engine
  • UI: ส่วนเสริม Google Workspace สำหรับ Chat และ Gmail (ขยายไปยังปฏิทิน, ไดรฟ์, เอกสาร, ชีต และสไลด์ได้อย่างง่ายดาย)
  • ส่วนเสริมของ Google Workspace: Apps Script, Vertex AI Agent Engine API, บริบท (ข้อความ Gmail ที่เลือก)

172da43f310a0579.png

840b494aa5eaa1ef.png

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

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

2. ตั้งค่า

ก่อนสร้างโซลูชัน เราต้องเริ่มต้นการตั้งค่าแอปพลิเคชัน Vertex AI ของโปรเจ็กต์ เปิดใช้ API ที่จำเป็น และสร้างที่เก็บข้อมูล Vertex AI Workspace

แนวคิดการตรวจสอบ

แอปพลิเคชัน Vertex AI

แอปพลิเคชัน Vertex AI คือโซลูชันที่มีการจัดการแบบครบวงจรใน Google Cloud ซึ่งผสานรวมโมเดลแมชชีนเลิร์นนิง (เช่น เอเจนต์ Generative AI หรือเครื่องมือค้นหา) กับข้อมูลขององค์กรและเครื่องมือเฉพาะทางเพื่อทำงานที่ซับซ้อน เช่น การค้นหาเชิงความหมาย การสร้างเนื้อหา หรือการโต้ตอบกับลูกค้าโดยอัตโนมัติ

ที่เก็บข้อมูล Vertex AI

ที่เก็บข้อมูล Vertex AI คือเอนทิตีที่มีข้อมูลที่ส่งจากแหล่งข้อมูลจากบุคคลที่หนึ่ง เช่น Google Workspace หรือแอปพลิเคชันของบุคคลที่สาม เช่น Jira หรือ Shopify ที่เก็บข้อมูลที่มีข้อมูลจากแอปพลิเคชันของบุคคลที่สามเรียกว่าเครื่องมือเชื่อมต่อข้อมูลด้วย

เริ่มต้นการตั้งค่าแอปพลิเคชัน Vertex AI

เริ่มต้นการตั้งค่าแอปพลิเคชัน Vertex AI เพื่อเปิดใช้การสร้างเอเจนต์

เปิด Google Cloud Console ในแท็บใหม่ แล้วทำตามขั้นตอนต่อไปนี้

  1. เลือกโปรเจ็กต์
  2. ไปที่แอปพลิเคชัน AI ในช่องค้นหาของ Google Cloud

  1. คลิกดำเนินการต่อและเปิดใช้งาน API หลังจากอ่านและยอมรับข้อกำหนดแล้ว
  2. ไปที่การตั้งค่า
  3. ในแท็บ Authentication ให้แก้ไข global

93b0cc6ed63fba0c.png

  1. เลือก Google Identity แล้วคลิกบันทึก

5c01b4cbeebaa93b.png

เปิดใช้ API

พื้นที่เก็บข้อมูลของ Vertex AI Workspace ต้องเปิดใช้ API ดังนี้

  1. ในคอนโซล Google Cloud ให้เปิดใช้ Calendar, Gmail และ People API โดยทำดังนี้

3877dcaa56624d0b.png

  1. คลิกเมนู ☰ > API และบริการ > API และบริการที่เปิดใช้ แล้วตรวจสอบว่า Google Calendar API, Gmail API และ People API อยู่ในรายการ

สร้างที่เก็บข้อมูล

สร้างที่เก็บข้อมูล Google ไดรฟ์

  1. ในคอนโซล Google Cloud ให้ไปที่แอปพลิเคชัน AI แล้วไปที่ที่เก็บข้อมูล

  1. คลิก + สร้างที่เก็บข้อมูล
  2. ในแหล่งที่มา ภายใน Google ไดรฟ์ ให้คลิกเลือก

6939363368bde36d.png

  1. ในข้อมูล ให้เลือกทั้งหมด แล้วคลิกต่อไป

5044243322acec9e.png

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

1f5deb1aeecee983.png

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

สร้างที่เก็บข้อมูล Google ปฏิทิน

  1. คลิก + สร้างที่เก็บข้อมูล
  2. ในแหล่งที่มา ให้ค้นหา Google ปฏิทิน แล้วคลิกเลือก
  3. ในส่วนการดำเนินการ ให้คลิกข้าม
  4. ในส่วนการกำหนดค่า ให้ตั้งชื่อเครื่องมือเชื่อมต่อข้อมูลเป็น calendar
  5. คลิกสร้าง
  6. ระบบจะเปลี่ยนเส้นทางคุณไปยังที่เก็บข้อมูลโดยอัตโนมัติ ซึ่งคุณจะเห็นที่เก็บข้อมูลที่เพิ่มใหม่

สร้างพื้นที่เก็บข้อมูล Google Gmail โดยทำดังนี้

  1. คลิก + ที่เก็บข้อมูลใหม่
  2. ในแหล่งที่มา ให้ค้นหา Google Gmail แล้วคลิกเลือก
  3. ในส่วนการดำเนินการ ให้คลิกข้าม
  4. ในส่วนการกำหนดค่า ให้ตั้งชื่อเครื่องมือเชื่อมต่อข้อมูลเป็น gmail
  5. คลิกสร้าง
  6. ระบบจะเปลี่ยนเส้นทางคุณไปยังที่เก็บข้อมูลโดยอัตโนมัติ ซึ่งคุณจะเห็นที่เก็บข้อมูลที่เพิ่มใหม่

3. แอป Vertex AI Search

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

  • โมเดล: Gemini
  • ข้อมูลและการดำเนินการ: ที่เก็บข้อมูล Vertex AI สำหรับ Google Workspace (ปฏิทิน, Gmail, ไดรฟ์)
  • โฮสต์ของ Agent: Vertex AI Search
  • UI: วิดเจ็ตเว็บของ Vertex AI Search

ตรวจสอบแนวคิด

แอป Vertex AI Search

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

วิดเจ็ตเว็บ Vertex AI Search

วิดเจ็ตเว็บของ Vertex AI Search เป็นคอมโพเนนต์ UI ที่สร้างไว้ล่วงหน้าและปรับแต่งได้ ซึ่งช่วยให้นักพัฒนาแอปฝังแถบค้นหาและอินเทอร์เฟซผลการค้นหาที่ทำงานด้วยระบบ AI ลงในเว็บไซต์ได้โดยตรงโดยใช้การเขียนโค้ดน้อยที่สุด

เวอร์ชันตัวอย่างของ Vertex AI Search

Vertex AI Search เวอร์ชันตัวอย่างคือสภาพแวดล้อมการทดสอบในตัวภายใน Google Cloud Console ซึ่งช่วยให้นักพัฒนาแอปตรวจสอบการกำหนดค่าการค้นหาและคำตอบแบบ Generative ก่อนที่จะติดตั้งใช้งานการตั้งค่าเดียวกันเหล่านั้นอย่างราบรื่นกับวิดเจ็ตเว็บ Vertex AI Search ที่พร้อมใช้งานจริง

ตรวจสอบสถาปัตยกรรมโซลูชัน

1f337dc91da74391.png

สร้างแอป

สร้างแอปค้นหาใหม่เพื่อยึดพื้นที่เก็บข้อมูล

เปิด AI Applications > Apps จาก Cloud Console แล้วทำตามขั้นตอนต่อไปนี้

  1. คลิก + สร้างแอป
  2. ในส่วนประเภท ภายในCustom Search (ทั่วไป) ให้คลิกสร้าง

9714a5fff49b5e1b.png

  1. ในการกำหนดค่า ให้เลือกฟีเจอร์รุ่น Enterprise และคำตอบที่สร้างขึ้นหลังจากตรวจสอบและตกลงราคาแล้ว
  2. ตั้งค่าชื่อแอปเป็น codelab
  3. ระบบจะสร้างรหัสตามชื่อและแสดงไว้ใต้ช่อง ให้คัดลอกรหัส
  4. ตั้งค่าชื่อบริษัทเป็น Codelab
  5. ตั้งค่าหลายภูมิภาคเป็น global (Global)
  6. คลิกต่อไป

327702cd837cbb18.png

  1. ในข้อมูล ให้เลือกที่เก็บข้อมูล ไดรฟ์, Gmail และปฏิทิน แล้วคลิกต่อไป

5745607f3c43d5c0.png

  1. ในการกำหนดราคา ให้เลือกรูปแบบการกำหนดราคาที่ต้องการ แล้วคลิกสร้าง เราขอแนะนำให้ใช้การกำหนดราคาทั่วไปในบริบทของโค้ดแล็บนี้
  2. ระบบจะสร้างแอปและเปลี่ยนเส้นทางคุณไปยังแอปพลิเคชัน AI > แอป > Codelab > ภาพรวมแอป โดยอัตโนมัติ
  3. ไปที่ที่เก็บข้อมูลที่เชื่อมต่อ
  4. หลังจากผ่านไป 2-3 นาที สถานะที่เก็บข้อมูลที่เชื่อมต่อทั้งหมดควรเป็นใช้งานอยู่

d53ed9d9d1ced955.png

กำหนดค่าวิดเจ็ตเว็บ

กำหนดค่าลักษณะที่ปรากฏและลักษณะการทำงานของวิดเจ็ตค้นหา

  1. ไปที่การกำหนดค่า
  2. ในแท็บ UI ให้ตั้งค่าประเภทการค้นหาเป็นค้นหาพร้อมคำถามติดตามผล แล้วคลิกบันทึกและเผยแพร่

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, ไดรฟ์), เซิร์ฟเวอร์ Context Protocol (MCP) ของโมเดลการค้นหา Vertex AI ที่ Google จัดการ, ฟังก์ชันเครื่องมือที่กำหนดเองเพื่อส่งข้อความ Google Chat (ผ่าน Google Chat API)
  • เครื่องมือสร้าง Agent: Agent Development Kit (ADK)
  • โฮสต์ของ Agent: Vertex AI Agent Engine
  • UI: ADK Web

แนวคิดการตรวจสอบ

ชุดพัฒนาเอเจนต์ (ADK)

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

Model Context Protocol (MCP)

Model Context Protocol (MCP) เป็นมาตรฐานแบบเปิดที่ออกแบบมาเพื่อเปิดใช้การผสานรวมที่ราบรื่นและปลอดภัยระหว่างแอปพลิเคชัน AI กับแหล่งข้อมูลหรือเครื่องมือต่างๆ ผ่านอินเทอร์เฟซแบบ "พลักแอนด์เพลย์" ที่ใช้ได้ทั่วไป

เครื่องมือฟังก์ชัน

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

ADK Web

ADK Web คือ UI สำหรับนักพัฒนาแอปในตัวที่มาพร้อมกับ ADK SDK เพื่อให้การพัฒนาและการแก้ไขข้อบกพร่องง่ายขึ้น

ตรวจสอบสถาปัตยกรรมโซลูชัน

f14251cca6a19b1f.png

ตรวจสอบซอร์สโค้ด

agent.py

โค้ดต่อไปนี้จะตรวจสอบสิทธิ์กับ Vertex AI, เริ่มต้นเครื่องมือ MCP และ Chat API ของ Vertex AI Search และกำหนดลักษณะการทำงานของเอเจนต์

  1. การตรวจสอบสิทธิ์: ดึง ACCESS_TOKEN จากตัวแปรสภาพแวดล้อมเพื่อตรวจสอบสิทธิ์ MCP และการเรียก API
  2. การตั้งค่าเครื่องมือ: เริ่มต้น 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 ให้เปิดใช้ Vertex AI, Cloud Resource Manager และ Google Chat API โดยทำดังนี้

60bae4065338c5bf.png

  1. คลิกเมนู ☰ > API และบริการ > API และบริการที่เปิดใช้ แล้วตรวจสอบว่า Vertex AI API, Cloud Resource Manager API และ Google Chat API อยู่ในรายการ

โซลูชันต้องมีการกำหนดค่าหน้าจอขอความยินยอมดังนี้

  1. ในคอนโซล Google Cloud ให้คลิก เมนู ☰ > แพลตฟอร์มการตรวจสอบสิทธิ์ของ Google > การสร้างแบรนด์

  1. คลิกเริ่มต้นใช้งาน
  2. ในส่วนข้อมูลแอป ให้ตั้งชื่อแอปเป็น Codelab
  3. ในอีเมลสนับสนุนสำหรับผู้ใช้ ให้เลือกอีเมลสนับสนุนที่ผู้ใช้สามารถติดต่อคุณได้หากมีข้อสงสัยเกี่ยวกับการยินยอม
  4. คลิกถัดไป
  5. ในส่วนผู้ชม ให้เลือกภายใน
  6. คลิกถัดไป
  7. ในส่วนข้อมูลติดต่อ ให้ป้อนอีเมลที่คุณต้องการรับการแจ้งเตือนเกี่ยวกับการเปลี่ยนแปลงในโปรเจ็กต์
  8. คลิกถัดไป
  9. ในส่วนเสร็จสิ้น ให้อ่านนโยบายข้อมูลผู้ใช้ของบริการ Google API และหากยอมรับ ให้เลือกฉันยอมรับบริการ Google API: นโยบายข้อมูลผู้ใช้
  10. คลิกต่อไป แล้วคลิกสร้าง

bb53eeb45c51d301.png

  1. ระบบจะบันทึกการกำหนดค่าและเปลี่ยนเส้นทางคุณไปยัง Google Auth Platform > ภาพรวม โดยอัตโนมัติ

ดูข้อมูลเพิ่มเติมได้ที่คู่มือกำหนดค่าความยินยอม OAuth ฉบับเต็ม

สร้างข้อมูลเข้าสู่ระบบไคลเอ็นต์ OAuth

สร้างไคลเอ็นต์ OAuth ของแอปบนเดสก์ท็อปใหม่เพื่อตรวจสอบสิทธิ์ผู้ใช้ในสภาพแวดล้อมในเครื่อง

  1. ในคอนโซล Google Cloud ให้คลิก เพื่อไปที่เมนู ☰ > แพลตฟอร์มการตรวจสอบสิทธิ์ของ Google > ไคลเอ็นต์

  1. คลิก + สร้างไคลเอ็นต์
  2. ในส่วนประเภทแอปพลิเคชัน ให้เลือกแอปเดสก์ท็อป
  3. ตั้งค่าชื่อเป็น 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 ให้ค้นหา 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. เลือกบันทึกข้อผิดพลาดไปยังการบันทึก
  5. คลิกบันทึก

952e7ebcb945f1b2.png

เรียกใช้ Agent ใน 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

ลองใช้ Agent

ยืนยันโฟลว์โดยแชทกับเอเจนต์ที่กำหนดเอง

  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 ในภาษาที่เป็นธรรมชาติได้ภายในบริบทของ UI ของแอป Workspace โดยจะอิงตามองค์ประกอบต่อไปนี้

  • โมเดล: Gemini
  • ข้อมูลและการดำเนินการ: ที่เก็บข้อมูล Vertex AI สำหรับ Google Workspace (ปฏิทิน, Gmail, ไดรฟ์), เซิร์ฟเวอร์ Context Protocol (MCP) ของโมเดลการค้นหา Vertex AI ที่ Google จัดการ, ฟังก์ชันเครื่องมือที่กำหนดเองเพื่อส่งข้อความ Google Chat (ผ่าน Google Chat API)
  • เครื่องมือสร้าง Agent: Agent Development Kit (ADK)
  • โฮสต์ของ Agent: Vertex AI Agent Engine
  • UI: ส่วนเสริม Google Workspace สำหรับ Chat และ Gmail (ขยายไปยังปฏิทิน, ไดรฟ์, เอกสาร, ชีต และสไลด์ได้อย่างง่ายดาย)
  • ส่วนเสริมของ Google Workspace: Apps Script, Vertex AI Agent Engine API, บริบท (ข้อความ Gmail ที่เลือก)

ตรวจสอบแนวคิด

ส่วนเสริมของ Google Workspace

ส่วนเสริมของ Google Workspace คือแอปพลิเคชันที่ปรับแต่งแล้วซึ่งขยายแอปพลิเคชัน Google Workspace อย่างน้อย 1 รายการ (Gmail, Chat, ปฏิทิน, เอกสาร, ไดรฟ์, Meet, ชีต และสไลด์)

Apps Script

Apps Script คือแพลตฟอร์ม JavaScript บนระบบคลาวด์ที่ขับเคลื่อนโดย Google ไดรฟ์ ซึ่งช่วยให้คุณผสานรวมและกำหนดงานอัตโนมัติในผลิตภัณฑ์ต่างๆ ของ Google ได้

เฟรมเวิร์กการ์ด Google Workspace

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

ตรวจสอบสถาปัตยกรรมโซลูชัน

f2fd048ba298f431.png

ตรวจสอบซอร์สโค้ด

Agent

agent.py

โค้ดต่อไปนี้จะตรวจสอบสิทธิ์กับ Vertex AI, เริ่มต้นเครื่องมือ MCP และ Chat API ของ Vertex AI Search และกำหนดลักษณะการทำงานของเอเจนต์

  1. การตรวจสอบสิทธิ์: ใช้ฟังก์ชันตัวช่วย _get_access_token_from_context เพื่อดึงโทเค็นการตรวจสอบสิทธิ์ (CLIENT_AUTH_NAME) ที่ไคลเอ็นต์แทรก โทเค็นนี้มีความสําคัญอย่างยิ่งต่อการเรียกใช้บริการดาวน์สตรีมอย่างปลอดภัย เช่น Vertex AI Search MCP และเครื่องมือ Google Chat
  2. การตั้งค่าเครื่องมือ: เริ่มต้น 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 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. Delegates to Agent: เรียก 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. สร้าง UI: 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

โค้ดต่อไปนี้จัดระเบียบการเรียก API ไปยัง Vertex AI

  1. จัดระเบียบการเรียก API: queryAgent เป็นตัวเชื่อมระหว่างส่วนเสริมกับ Vertex AI Agent Engine โดยจะสร้างคำขอที่มีคำค้นหาของผู้ใช้และโทเค็นการให้สิทธิ์ในสถานะ
  2. สตรีมคำตอบ: เนื่องจากคำตอบของเอเจนต์อาจใช้เวลาสักครู่ จึงใช้ streamQuery API กับเหตุการณ์ที่เซิร์ฟเวอร์ส่ง (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 };
}
...

ติดตั้งใช้งาน Agent ใน 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. คลิกเมนู ☰ > IAM และผู้ดูแลระบบ > บัญชีบริการ > + สร้างบัญชีบริการ

  1. ตั้งชื่อบัญชีบริการเป็น vertexai-add-on

46be0eb53f416c59.png

  1. คลิกเสร็จสิ้น ระบบจะเปลี่ยนเส้นทางคุณไปยังหน้าบัญชีบริการ และคุณจะเห็นบัญชีบริการที่สร้างขึ้น

f002fef61c71ed8.png

  1. เลือกบัญชีบริการที่สร้างใหม่ แล้วเลือกแท็บคีย์
  2. คลิกเพิ่มคีย์ แล้วคลิกสร้างคีย์ใหม่
  3. เลือก JSON แล้วคลิกสร้าง

7b140535d9e1af44.png

  1. กล่องโต้ตอบจะปิดลง และระบบจะดาวน์โหลดคู่คีย์สาธารณะ/ส่วนตัวที่สร้างขึ้นใหม่ลงในสภาพแวดล้อมในเครื่องโดยอัตโนมัติเป็นไฟล์ JSON

สร้างและกำหนดค่าโปรเจ็กต์ Apps Script

สร้างโปรเจ็กต์ Apps Script ใหม่เพื่อโฮสต์โค้ดส่วนเสริมและกำหนดค่าพร็อพเพอร์ตี้การเชื่อมต่อ

  1. คลิกปุ่มต่อไปนี้เพื่อเปิดโปรเจ็กต์ Apps Script ของส่วนเสริม Enterprise AI

  1. คลิกภาพรวม > ทำสำเนา
  2. ในโปรเจ็กต์ Apps Script ให้คลิกการตั้งค่าโปรเจ็กต์ > แก้ไขพร็อพเพอร์ตี้สคริปต์ > เพิ่มพร็อพเพอร์ตี้สคริปต์เพื่อเพิ่มพร็อพเพอร์ตี้สคริปต์
  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. คลิกติดตั้งใช้งาน > ทดสอบการติดตั้งใช้งาน แล้วคลิกติดตั้ง ซึ่งตอนนี้พร้อมให้ใช้งานใน Gmail แล้ว
  2. คลิกคัดลอกในส่วนรหัสการทำให้ใช้งานได้ของส่วนหัว

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. เปิดพื้นที่ข้อความส่วนตัวด้วยแอป 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 เพื่อหลีกเลี่ยงการเรียกเก็บเงินจากบัญชี Google Cloud สำหรับทรัพยากรที่ใช้ในโค้ดแล็บนี้

ในคอนโซล Google Cloud ให้ทำตามขั้นตอนต่อไปนี้

  1. คลิกเมนู ☰ > IAM และผู้ดูแลระบบ > การตั้งค่า

  1. คลิกปิดเครื่อง
  2. ป้อนรหัสโปรเจ็กต์
  3. คลิกปิดเครื่องต่อไป

3b9492d97f771b2c.png

7. ขอแสดงความยินดี

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

ขั้นตอนต่อไปคืออะไร

เราจะแสดงเฉพาะกรณีการใช้งานที่พบบ่อยที่สุดใน Codelab นี้ แต่ก็ยังมีขอบเขตการขยายอีกมากมายที่คุณอาจต้องการพิจารณาในโซลูชันของคุณ เช่น

  • ใช้เครื่องมือสำหรับนักพัฒนาแอปที่ทำงานด้วยระบบ AI เช่น Gemini CLI และ Antigravity
  • ผสานรวมกับเฟรมเวิร์กและเครื่องมือของเอเจนต์อื่นๆ เช่น MCP ที่กำหนดเอง การเรียกใช้ฟังก์ชันที่กำหนดเอง และ UI แบบ Generative
  • ผสานรวมกับโมเดล AI อื่นๆ รวมถึงโมเดลที่กำหนดเองซึ่งโฮสต์อยู่ในแพลตฟอร์มเฉพาะ เช่น Vertex AI
  • ผสานรวมกับเอเจนต์อื่นๆ ที่โฮสต์ในแพลตฟอร์มเฉพาะ เช่น Dialogflow หรือโดยบุคคลที่สามผ่าน Cloud Marketplace
  • เผยแพร่เอเจนต์ใน Cloud Marketplace เพื่อเพิ่มศักยภาพให้กับทีม องค์กร หรือผู้ใช้ทั่วไป

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

นักพัฒนาซอฟต์แวร์สามารถเข้าถึงแหล่งข้อมูลมากมาย เช่น วิดีโอบน YouTube, เว็บไซต์เอกสารประกอบ, ตัวอย่างโค้ด และบทแนะนำ