1. ก่อนเริ่มต้น
สมมติว่าคุณทำงานในบริษัทด้านการดูแลสุขภาพที่มีข้อมูลจำนวนมากเกี่ยวกับบันทึกการนัดหมาย ซึ่งรวมถึง Structured Data เช่น วันที่และรหัสผู้ให้บริการ ตลอดจน Unstructured Data เช่น บันทึกของแพทย์และข้อความของผู้ป่วย คุณต้องการให้พนักงานใช้ภาษาธรรมชาติเพื่อดึงข้อมูลที่ต้องการ แทนที่จะให้พนักงานคัดกรองข้อมูลนี้ด้วยตนเองหรือเขียนการค้นหา SQL ของตนเอง เช่น "แสดงรายชื่อผู้ป่วยทั้งหมดที่ได้รับใบสั่งยาให้กินไอศกรีมในช่วง 30 วันที่ผ่านมา" หรือ "ค้นหาผู้ป่วยทั้งหมดของ นพ. X ที่ไม่ได้มาติดตามผลในช่วงปีที่ผ่านมา"
ใน Codelab นี้ คุณจะสร้างและติดตั้งใช้งาน Agent ด้วย Agent Development Kit (ADK) ที่สามารถโต้ตอบกับฐานข้อมูล Cloud Spanner เพื่อแสดงภาพรวมของฐานข้อมูลและทำการให้เหตุผลเชิงความหมาย
ADK เป็นเฟรมเวิร์กแบบโอเพนซอร์สที่เน้นโค้ดเป็นหลัก ซึ่งออกแบบมาเพื่อสร้าง ประเมิน และติดตั้งใช้งานแอปพลิเคชันแบบ Multi-Agent ที่ยืดหยุ่น Cloud Spanner เป็นฐานข้อมูลที่มีการจัดการครบวงจร มีการกระจายทั่วโลก และปรับขนาดได้ในแนวนอน ซึ่งให้ความหมายเชิงสัมพันธ์พร้อมความสามารถในการค้นหาเวกเตอร์และ AI ในตัว
การรวม ADK เข้ากับ Spanner ช่วยให้ AI Agent ของ Generative AI สามารถค้นพบสคีมาฐานข้อมูล ดำเนินการค้นหาที่มีโครงสร้าง และทำการค้นหาความคล้ายคลึงกันทางความหมายแบบเรียลไทม์ในข้อมูลการดำเนินงานของคุณได้แบบไดนามิก
แม้ว่า Codelab นี้จะใช้ตัวอย่างด้านการดูแลสุขภาพที่สมมติขึ้น แต่ก็มีแอปพลิเคชันที่เป็นไปได้มากมายสำหรับสถานการณ์นี้ ซึ่งรวมถึงคำขอแจ้งปัญหาการสนับสนุนลูกค้า ข้อมูลอีคอมเมิร์ซ และอื่นๆ
สิ่งที่คุณจะทำ
คุณจะสร้าง Agent ด้านการดูแลสุขภาพที่เชื่อมต่อกับฐานข้อมูล Spanner โดยใช้ SpannerToolset ของ ADK Agent จะตรวจสอบสคีมาตารางและสร้างคำค้นหา SQL เพื่อตอบคำถามในภาษาธรรมชาติโดยใช้การค้นหาความคล้ายคลึงกันของเวกเตอร์ หลังจากทดสอบ Agent ในเครื่องแล้ว คุณจะติดตั้งใช้งาน Agent ใน Cloud Run
สิ่งที่คุณจะได้เรียนรู้
- วิธีสร้างฐานข้อมูล Spanner และเพิ่มคอลัมน์การฝัง
- วิธีกำหนดค่า
SpannerToolsetและSpannerToolSettingsของ ADK - วิธีเปิดใช้เครื่องมือตรวจสอบข้อมูลเมตาของฐานข้อมูล, การดำเนินการ SQL และการค้นหาความคล้ายคลึงกันของเวกเตอร์
- วิธีทดสอบ Agent โดยใช้
adk web - วิธีทำให้ Agent ใช้งานได้ด้วย Cloud Run และเรียกใช้การค้นหาไปยัง Agent เวอร์ชันที่ใช้งานจริง
สิ่งที่คุณต้องมี
- โปรเจ็กต์ Google Cloud ที่เปิดใช้การเรียกเก็บเงิน
- เว็บเบราว์เซอร์ เช่น Google Chrome
- มีความคุ้นเคยกับแนวคิดพื้นฐานของ Python และ SQL
2. ตั้งค่าสภาพแวดล้อม
สร้างโปรเจ็กต์ Google Cloud
- ในคอนโซล Google Cloud ในหน้าตัวเลือกโปรเจ็กต์ ให้เลือกหรือสร้างโปรเจ็กต์ Google Cloud
- ตรวจสอบว่าได้เปิดใช้การเรียกเก็บเงินสำหรับโปรเจ็กต์ที่อยู่ในระบบคลาวด์แล้ว ดูวิธีตรวจสอบว่าได้เปิดใช้การเรียกเก็บเงินในโปรเจ็กต์แล้วหรือยัง
เริ่มต้น Cloud Shell
Cloud Shell เป็นสภาพแวดล้อมบรรทัดคำสั่งในเบราว์เซอร์ที่ทำงานใน Google Cloud ซึ่งมาพร้อมกับ gcloud, Python และเครื่องมือสำหรับนักพัฒนาซอฟต์แวร์ที่จำเป็นอื่นๆ
- คลิกเปิดใช้งาน Cloud Shell ที่ด้านบนของคอนโซล Google Cloud

- เมื่อเชื่อมต่อกับ Cloud Shell แล้ว ให้ยืนยันการตรวจสอบสิทธิ์ที่ใช้งานอยู่โดยทำดังนี้
gcloud auth list - ยืนยันว่าได้กำหนดค่าโปรเจ็กต์เริ่มต้นแล้ว โดยทำดังนี้
gcloud config get project - หากไม่ได้ตั้งค่าโปรเจ็กต์ ให้กำหนดค่าด้วยคำสั่งต่อไปนี้
export GOOGLE_CLOUD_PROJECT=<YOUR_GOOGLE_CLOUD_PROJECT> gcloud config set project $GOOGLE_CLOUD_PROJECT
เปิดใช้ Google Cloud API ที่จำเป็น
คุณต้องมีสิทธิ์เข้าถึงบริการบางอย่างเพื่อใช้งานห้องทดลองนี้ เปิดใช้ API ที่จำเป็นทั้งหมดใน Cloud Shell โดยทำดังนี้
gcloud services enable spanner.googleapis.com aiplatform.googleapis.com run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com
ตรวจสอบว่าการดำเนินการเสร็จสมบูรณ์แล้ว โดยทำดังนี้
Operation "operations/..." finished successfully.
ตั้งค่าตัวแปรสภาพแวดล้อม
กำหนดค่าตัวแปรสภาพแวดล้อมเพื่อบอกให้ ADK ใช้โปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google และฐานข้อมูล Spanner ดังนี้
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
export GOOGLE_CLOUD_LOCATION="us"
export GOOGLE_GENAI_USE_VERTEXAI=True
export SPANNER_INSTANCE_ID="healthcare"
export SPANNER_DATABASE_ID="medical-db"
ตรวจสอบสิทธิ์ด้วย gcloud
เรียกใช้คำสั่งต่อไปนี้เพื่อให้แน่ใจว่าสภาพแวดล้อม Cloud Shell ได้รับการตรวจสอบสิทธิ์แล้ว
gcloud auth application-default login
3. สร้างอินสแตนซ์และฐานข้อมูล Spanner
ใน Codelab นี้ คุณจะสร้างอินสแตนซ์และฐานข้อมูล Spanner ในคอนโซล Cloud นอกจากนี้ คุณยังสร้างฐานข้อมูลแบบเป็นโปรแกรมได้ด้วย เช่น ใช้ไคลเอ็นต์ Spanner Python
สร้างอินสแตนซ์และฐานข้อมูล Spanner
ไปที่หน้า Spanner ในคอนโซล Cloud แล้วสร้างอินสแตนซ์แบบไม่มีค่าใช้จ่าย พิมพ์ healthcare เป็นทั้ง "ชื่ออินสแตนซ์" และ "รหัสอินสแตนซ์" แล้วเลือก us-central1 เป็นภูมิภาค จากนั้นคลิกสร้างอินสแตนซ์ที่ไม่มีค่าใช้จ่าย

สร้างฐานข้อมูลและสคีมา
จากนั้นไปที่หน้าสำหรับอินสแตนซ์ที่คุณเพิ่งสร้าง แล้วคลิกสร้างฐานข้อมูล

ตั้งชื่อฐานข้อมูล medical-db โดยเลือก Google SQL มาตรฐาน ไว้ แล้วคลิกสร้าง

ถัดไป คุณจะสร้างตารางและเพิ่มข้อมูลตัวอย่างลงในฐานข้อมูล
4. ป้อนข้อมูลจากการสุ่มตัวอย่างและสร้างคอลัมน์การฝัง
เมื่อสร้างฐานข้อมูลแล้ว คุณจะใช้ Spanner Studio ในคอนโซล Cloud เพื่อสร้างตารางและแทรกข้อมูลจากการสุ่มตัวอย่าง
สร้างตาราง
ในแถบเมนูด้านซ้ายภายในฐานข้อมูล medical-db ให้คลิก Spanner Studio Spanner Studio มี UI สำหรับเรียกใช้การค้นหา SQL เพื่อสร้างตาราง แทรก และค้นหาข้อมูล
คลิกแท็บการค้นหาที่ไม่มีชื่อใน Spanner Studio

ถัดไป คุณจะสร้างตาราง 4 ตารางเพื่อเก็บข้อมูลด้านการดูแลสุขภาพ ได้แก่ Providers, Patients, Appointments และ Prescriptions ตาราง Providers จะเป็นตารางอิสระ และตาราง Patients จะเป็นตารางหลักสำหรับ Appointments และ Prescriptions ตาราง Appointments และ Prescriptions จะสลับกัน ซึ่งหมายความว่าระบบจะจัดเก็บตารางทั้งสองไว้ในเซิร์ฟเวอร์เดียวกับตาราง Patients ระดับบนสุดเพื่อให้ค้นหาได้เร็วขึ้น
คัดลอกการค้นหา SQL ต่อไปนี้ลงในเครื่องมือแก้ไขเพื่อสร้างตาราง 4 ตาราง
-- 1. Create the independent Providers table
CREATE TABLE Providers (
ProviderId INT64 NOT NULL,
ProviderName STRING(MAX),
Specialty STRING(MAX)
) PRIMARY KEY (ProviderId);
-- 2. Create the parent Patients table
CREATE TABLE Patients (
PatientId INT64 NOT NULL,
FirstName STRING(MAX),
LastName STRING(MAX),
DateOfBirth DATE
) PRIMARY KEY (PatientId);
-- 3. Create the interleaved Appointments table
CREATE TABLE Appointments (
PatientId INT64 NOT NULL,
AppointmentId INT64 NOT NULL,
ProviderId INT64,
AppointmentDate DATE,
Status STRING(MAX),
DoctorNotes STRING(MAX),
DoctorNotesEmbedding ARRAY<FLOAT32>(vector_length=>768)
) PRIMARY KEY (PatientId, AppointmentId),
INTERLEAVE IN PARENT Patients ON DELETE CASCADE;
-- 4. Create the interleaved Prescriptions table
CREATE TABLE Prescriptions (
PatientId INT64 NOT NULL,
PrescriptionId INT64 NOT NULL,
ProviderId INT64 NOT NULL,
MedicationName STRING(MAX),
DatePrescribed DATE
) PRIMARY KEY (PatientId, PrescriptionId),
INTERLEAVE IN PARENT Patients ON DELETE CASCADE;
คลิกเรียกใช้เพื่อเรียกใช้การค้นหา CREATE TABLE รายการ เมื่อการค้นหาเสร็จสมบูรณ์ คุณจะเห็นตารางใหม่ 4 ตารางใน Explorer การนําทางด้านซ้าย ดังนี้

ยังไม่มีข้อมูลในรายงาน มาเพิ่มข้อมูลกันเลย
แทรกข้อมูลตัวอย่าง
เปิดแท็บการค้นหาใหม่ใน Spanner Studio โดยคลิกไอคอน + คัดลอก SQL ต่อไปนี้เพื่อแทรกข้อมูลปลอม 10 แถวลงในตารางทั้ง 4 ตาราง
INSERT INTO Providers (ProviderId, ProviderName, Specialty)
VALUES
(1, 'Dr. Aris Thorne', 'Culinary Diagnostics'),
(2, 'Dr. Beatrice Plum', 'Chronological Confusion'),
(3, 'Dr. Caspian Vane', 'Gravity Resistance'),
(4, 'Dr. Delilah Frost', 'Acute Dessert Therapy'),
(5, 'Dr. Eldon Rook', 'Somnambulant Gymnastics'),
(6, 'Dr. Fiona Gale', 'Over-enthusiastic Sneezing'),
(7, 'Dr. Gideon Vance', 'Extreme Couch Potato-ism'),
(8, 'Dr. Hazel Quinn', 'Spontaneous Melody Outbreaks'),
(9, 'Dr. Ignatius Flint', 'Stubbed Toe Trauma'),
(10, 'Dr. Juniper Slate', 'Advanced Broccoli Administration');
INSERT INTO Patients (PatientId, FirstName, LastName, DateOfBirth)
VALUES
(1, 'Barnaby', 'Quigley', DATE '1982-04-12'),
(2, 'Seraphina', 'Pockets', DATE '1995-11-23'),
(3, 'Thaddeus', 'Plumbob', DATE '1978-01-30'),
(4, 'Marigold', 'Swoon', DATE '2002-08-14'),
(5, 'Silas', 'Fiddlewood', DATE '1965-06-05'),
(6, 'Clementine', 'Fizz', DATE '1988-12-10'),
(7, 'Orville', 'Snipe', DATE '1971-03-22'),
(8, 'Rosalind', 'Furlong', DATE '1999-07-07'),
(9, 'Percival', 'Gout', DATE '1955-09-18'),
(10, 'Elara', 'Moonbeam', DATE '2010-02-28');
INSERT INTO Appointments (PatientId, AppointmentId, ProviderId, AppointmentDate, Status, DoctorNotes)
VALUES
(1, 101, 1, DATE '2026-10-01', 'Completed', 'Patient complains of tasting the color blue. Prescribed 14 hours of video games and a large pizza.'),
(2, 102, 3, DATE '2026-10-02', 'Completed', 'Patient accidentally swallowed a cloud. Floating slightly above the exam table. Needs a heavy lunch to weigh her down.'),
(3, 103, 2, DATE '2026-10-03', 'Completed', 'Patient has developed a severe allergy to Mondays. Breaking out in hives when looking at a calendar.'),
(4, 104, 6, DATE '2026-10-04', 'Completed', 'Patient reports excessive glitter in bloodstream after crafting accident. Sparkles violently when sneezing.'),
(5, 105, 5, DATE '2026-10-05', 'Completed', 'Diagnosed with resting confused face. Patient forgot why he came to the clinic in the first place.'),
(6, 106, 4, DATE '2026-10-06', 'Scheduled', 'Severe case of ice cream withdrawal. Symptoms include whining, shivering, and aggressively pointing at freezers.'),
(7, 107, 7, DATE '2026-10-07', 'Completed', 'Patient left leg has fallen asleep and refuses to wake up without a bedtime story.'),
(8, 108, 8, DATE '2026-10-08', 'Completed', 'Uncontrollable urge to tap dance when hearing elevator music. Ankles are showing signs of extreme wear.'),
(9, 109, 9, DATE '2026-10-09', 'Scheduled', 'Patient believes his eyebrows are trying to escape. Taped them down pending further review.'),
(10, 110, 10, DATE '2026-10-10', 'Completed', 'Diagnosed with acute vegetable aversion. Emits a high-pitched frequency when placed within 10 feet of broccoli.');
INSERT INTO Prescriptions (PatientId, PrescriptionId, ProviderId, MedicationName, DatePrescribed)
VALUES
(1, 201, 1, 'Extra Cheese Pepperoni Pizza (Taken orally)', DATE '2026-10-01'),
(2, 202, 3, 'Lead-weighted Boots (Wear daily)', DATE '2026-10-02'),
(3, 203, 2, 'Time Machine set to Tuesday (Use once)', DATE '2026-10-03'),
(4, 204, 6, 'Vacuum Cleaner on Reverse Mode (Apply to nose)', DATE '2026-10-04'),
(5, 205, 5, 'A Map and a Compass (Consult twice daily)', DATE '2026-10-05'),
(6, 206, 4, 'Three Scoops of Neapolitan Ice Cream (Stat!)', DATE '2026-10-06'),
(7, 207, 7, 'Collection of Fairy Tales (Read to leg at 9PM)', DATE '2026-10-07'),
(8, 208, 8, 'Noise Cancelling Headphones (Wear near lobbies)', DATE '2026-10-08'),
(9, 209, 9, 'Heavy Duty Masking Tape (Apply to forehead)', DATE '2026-10-09'),
(10, 210, 10, 'Chocolate-Covered Broccoli (To trick the system, eat with caution)', DATE '2026-10-10');
คลิกเรียกใช้ เมื่อการค้นหาการแทรกเสร็จสมบูรณ์ คุณจะดูตัวอย่างข้อมูลสำหรับตารางได้โดยไปที่แท็บภาพรวมของ Spanner แล้วเลื่อนลงไปที่แท็บตาราง
คลิกตารางใดก็ได้ เช่น Prescriptions แล้วไปที่แท็บ Data ในการนำทางด้านซ้ายเพื่อดูตัวอย่างข้อมูล ดังนี้

สร้างการฝังเวกเตอร์ใน Spanner
เมื่อสร้างและแทรกข้อมูลลงในตาราง Appointments คุณได้สร้างคอลัมน์ DoctorNotesEmbedding ซึ่งปัจจุบันว่างเปล่า เพื่อให้โมเดลเข้าใจข้อความรูปแบบอิสระในคอลัมน์ DoctorNotes คุณต้องแปลงข้อความเป็นเวกเตอร์การฝัง ซึ่งเป็นการแสดงข้อความในรูปแบบตัวเลขในอาร์เรย์หรือเวกเตอร์
หากต้องการสร้างคอลัมน์การฝัง คุณต้องสร้างโมเดลการฝังข้อความในฐานข้อมูลก่อน กลับไปที่ Spanner Studio เปิดแท็บการค้นหาใหม่ แล้ววางโค้ดต่อไปนี้
-- Create a text embedding model
CREATE OR REPLACE MODEL TextEmbeddingModel
INPUT(content STRING(MAX))
OUTPUT(embeddings STRUCT<values ARRAY<FLOAT32>>)
REMOTE OPTIONS(
endpoint = '//aiplatform.googleapis.com/projects/YOUR_PROJECT_ID/locations/us-central1/publishers/google/models/text-embedding-005'
);
ถัดไป ในการค้นหาใหม่ใน Spanner Studio คุณจะสร้างการฝังจากคอลัมน์ DoctorNotes โดยใช้โมเดลที่เพิ่งสร้างและแทรกลงในคอลัมน์ DoctorNotesEmbedding สำหรับแต่ละแถว
UPDATE Appointments
SET DoctorNotesEmbedding = (
SELECT embeddings.values
FROM ML.PREDICT(
MODEL TextEmbeddingModel,
(SELECT DoctorNotes AS content)
)
)
WHERE DoctorNotes IS NOT NULL AND DoctorNotesEmbedding IS NULL;
ดูตัวอย่างข้อมูลการฝัง
ไปที่แท็บข้อมูลสำหรับตารางการนัดหมาย แล้วคุณจะเห็นคอลัมน์ DoctorNotesEmbedding ปรากฏขึ้น

เมื่อสร้างอินสแตนซ์ ฐานข้อมูล และตาราง Spanner แล้ว คุณก็พร้อมที่จะสร้าง Agent ที่สามารถเข้าถึงและอ่านข้อมูลจากอินสแตนซ์ ฐานข้อมูล และตาราง Spanner ได้อย่างปลอดภัย
5. สร้าง Agent เพื่อสรุปฐานข้อมูล Spanner
สร้างโครงสร้างไดเรกทอรี
ก่อนอื่น คุณจะต้องสร้าง Agent ADK แบบง่ายที่สามารถสรุปข้อมูลเมตาเกี่ยวกับตารางได้
ก่อนอื่น ให้ตรวจสอบว่าคุณได้ติดตั้ง google-adk เวอร์ชันล่าสุดแล้ว เรียกใช้คำสั่งนี้ในเทอร์มินัล Cloud Shell
pip install --upgrade google-adk
จากนั้นเรียกใช้คำสั่งต่อไปนี้เพื่อสร้างไดเรกทอรีใน Cloud Shell สำหรับโค้ดของ Agent
cd ~ mkdir healthcare_agents mkdir healthcare_agents/basic_spanner_agent touch healthcare_agents/basic_spanner_agent/agent.py
ซึ่งจะสร้างโครงสร้างไดเรกทอรีต่อไปนี้ใน Cloud Shell
+ healthcare_agents
+ basic_spanner_agent
+ agent.py
หากต้องการสร้าง Agent เพิ่มเติม คุณสามารถเพิ่มไดเรกทอรีในรูท healthcare_agents/ ตามรูปแบบนี้
นี่คือโครงสร้างไดเรกทอรีที่ ADK Web ค้นหา คุณจะใช้ข้อมูลดังกล่าวเพื่อทดสอบ Agent ในขั้นตอนถัดไป
เพิ่มรหัสตัวแทน
เปิดเครื่องมือแก้ไข Cloud Shell โดยคลิกปุ่มเปิดเครื่องมือแก้ไขที่ด้านบนของ Cloud Shell คุณจะใช้ปุ่มนี้เพื่อสลับไปมาระหว่างเทอร์มินัลและเครื่องมือแก้ไขตลอดทั้ง Codelab นี้
เปิดไฟล์ healthcare_agents/basic_spanner_agent/agent.py ที่เพิ่งสร้างขึ้นและวางโค้ดต่อไปนี้
import os
import sys
import asyncio
import google.auth
from google.auth.transport.requests import Request
from google.adk.agents import Agent
from google.adk.tools.spanner import client as spanner_client_module
from google.adk.tools.spanner.settings import SpannerToolSettings, Capabilities
from google.adk.tools.spanner.spanner_credentials import SpannerCredentialsConfig
from google.adk.tools.spanner.spanner_toolset import SpannerToolset
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
INSTANCE_ID = os.environ.get("SPANNER_INSTANCE_ID", "healthcare")
DATABASE_ID = os.environ.get("SPANNER_DATABASE_ID", "medical-db")
# --- Cloud Shell Workaround ---
# Because we are running in Cloud Shell, we need to apply a small patch to prevent
# the local proxy from deadlocking Spanner's gRPC cleanup.
# You do not need this in standard production environments like Cloud Run or your local laptop.
if hasattr(spanner_client_module, "_close_spanner_resources"):
spanner_client_module._close_spanner_resources = lambda *args, **kwargs: None
# --- Auth ---
try:
application_default_credentials, _ = google.auth.default()
if not application_default_credentials.valid:
application_default_credentials.refresh(Request())
except Exception as e:
print(f"\n[ERROR] Failed to authenticate: {e}", flush=True)
sys.exit(1)
# --- Spanner Tool config ---
credentials_config = SpannerCredentialsConfig(credentials=application_default_credentials)
tool_settings = SpannerToolSettings(capabilities=[Capabilities.DATA_READ])
spanner_toolset = SpannerToolset(credentials_config=credentials_config, spanner_tool_settings=tool_settings)
root_agent = Agent(
model="gemini-3.8-flash",
name="spanner_healthcare_agent",
description="Agent to answer questions about Spanner database and execute SQL queries.",
instruction=f"""
You are a data assistant agent with access to several Spanner tools.
Make use of those tools to answer the user's questions.
When using your tools, always use the following default database configuration:
- project_id: {PROJECT_ID}
- instance_id: {INSTANCE_ID}
- database_id: {DATABASE_ID}
""",
tools=[
spanner_toolset,
],
)
สิ่งที่จะเกิดขึ้นในโค้ดที่คุณเพิ่งเพิ่มมีดังนี้
- คุณใช้ไลบรารี
google.authเพื่อตรวจสอบสิทธิ์ และส่งข้อมูลเข้าสู่ระบบเหล่านั้นไปยังSpannerCredentialsConfigซึ่ง Agent จะใช้เพื่อเข้าถึงฐานข้อมูล Spanner - คุณสร้างอินสแตนซ์
SpannerToolSettingsและให้สิทธิ์เข้าถึงDATA_READซึ่งจะช่วยให้ตัวแทนมีสิทธิ์อ่านตารางทั้งหมดในอินสแตนซ์ Spanner หากต้องการจำกัดสิทธิ์เข้าถึงตารางที่เฉพาะเจาะจงของ Agent โปรดดูขั้นตอนที่ไม่บังคับที่ส่วนท้ายของ Codelab นี้ - คุณสร้างอินสแตนซ์
SpannerToolsetซึ่งจะทำให้ Agent มีสิทธิ์เข้าถึงเครื่องมือ Spanner ทั้งหมดที่มี เช่นlist_table_namesและget_table_schemaดูรายการทั้งหมดได้ในเอกสารประกอบ - คุณสร้างอินสแตนซ์
Agentใน ADK และระบุโมเดล ชื่อ คำอธิบาย คำสั่ง และให้สิทธิ์เข้าถึงSpannerToolsetที่เรากำหนดไว้ก่อนหน้านี้
6. ทดสอบ Agent ใน ADK Web
คุณใช้ ADK Web เพื่อทดสอบ Agent ในเครื่องได้ ADK Web เป็น UI แบบภาพสำหรับตรวจสอบและแก้ไขข้อบกพร่องของ Agent จากเทอร์มินัล Cloud Shell ให้เรียกใช้คำสั่งต่อไปนี้เพื่อไปยังไดเรกทอรีราก
cd ~
จากนั้นเรียกใช้คำสั่ง adk web นี้เพื่อเปิดเว็บเซิร์ฟเวอร์ ADK เมื่อเรียกใช้คำสั่งนี้ ระบบอาจแจ้งให้คุณเปิดใช้การส่งข้อมูลทางไกล คุณเลือกได้ว่าจะเปิดใช้หรือไม่เมื่อได้รับข้อความแจ้ง
adk web --allow_origins="regex:.*" --session_service_uri="memory://" healthcare_agents
คุณควรเห็นบันทึกที่คล้ายกับตัวอย่างนี้
+-----------------------------------------------------------------------------+ | ADK Web Server started | | | | For local testing, access at http://127.0.0.1:8000. | +-----------------------------------------------------------------------------+ INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
คลิก CMD + URL ของ Localhost เพื่อเปิดแท็บใหม่ในเบราว์เซอร์ จากเมนูแบบเลื่อนลงที่ด้านบน ให้เลือก basic_spanner_agent ที่คุณเพิ่งสร้าง ซึ่งจะเปิด UI แชทที่คุณสามารถส่งคำถามไปยังตัวแทนได้ พิมพ์ "สรุปตารางใน medical-db"
คุณควรเห็นเครื่องมือทั้งหมดที่ Agent เรียกใช้พร้อมกับคำตอบ ดังนี้

คุณสามารถใช้ ADK Web เพื่อทดสอบคำค้นหาเพิ่มเติมเกี่ยวกับฐานข้อมูลและตารางได้
หากต้องการออกจาก ADK Web ให้หยุดกระบวนการในเทอร์มินัล Cloud Shell โดยพิมพ์ CTRL + C
7. สร้าง Agent การค้นหาเชิงความหมายของ Spanner
ตอนนี้คุณได้สร้าง Agent พื้นฐานที่สามารถสรุปข้อมูลเกี่ยวกับอินสแตนซ์ ฐานข้อมูล และตาราง Spanner แล้ว เรามาสร้าง Agent ที่สามารถวิเคราะห์ข้อความที่ไม่มีโครงสร้างในฐานข้อมูลกัน เพื่อให้ทุกคนในทีมวิเคราะห์บันทึกผู้ป่วยได้โดยไม่ต้องเขียนการค้นหา SQL ตัวแทนของคุณควรจะสามารถรับการค้นหาด้วยภาษาธรรมชาติและใช้คอลัมน์การฝังเวกเตอร์ที่คุณสร้างไว้ก่อนหน้านี้เพื่อทำการค้นหาเวกเตอร์ในข้อมูลบันทึกของแพทย์ได้
กำลังเขียนโค้ด Agent
หากต้องการสร้างไดเรกทอรีใหม่สำหรับ Semantic Agent ให้เรียกใช้คำสั่งต่อไปนี้ในเทอร์มินัล Cloud Shell
cd ~
mkdir healthcare_agents/semantic_agent
touch healthcare_agents/semantic_agent/agent.py
ไปที่เครื่องมือแก้ไข Cloud Shell (คุณอาจต้องโหลดซ้ำ) แล้วเปิดไฟล์ healthcare_agents/semantic_agent/agent.py ที่ว่างเปล่าซึ่งคุณเพิ่งสร้างขึ้น จากนั้นเพิ่มเนื้อหาต่อไปนี้
import os
import sys
import asyncio
import google.auth
from google.auth.transport.requests import Request
from google.adk.agents import Agent
from google.adk.tools.spanner import utils as spanner_utils
from google.adk.tools.spanner import client as spanner_client_module
from google.adk.tools.spanner.settings import SpannerToolSettings, Capabilities, SpannerVectorStoreSettings
from google.adk.tools.spanner.spanner_credentials import SpannerCredentialsConfig
from google.adk.tools.spanner.spanner_toolset import SpannerToolset
from google.genai import Client
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
INSTANCE_ID = os.environ.get("SPANNER_INSTANCE_ID", "healthcare")
DATABASE_ID = os.environ.get("SPANNER_DATABASE_ID", "medical-db")
# --- Cloud Shell Workaround ---
# Because we are running in Cloud Shell, we need to apply a small patch to prevent
# the local proxy from deadlocking Spanner's gRPC cleanup.
# You do not need this in standard production environments like Cloud Run or your local laptop.
if hasattr(spanner_client_module, "_close_spanner_resources"):
spanner_client_module._close_spanner_resources = lambda *args, **kwargs: None
# Because text-embedding-005 uses a regional endpoint (i.e. 'us-central1')
# and gemini-3.8-flash uses a multi-regional endpoint (i.e. 'us')
# We need the following patch to pass the correct region to the embedding model
async def _patched_embed_contents_async(vertex_ai_embedding_model_name: str, contents: list[str], output_dimensionality: int | None = None, genai_client: Client | None = None):
regional_client = Client(vertexai=True, project=PROJECT_ID, location="us-central1")
return await asyncio.to_thread(
spanner_utils.embed_contents, vertex_ai_embedding_model_name, contents,
output_dimensionality=output_dimensionality, genai_client=regional_client,
)
spanner_utils.embed_contents_async = _patched_embed_contents_async
# --- Auth ---
try:
application_default_credentials, _ = google.auth.default()
if not application_default_credentials.valid:
application_default_credentials.refresh(Request())
except Exception as e:
print(f"\n[ERROR] Failed to authenticate: {e}", flush=True)
sys.exit(1)
# --- Spanner semantic search config ---
credentials_config = SpannerCredentialsConfig(
credentials=application_default_credentials
)
my_vector_store_settings = SpannerVectorStoreSettings(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
database_id=DATABASE_ID,
table_name="Appointments",
content_column="DoctorNotes",
embedding_column="DoctorNotesEmbedding",
vector_length=768,
vertex_ai_embedding_model_name="text-embedding-005",
selected_columns=["PatientId", "ProviderId", "AppointmentDate", "DoctorNotes"],
nearest_neighbors_algorithm="EXACT_NEAREST_NEIGHBORS",
top_k=3,
distance_type="COSINE",
)
my_tool_settings = SpannerToolSettings(
capabilities=[Capabilities.DATA_READ],
vector_store_settings=my_vector_store_settings,
)
my_spanner_toolset = SpannerToolset(
credentials_config=credentials_config,
spanner_tool_settings=my_tool_settings,
tool_filter=["vector_store_similarity_search"],
)
root_agent = Agent(
model="gemini-3.8-flash",
name="doctor_notes_agent",
description="Semantic search agent for medical notes.",
instruction="""
You are a medical assistant that returns patient and provider IDs based on the query.
1. Always use the `spanner_vector_store_similarity_search` tool to find associated IDs.
2. If no relevant information is found, state that no patient notes matched the request.
3. Present the patient ID, provider ID, and relevant doctor notes to make it clear why each patient and provider were returned for a particular search.
""",
tools=[my_spanner_toolset],
)
วิธีการทำงานของ Agent การค้นหาเชิงความหมายมีดังนี้
- คุณกำหนด
SpannerVectorStoreSettingsเพื่อส่งไปยังSpannerToolsetซึ่งจะบอก Agent ดังนี้- ข้อมูลเมตาพื้นฐานเกี่ยวกับอินสแตนซ์ ฐานข้อมูล และตาราง
embedding_column: คอลัมน์ที่มีการฝังcontent_column: คอลัมน์ที่มีข้อความที่ไม่มีโครงสร้างซึ่งใช้สร้างการฝังvertex_ai_embedding_model_name: โมเดลการฝังที่คุณใช้ ซึ่งในกรณีนี้คือtext-embedding-005selected_columns: คอลัมน์อื่นๆ ที่คุณต้องการให้ Agent แสดงในผลการค้นหาความคล้ายคลึงกันของเวกเตอร์ ตัวอย่างเช่น หากคุณขอให้ Agent แสดงรายชื่อผู้ป่วยทั้งหมดที่ได้รับใบสั่งยาให้รับประทานไอศกรีม คุณจะต้องรวมคอลัมน์PatientIDไว้ในรายการนี้nearest_neighbors_algorithm,top_kและdistance_type: การปรับแต่งวิธีที่ Agent ควรทำการค้นหาความคล้ายคลึงกันของเวกเตอร์ ดูรายละเอียดเพิ่มเติมได้ในเอกสารประกอบ
การทดสอบตัวแทนการค้นหาเชิงความหมาย
เมื่อกำหนด Agent การค้นหาเชิงความหมายแล้ว คุณสามารถทดสอบโดยใช้ ADK Web ได้ในลักษณะเดียวกับที่ทดสอบ Agent Spanner พื้นฐาน
เรียกใช้คำสั่งต่อไปนี้ในเทอร์มินัล Cloud Shell
adk web --allow_origins="regex:.*" --session_service_uri="memory://" healthcare_agents
ครั้งนี้ให้เลือก semantic_agent จากเมนูแบบเลื่อนลง ใน UI ของแชท ให้ถามว่า "ผู้ป่วยรายใดมีบันทึกเกี่ยวกับอาหาร" คุณควรเห็นว่า Agent ใช้เครื่องมือ spanner_vector_store_similarity_search และแสดงข้อมูลเกี่ยวกับผู้ป่วย 2-3 ราย ดังนี้

ไม่บังคับ: การสร้าง Agent แบบหลายเครื่องมือเพื่อรองรับการค้นหาที่ซับซ้อน
ถัดไป ลองถาม Agent ว่า "ขอดูรายชื่อผู้ป่วยทั้งหมดที่ได้รับใบสั่งยาเป็นไอศกรีม" คุณจะเห็นว่า Agent ไม่พบบันทึกใดๆ แม้ว่าตาราง Prescriptions จะมีแถวที่มีข้อความ "Ice cream" ก็ตาม

ทำไม Agent จึงไม่พบข้อมูลนี้ ก่อนหน้านี้ คุณได้จำกัดให้ Agent ใช้เฉพาะเครื่องมือค้นหาความคล้ายคลึงกันของเวกเตอร์ในตาราง Appointments เท่านั้น จึงไม่สามารถเรียกใช้การค้นหา SQL แบบไดนามิกในตารางอื่นๆ ได้ หากต้องการสร้าง Agent ที่สามารถทำการค้นหาเชิงความหมายในข้อความที่ไม่มีโครงสร้างและ SQL มาตรฐานได้ คุณสามารถกำหนดชุดเครื่องมือที่ทำงานทั้ง 2 อย่างได้ นั่นคือการค้นหาเวกเตอร์และ SQL พื้นฐาน
ก่อนอื่น ให้สร้างไดเรกทอรีใหม่ในเทอร์มินัล Cloud Shell โดยทำดังนี้
cd ~
mkdir healthcare_agents/multi_tool_agent
touch healthcare_agents/multi_tool_agent/agent.py
ถัดไป ให้เพิ่มโค้ดต่อไปนี้ลงในไฟล์ agent.py ใหม่ที่คุณเพิ่งสร้างขึ้น
import os
import sys
import asyncio
import google.auth
from google.auth.transport.requests import Request
from google.adk.agents import Agent
from google.adk.tools.spanner import utils as spanner_utils
from google.adk.tools.spanner import client as spanner_client_module
from google.adk.tools.spanner.settings import SpannerToolSettings, Capabilities, SpannerVectorStoreSettings
from google.adk.tools.spanner.spanner_credentials import SpannerCredentialsConfig
from google.adk.tools.spanner.spanner_toolset import SpannerToolset
from google.genai import Client
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
INSTANCE_ID = os.environ.get("SPANNER_INSTANCE_ID", "healthcare")
DATABASE_ID = os.environ.get("SPANNER_DATABASE_ID", "medical-db")
# --- Cloud Shell Workaround ---
# Because we are running in Cloud Shell, we need to apply a small patch to prevent
# the local proxy from deadlocking Spanner's gRPC cleanup.
# You do not need this in standard production environments like Cloud Run or your local laptop.
if hasattr(spanner_client_module, "_close_spanner_resources"):
spanner_client_module._close_spanner_resources = lambda *args, **kwargs: None
# Because text-embedding-005 uses a regional endpoint (i.e. 'us-central1')
# and gemini-3.8-flash uses a multi-regional endpoint (i.e. 'us')
# We need the following patch to pass the correct region to the embedding model
async def _patched_embed_contents_async(vertex_ai_embedding_model_name: str, contents: list[str], output_dimensionality: int | None = None, genai_client: Client | None = None):
regional_client = Client(vertexai=True, project=PROJECT_ID, location="us-central1")
return await asyncio.to_thread(
spanner_utils.embed_contents, vertex_ai_embedding_model_name, contents,
output_dimensionality=output_dimensionality, genai_client=regional_client,
)
spanner_utils.embed_contents_async = _patched_embed_contents_async
# --- Auth ---
try:
application_default_credentials, _ = google.auth.default()
if not application_default_credentials.valid:
application_default_credentials.refresh(Request())
except Exception as e:
print(f"\n[ERROR] Failed to authenticate: {e}", flush=True)
sys.exit(1)
# --- Shared Credentials Config ---
credentials_config = SpannerCredentialsConfig(
credentials=application_default_credentials
)
# --- Vector tool settings ---
vector_store_settings = SpannerVectorStoreSettings(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
database_id=DATABASE_ID,
table_name="Appointments",
content_column="DoctorNotes",
embedding_column="DoctorNotesEmbedding",
vector_length=768,
vertex_ai_embedding_model_name="text-embedding-005",
selected_columns=["PatientId", "ProviderId", "AppointmentDate", "DoctorNotes"],
nearest_neighbors_algorithm="EXACT_NEAREST_NEIGHBORS",
top_k=3,
distance_type="COSINE",
)
tool_settings = SpannerToolSettings(
capabilities=[Capabilities.DATA_READ],
vector_store_settings=vector_store_settings,
)
spanner_toolset = SpannerToolset(
credentials_config=credentials_config,
spanner_tool_settings=tool_settings,
)
# --- Multi-Tool Agent Definition ---
root_agent = Agent(
model="gemini-3.8-flash",
name="super_doctor_agent",
description="Advanced medical agent that combines semantic search with relational SQL.",
instruction=f"""
You are an advanced medical assistant with access to both vector similarity search and standard SQL queries.
When a user asks a medical question (like finding patients with specific symptoms AND their prescribed treatments):
1. First, use `spanner_vector_store_similarity_search` to find the `PatientId` based on the symptom/note description.
2. Then, use `spanner_execute_sql` to run a SQL query against the `Prescriptions` table to find what medication was prescribed for that exact `PatientId`.
3. If the user asks for exact matches (e.g. "patients prescribed ice cream"), skip the vector search and just use `spanner_execute_sql` directly on the Prescriptions table.
Always combine the information into a single, friendly response.
Default Database Configuration:
- project_id: {PROJECT_ID}
- instance_id: {INSTANCE_ID}
- database_id: {DATABASE_ID}
""",
tools=[
spanner_toolset,
],
)
ทดสอบ Agent แบบหลายเครื่องมือใหม่ในเครื่องด้วย ADK Web โดยทำดังนี้
adk web --allow_origins="regex:.*" --session_service_uri="memory://" healthcare_agents
เลือก multi_tool_agent จากเมนูแบบเลื่อนลง แล้วป้อนพรอมต์ที่คุณลองใช้ก่อนหน้านี้แต่ไม่สำเร็จ: "แสดงรายชื่อผู้ป่วยทั้งหมดที่ได้รับใบสั่งยาให้รับประทานไอศกรีม" คุณควรเห็นข้อความในลักษณะต่อไปนี้

8. ติดตั้งใช้งาน Agent การค้นหาเชิงความหมายใน Cloud Run
จนถึงตอนนี้ คุณได้ทดสอบ Agent ในเครื่องแล้ว แต่จะเป็นประโยชน์หากสมาชิกคนอื่นๆ ในทีมในบริษัทด้านการดูแลสุขภาพสมมติของคุณเข้าถึง Agent ได้ หากต้องการเปิดใช้ฟีเจอร์ดังกล่าว ให้ทำให้ Agent ใช้งานได้ด้วย Cloud Run ซึ่งทำได้ง่ายๆ ด้วย ADK CLI เราจะแสดงวิธีดำเนินการนี้โดยให้คุณติดตั้งใช้งาน Agent การค้นหาเชิงความหมาย
ก่อนอื่น คุณต้องเพิ่มไฟล์ requirements.txt ลงในไดเรกทอรีที่คุณกำหนดตัวแทนการค้นหาเชิงความหมายไว้ ในสภาพแวดล้อม Cloud Shell คุณได้ติดตั้ง google-cloud-spanner ไว้แล้ว แต่คุณต้องทำให้ทรัพยากร Dependency นี้พร้อมใช้งานอย่างชัดเจนเมื่อทำให้ Agent ใช้งานได้ จากไดเรกทอรี Cloud Shell รูท ให้เรียกใช้คำสั่งต่อไปนี้ในเทอร์มินัลเพื่อสร้างไฟล์นี้
echo "google-cloud-spanner>=3.64" > healthcare_agents/semantic_agent/requirements.txt
ถัดไป ให้เรียกใช้คำสั่งต่อไปนี้เพื่อทำให้ Agent การค้นหาเชิงความหมายใช้งานได้ใน Cloud Run
adk deploy cloud_run \
--project=${GOOGLE_CLOUD_PROJECT} \
--region=us-central1 \
--env="GOOGLE_CLOUD_PROJECT=${GOOGLE_CLOUD_PROJECT},GOOGLE_CLOUD_LOCATION=us,SPANNER_INSTANCE_ID=${SPANNER_INSTANCE_ID},SPANNER_DATABASE_ID=${SPANNER_DATABASE_ID}" \
--with_ui \
healthcare_agents/semantic_agent/ \
-- \
--allow-unauthenticated
แฟล็ก --with_ui จะทำให้ Agent ใช้งานได้โดยอัตโนมัติด้วย UI แชทเดียวกับที่คุณทดสอบก่อนหน้านี้ใน ADK Web คุณสามารถทำให้ใช้งานได้โดยไม่ต้องมีแฟล็กดังกล่าวหากต้องการให้ Agent พร้อมใช้งานเป็น REST API เท่านั้น
เมื่อเรียกใช้คำสั่งข้างต้น ระบบจะขอให้คุณยืนยันว่าต้องการดำเนินการต่อด้วยการทำให้ใช้งานได้ พิมพ์ Y เพื่อยืนยัน
เมื่อคำสั่ง deploy เสร็จสมบูรณ์ คุณจะเห็น URL ของ UI ของ Agent ที่บันทึกไว้ในเอาต์พุต คลิกเพื่อเปิด URL และค้นหา Agent เหมือนที่เคยทำก่อนหน้านี้
9. ไม่บังคับ: สร้าง Agent ที่มีสิทธิ์เข้าถึงฐานข้อมูลแบบจำกัด
ในสภาพแวดล้อมเวอร์ชันที่ใช้งานจริง คุณอาจต้องการจำกัดสิทธิ์เข้าถึงของ Agent ให้เข้าถึงได้เฉพาะตารางฐานข้อมูลและคำค้นหา SQL ที่เฉพาะเจาะจง ในส่วนนี้ คุณจะได้เรียนรู้วิธีสร้าง Agent ที่มีสิทธิ์เข้าถึงเฉพาะเครื่องมือและตารางที่เฉพาะเจาะจงในอินสแตนซ์ Spanner
การกำหนด Agent
ขั้นแรก ให้สร้างไดเรกทอรีใหม่สำหรับ Agent นี้ โดยทำดังนี้
cd ~
mkdir healthcare_agents/secure_agent
touch healthcare_agents/secure_agent/agent.py
เปิดไฟล์ healthcare_agents/secure_agent/agent.py ที่สร้างขึ้นใหม่ในเครื่องมือแก้ไข Cloud Shell แล้วเพิ่มโค้ดต่อไปนี้
import os
import sys
import google.auth
from google.auth.credentials import Credentials
from google.auth.transport.requests import Request
from google.adk.agents import Agent
from google.adk.tools import ToolContext
from google.adk.tools.spanner import query_tool
from google.adk.tools.google_tool import GoogleTool
from google.adk.tools.spanner import client as spanner_client_module
from google.adk.tools.spanner.settings import SpannerToolSettings
from google.adk.tools.spanner.spanner_credentials import SpannerCredentialsConfig
from google.adk.tools.spanner.spanner_toolset import SpannerToolset
PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT")
INSTANCE_ID = os.environ.get("SPANNER_INSTANCE_ID", "healthcare")
DATABASE_ID = os.environ.get("SPANNER_DATABASE_ID", "medical-db")
# --- Cloud Shell Workaround ---
# Because we are running in Cloud Shell, we need to apply a small patch to prevent
# the local proxy from deadlocking Spanner's gRPC cleanup.
# You do not need this in standard production environments like Cloud Run or your local laptop.
if hasattr(spanner_client_module, "_close_spanner_resources"):
spanner_client_module._close_spanner_resources = lambda *args, **kwargs: None
# --- Auth ---
try:
application_default_credentials, _ = google.auth.default()
if not application_default_credentials.valid:
application_default_credentials.refresh(Request())
except Exception as e:
print(f"\n[ERROR] Failed to authenticate: {e}", flush=True)
sys.exit(1)
# --- Spanner Tool config ---
credentials_config = SpannerCredentialsConfig(
credentials=application_default_credentials
)
# Revoke general SQL access by passing an empty capabilities list
secure_tool_settings = SpannerToolSettings(capabilities=[])
secure_spanner_toolset = SpannerToolset(
credentials_config=credentials_config,
spanner_tool_settings=secure_tool_settings
)
# Define a strict allowlist of tables the agent is permitted to access
ALLOWED_TABLES = {"Appointments", "Prescriptions"}
async def secure_count_rows_tool(
table_name: str,
credentials: Credentials,
settings: SpannerToolSettings,
tool_context: ToolContext,
):
"""Counts the total number of rows for a specified table."""
# Guard against SQL injection and unauthorized access
if table_name not in ALLOWED_TABLES:
return {"status": "ERROR", "message": f"Unauthorized table: {table_name}"}
return await query_tool.execute_sql(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
database_id=DATABASE_ID,
query=f"SELECT count(*) FROM {table_name}",
credentials=credentials,
settings=settings,
tool_context=tool_context,
)
# Give the agent your secured tool
root_agent = Agent(
model="gemini-3.8-flash",
name="secure_healthcare_agent",
description="Agent to count rows in allowed Spanner tables.",
instruction="""
You are a database agent with access to a custom SQL tool that can run on specified tables. If a user asks for the name of a table with the wrong casing (i.e. 'appointments' when the table name is 'Appointments') they should still be able to get info on that table.
""",
tools=[
secure_spanner_toolset,
GoogleTool(
func=secure_count_rows_tool,
credentials_config=credentials_config,
tool_settings=secure_tool_settings,
),
],
)
มาดูความแตกต่างระหว่างโค้ดนี้กับโค้ด Agent ก่อนหน้ากัน
- เมื่อคุณกำหนด
SpannerToolSettingsคุณไม่ได้ส่งcapabilitiesไปยัง Agent - เมื่อคุณกำหนด
Agentคุณจะส่งGoogleToolพร้อมฟังก์ชันที่กำหนดเองซึ่งคุณกำหนดไว้ชื่อsecure_count_rows_tool - ฟังก์ชัน
secure_count_rows_toolนี้ใช้เครื่องมือ Spanner เพียงเครื่องมือเดียวที่ชื่อว่าexecute_sqlและคุณได้กำหนดการค้นหา SQL ที่เครื่องมือนี้เรียกใช้ได้แล้ว ในกรณีนี้ คุณใช้การค้นหาง่ายๆ เพื่อนับแถว และ Agent จะส่งชื่อตารางไปยังฟังก์ชันนี้ - เพื่อเป็นมาตรการป้องกันเพิ่มเติม ฟังก์ชันนี้จะจำกัดไม่ให้ Agent เรียกใช้การค้นหาในตารางที่ไม่ได้รับอนุญาตโดยแสดงข้อผิดพลาดหาก
table_nameที่ระบุไม่อยู่ในรายการALLOWED_TABLESที่กำหนดไว้ล่วงหน้า
การทดสอบ Agent ในเครื่อง
มาทดสอบ Agent นี้โดยใช้ ADK Web กัน
adk web --allow_origins="regex:.*" --session_service_uri="memory://" healthcare_agents
ครั้งนี้ให้เลือก secure_agent จากเมนูแบบเลื่อนลง ใน UI ของแชท ให้ลองขอให้ Agent นับแถวจากทั้งตารางที่ไม่ได้รับอนุญาตและได้รับอนุญาตโดยใช้พรอมต์ต่อไปนี้
- "สรุปตารางการนัดหมาย"
- "สรุปตารางผู้ป่วย"
พรอมต์แรกที่สรุปตารางการนัดหมายควรแสดงผลจำนวนแถวสำหรับตารางนั้น และพรอมต์ที่ 2 ที่สรุปตารางผู้ป่วยควรแสดงผลข้อความว่า Agent ไม่ได้รับอนุญาตให้เข้าถึงตารางนั้น
คุณได้ทดสอบ Agent นี้ในเครื่องเท่านั้น แต่คุณสามารถทำให้ใช้งานได้โดยใช้เวิร์กโฟลว์เดียวกับขั้นตอนก่อนหน้า
10. ล้างทรัพยากร
ลบอินสแตนซ์ Spanner
เรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell เพื่อลบอินสแตนซ์ Spanner และฐานข้อมูล
gcloud spanner instances delete ${SPANNER_INSTANCE_ID} --quiet
ยืนยันว่าอินสแตนซ์ถูกนำออกแล้ว โดยทำดังนี้
gcloud spanner instances list
ลบบริการ Cloud Run
หากต้องการลบบริการ Cloud Run ที่คุณติดตั้งใช้งาน ให้เรียกใช้คำสั่งต่อไปนี้
gcloud run services delete adk-default-service-name \
--project=${GOOGLE_CLOUD_PROJECT} \
--region=us-central1
ล้างไฟล์ในเครื่อง
หากต้องการล้างไฟล์ Cloud Shell ที่สร้างใน Codelab นี้ ให้เรียกใช้คำสั่งต่อไปนี้
rm -rf ~/healthcare_agents
11. ขอแสดงความยินดี
ยินดีด้วย คุณได้สร้าง ทดสอบ และติดตั้งใช้งาน AI Agent ที่อ่านจากฐานข้อมูล Spanner โดยใช้ ADK เรียบร้อยแล้ว
สิ่งที่คุณได้พูดถึงไปแล้ว
- จัดสรรอินสแตนซ์ Cloud Spanner, สร้างตาราง และเพิ่มข้อมูลโดยใช้ Spanner Studio
- สร้างการฝังเวกเตอร์จากคอลัมน์ข้อความที่ไม่มีโครงสร้างในตาราง Spanner
- ใช้การผสานรวม Spanner ของ ADK เพื่อสร้าง Agent สำหรับสรุปฐานข้อมูลและตาราง Spanner
- สร้าง Agent การค้นหาเชิงความหมายโดยใช้
SpannerVectorStoreSettingsของ ADK และเครื่องมือค้นหาความคล้ายคลึงของเวกเตอร์ - ทดสอบ Agent ด้วย ADK Web
- ติดตั้งใช้งาน Agent ด้วย ADK CLI
ขั้นตอนถัดไป
- สำรวจระบบ Multi-Agent ด้วย ADK เพื่อประสานงานฐานข้อมูลเฉพาะทางและ Agent ฟรอนท์เอนด์
- ดูข้อมูลเพิ่มเติมเกี่ยวกับ Spanner Graph สำหรับการให้เหตุผลของ Agent ที่อิงตามกราฟ
- ดูการควบคุมการเข้าถึงแบบละเอียดใน Spanner เพื่อใช้บทบาทฐานข้อมูลกับข้อมูลเข้าสู่ระบบของ Agent