建構代理程式來分析結構化和非結構化資料

1. 事前準備

假設您任職於一間醫療保健公司,擁有大量預約記錄資料。包括日期和供應商 ID 等結構化資料,以及醫生附註和病患訊息等非結構化資料。您需要一種方法,讓員工能使用自然語言擷取所需資訊,不必手動篩選資料或自行編寫 SQL 查詢。例如「列出過去 30 天內所有處方為冰淇淋的病患」,或「找出 X 醫生過去一年內未回診的所有病患」。

在本程式碼實驗室中,您將使用 Agent Development Kit (ADK) 建構及部署代理,該代理可與 Cloud Spanner 資料庫互動,提供資料庫總覽並執行語意推理。

ADK 是以程式碼為優先的開放原始碼框架,用於建構、評估及部署彈性的多代理應用程式。Cloud Spanner 是全代管、全球分散式、可水平擴充的資料庫,提供關聯語意,並內建向量搜尋和 AI 功能。

將 ADK 與 Spanner 結合,生成式 AI 代理就能動態探索資料庫結構定義、執行結構化查詢,並對作業資料執行即時語意相似度搜尋。

雖然本程式碼實驗室使用虛構的醫療照護範例,但這個情境有許多可能的應用,包括:客戶服務單、電子商務資料等。

學習內容

您將使用 ADK 的 SpannerToolset 建構醫療照護代理,並連結至 Spanner 資料庫。代理會檢查資料表結構定義,並生成 SQL 查詢,使用向量相似度搜尋回答自然語言問題。在本機測試代理後,您會將其部署至 Cloud Run。

課程內容

  • 如何建立 Spanner 資料庫並新增嵌入資料欄。
  • 如何設定 ADK 的 SpannerToolset 和 SpannerToolSettings。
  • 如何啟用資料庫中繼資料檢查、SQL 執行和向量相似度搜尋工具。
  • 如何使用 adk web 測試代理。
  • 如何使用 Cloud Run 部署代理,並對正式環境代理執行查詢。

軟硬體需求

  • 已啟用計費功能的 Google Cloud 專案。
  • 網路瀏覽器,例如 Google Chrome。
  • 熟悉基本的 Python 和 SQL 概念。

2. 設定環境

建立 Google Cloud 專案

  1. 在 Google Cloud 控制台的專案選取器頁面中,選取或建立 Google Cloud 專案。
  2. 確認雲端專案已啟用計費功能。瞭解如何確認專案是否已啟用計費功能。

啟動 Cloud Shell

Cloud Shell 是在 Google Cloud 中運作的瀏覽器內指令列環境,已預先載入 gcloud、Python 和其他必要的開發人員工具。

  1. 點選 Google Cloud 控制台頂端的「啟用 Cloud Shell」。

activate-cloud-shell.png

  1. 連至 Cloud Shell 後,請驗證您的有效驗證:
    gcloud auth list
    
  2. 確認預設專案已設定完成:
    gcloud config get project
    
  3. 如果未設定專案,請使用下列指令設定:
    export GOOGLE_CLOUD_PROJECT=<YOUR_GOOGLE_CLOUD_PROJECT>
    gcloud config set project $GOOGLE_CLOUD_PROJECT
    

啟用必要的 Google Cloud API

您需要存取幾項服務,才能執行這個實驗室。在 Cloud Shell 啟用所有必要 API:

gcloud services enable spanner.googleapis.com aiplatform.googleapis.com run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com

確認作業順利完成:

Operation "operations/..." finished successfully.

設定環境變數

設定環境變數,指示 ADK 使用 Google Cloud 雲端專案和 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 執行個體和資料庫

在本程式碼實驗室中,您會在 Cloud 控制台建立 Spanner 執行個體和資料庫。您也可以透過程式輔助方式建立資料庫,例如使用 Spanner Python 用戶端。

建立 Spanner 執行個體和資料庫

前往 Cloud 控制台的 Spanner 頁面,建立免費執行個體。在「執行個體名稱」和「執行個體 ID」中輸入 healthcare,然後選取 us-central1 做為區域。然後點選「建立免付費執行個體」。

free-spanner-instance.png

建立資料庫和結構定義

接著,前往您剛建立的執行個體頁面,然後點選「建立資料庫」:

create-db.png

將資料庫命名為 medical-db,保留「Google 標準 SQL」選項,然後點選「建立」:

medical-db.png

接下來,您將建立資料表,並在資料庫中新增範例資料。

4. 填入範例資料並生成嵌入欄

資料庫建立完成後,您將在 Cloud 控制台使用 Spanner Studio 建立資料表並插入範例資料。

建立資料表

在 medical-db 資料庫的左選單列,點選「Spanner Studio」。Spanner Studio 提供使用者介面,可執行 SQL 查詢來建立資料表、插入及查詢資料。

在 Spanner Studio 中,點選「未命名的查詢」分頁標籤:

new-query.png

接著,您將建立四個資料表來存放醫療照護資料:Providers、Patients、Appointments 和 Prescriptions。Providers 資料表會是獨立資料表,Patients 資料表則是 Appointments 和 Prescriptions 的父項資料表。Appointments 和 Prescriptions 資料表會交錯,也就是說,這些資料表會與父項 Patients 資料表儲存在同一個伺服器上,以便加快查詢速度。

將下列 SQL 查詢複製到編輯器,建立四個資料表:

-- 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 查詢。查詢完成後,您可以在左側導覽列的「Explorer」中看到四個新資料表:

table-explorer.png

目前沒有任何資料,請新增一些資料!

插入範例資料

在 Spanner Studio 中,點選「+」圖示,開啟新的查詢分頁。複製下列 SQL,在四個資料表中各插入十列假資料:

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-preview.png

在 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;

預覽嵌入資料

前往「Appointments」資料表的「資料」分頁,應該會看到「DoctorNotesEmbedding」欄已填入資料:

embedding-preview.png

您已建立 Spanner 執行個體、資料庫和資料表,現在可以建構代理,安全地存取及讀取這些資料。

5. 建構代理來總結 Spanner 資料庫

建立目錄架構

首先,您要建構簡單的 ADK 代理,用於總結資料表的中繼資料。

首先,請確認您已安裝最新版本的 google-adk。在 Cloud Shell 終端機執行下列指令:

pip install --upgrade google-adk

接著執行下列指令,在 Cloud Shell 建立代理程式程式碼的目錄:

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

如要建立其他代理,請按照這個格式在根目錄 healthcare_agents/ 下新增目錄。

這是 ADK Web 尋找的目錄結構。您將在下一個步驟中使用該網址測試代理。

新增代理程式碼

按一下 Cloud Shell 頂端的「開啟編輯器」按鈕,開啟 Cloud Shell 編輯器。在本程式碼實驗室中,您會使用這個按鈕在終端機和編輯器之間切換。

開啟剛建立的 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,代理會使用這些憑證存取 Spanner 資料庫
  • 您將 SpannerToolSettings 例項化,並授予 DATA_READ 存取權。這樣一來,代理就能讀取 Spanner 執行個體中的所有資料表。如要限制代理存取特定資料表,請參閱本程式碼實驗室結尾的選用步驟。
  • 您將 SpannerToolset 例項化。這樣一來,代理就能存取所有可用的 Spanner 工具,例如 list_table_names 和 get_table_schema。如要查看完整清單,請參閱說明文件。
  • 您在 ADK 中例項化 Agent,並提供模型、名稱、說明、指令,以及先前定義的 SpannerToolset 存取權。

6. 在 ADK Web 測試代理

您可以使用 ADK Web 在本機測試代理。ADK Web 是視覺化 UI,可用於檢查及偵錯代理。在 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 鍵並點選 localhost 網址,在瀏覽器中開啟新分頁。在頂端的下拉式選單,選取剛建立的 basic_spanner_agent。對話 UI 隨即開啟,您可以在這裡向代理傳送查詢。輸入「summarize the tables in medical-db」。

您應該會看到代理呼叫的所有工具,以及回覆:

adk-web-summary.png

您可以使用 ADK Web 測試資料庫和資料表的其他查詢。

如要退出 ADK Web,請在 Cloud Shell 終端機輸入 CTRL + C,停止程序。

7. 建構 Spanner 語意搜尋代理

您已建構基本的代理,可彙整 Spanner 執行個體、資料庫和資料表的資訊。接著,我們要建構一個代理,分析資料庫中的非結構化文字。為了讓團隊成員不必編寫 SQL 查詢,就能分析病患記錄,代理應能接受自然語言查詢,並使用您先前建立的向量嵌入欄,對醫生附註資料執行向量搜尋。

編寫代理程式碼

在 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],
)

語意搜尋代理的運作方式如下:

  • 您定義要傳遞至 SpannerToolset 的 SpannerVectorStoreSettings,指示代理:
    • 執行個體、資料庫和資料表的基本中繼資料。
    • embedding_column:包含嵌入的資料欄。
    • content_column:這個資料欄包含用於生成嵌入的非結構化文字。
    • vertex_ai_embedding_model_name:您使用的嵌入模型,在本例中為 text-embedding-005。
    • selected_columns:您希望代理在向量相似度搜尋結果中傳回的其他資料欄。舉例來說,如果您要求代理傳回所有處方為冰淇淋的病患,您會希望這份清單包含 PatientID 欄。
    • nearest_neighbors_algorithm、top_k和 distance_type:自訂代理執行向量相似度搜尋的方式。詳情請參閱說明文件。

測試語意搜尋代理

定義語意搜尋代理後,您可以使用 ADK Web 測試,方法與測試基本 Spanner 代理相同。

在 Cloud Shell 終端機執行下列指令:

adk web --allow_origins="regex:.*" --session_service_uri="memory://" healthcare_agents

這次請從下拉式選單中選取「semantic_agent」semantic_agent。在對話 UI 中,詢問「哪些病患的附註涉及食物?」。您應該會看到代理使用 spanner_vector_store_similarity_search 工具,並傳回幾位病患的資料:

adk-web-semantic.png

選用:建構多工具代理來支援複雜查詢

接著,請試著向代理提出以下問題:「請列出所有獲開冰淇淋處方的病患」。您會發現代理找不到任何記錄,即使「Prescriptions」資料表有一列包含「Ice cream」文字:

ice-cream-query.png

為什麼代理找不到這項資訊?先前您已限制代理只能在 Appointments 資料表使用向量相似度搜尋工具,因此無法在其他資料表執行動態 SQL 查詢。如要建構能對非結構化文字執行語意搜尋,以及執行標準 SQL 的代理,您可以定義能執行這兩項工作的工具集:向量搜尋和基本 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,
    ],
)

使用 ADK Web 在本機測試新的多工具代理:

adk web --allow_origins="regex:.*" --session_service_uri="memory://" healthcare_agents

從下拉式選單中選擇 multi_tool_agent,然後輸入先前失敗的提示:「Give me a list of all patients who have been prescribed ice cream」。您應該會看到類似下方的內容:

ice-cream-patient.png

8. 在 Cloud Run 部署語意搜尋代理

到目前為止,您已在本機測試代理,但如果虛構醫療保健公司的其他團隊成員也能存取代理,會很有幫助。為此,請使用 Cloud Run 部署代理。您可以使用 ADK CLI 輕鬆完成這項操作。為了說明如何執行這項操作,您將部署語意搜尋代理。

首先,您需要在定義語意搜尋代理的目錄中,新增 requirements.txt 檔案。Cloud Shell 殼層環境中已安裝 google-cloud-spanner,但您必須在部署代理時明確提供這項依附元件。在終端機中,從 Cloud Shell 根目錄執行下列指令,建立這個檔案:

echo "google-cloud-spanner>=3.64" > healthcare_agents/semantic_agent/requirements.txt

接著,執行下列指令,將語意搜尋代理部署至 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 旗標會自動部署代理,並使用您先前在 ADK Web 測試的相同對話 UI。如果只想將代理做為 REST API 使用,則可在部署時省略該旗標。

執行上述指令時,系統會要求您確認是否要繼續部署。請輸入 Y 確認操作。

deploy 指令執行完畢後,輸出內容會顯示代理 UI 的網址。點選網址開啟,然後像之前一樣查詢代理。

9. 選用:建立資料庫存取權受限的代理

在正式環境中,您可能需要限制代理存取特定資料庫資料表和 SQL 查詢。在本節中,您將瞭解如何建立代理,並限制其只能存取 Spanner 執行個體中的特定工具和資料表。

定義代理

首先,為這個代理建立新目錄:

cd ~
mkdir healthcare_agents/secure_agent
touch healthcare_agents/secure_agent/agent.py

在 Cloud Shell 編輯器中開啟新建立的 healthcare_agents/secure_agent/agent.py 檔案,並加入下列程式碼:

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,
        ),
    ],
)

以下是這段程式碼與先前代理程式碼的差異:

  • 定義 SpannerToolSettings 時,您並未將任何 capabilities 傳遞給代理
  • 定義 Agent 時,您會傳入 GoogleTool,並使用您定義的自訂函式 secure_count_rows_tool
  • 這個 secure_count_rows_tool 工具呼叫只會使用名為 execute_sql 的 Spanner 工具,而您已定義這項工具可執行的 SQL 查詢。在這個案例中,您會使用簡單的查詢來計算資料列數量,而代理會將資料表名稱傳遞至這個函式。
  • 為進一步防範,如果提供的 table_name 不在預先定義的 ALLOWED_TABLES 清單中,函式會引發錯誤,限制代理在未經授權的資料表上執行查詢。

在本機測試代理

使用 ADK Web 測試這個代理:

adk web --allow_origins="regex:.*" --session_service_uri="memory://" healthcare_agents

這次請從下拉式選單選取「secure_agent」secure_agent。在對話 UI 中,嘗試使用下列提示詞,要求代理計算未授權和已授權資料表的資料列數量:

  • 「總結預約表格」
  • 「總結病患資料表」

第一個提示要求摘要 appointments 資料表,應傳回該資料表的資料列數;第二個提示要求摘要 patients 資料表,應傳回訊息,指出代理沒有存取該資料表的權限。

您只在本機測試過這個代理,但可以使用與上一步相同的工作流程部署。

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 檔案,請執行下列指令:

rm -rf ~/healthcare_agents

11. 恭喜

恭喜!您已成功建構、測試及部署 AI 代理,可使用 ADK 讀取 Spanner 資料庫。

涵蓋內容

  • 佈建 Cloud Spanner 執行個體、建立資料表,並使用 Spanner Studio 新增資料。
  • 依據 Spanner 資料表中的非結構化文字欄,生成向量嵌入。
  • 使用 ADK 的 Spanner 整合功能,建構代理來彙整 Spanner 資料庫和資料表。
  • 使用 ADK 的 SpannerVectorStoreSettings 和向量相似度搜尋工具,建構語意搜尋代理。
  • 使用 ADK Web 測試代理。
  • 使用 ADK CLI 部署代理。

後續步驟