構造化データと非構造化データを分析するエージェントの構築

1. 始める前に

予約記録に関する大量のデータを扱う医療会社に勤務しているとします。これには、日付やプロバイダ ID などの構造化データと、医師のメモや患者のメッセージなどの非構造化データが含まれます。スタッフがこのデータを手動で選別したり、独自の SQL クエリを作成したりするのではなく、自然言語を使用して必要な情報を抽出する方法が必要です。たとえば、「過去 30 日間にアイスクリームを処方されたすべての患者のリストを教えてください」や「過去 1 年間にフォローアップの診察を受けていない X 医師のすべての患者を見つけてください」などです。

この Codelab では、Agent Development Kit(ADK)を使用して、Cloud Spanner データベースとやり取りしてデータベースの概要を提供し、セマンティック推論を行うエージェントを構築してデプロイします。

ADK は、柔軟なマルチエージェント アプリケーションを構築、評価、デプロイするために設計された、オープンソースのコードファースト フレームワークです。Cloud Spanner は、グローバルに分散された水平スケーラビリティを備えたフルマネージド データベースで、組み込みのベクトル検索と AI 機能を備えたリレーショナル セマンティクスを提供します。

ADK と Spanner を組み合わせることで、生成 AI エージェントはデータベース スキーマを動的に検出し、構造化クエリを実行して、運用データ全体でリアルタイムのセマンティック類似検索を実行できます。

この Codelab では架空の医療の例を使用しますが、このシナリオには、カスタマー サポート チケット、e コマースデータなど、多くの用途が考えられます。

演習内容

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 プロジェクトに対して課金が有効になっていることを確認します。プロジェクトで課金が有効になっているかどうかを確認する方法をご覧ください。

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 のインスタンスとデータベースを作成する

この Codelab では、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 クエリを実行してテーブルを作成し、データを挿入してクエリを実行するための UI が用意されています。

Spanner Studio で [無題のクエリ] タブをクリックします。

new-query.png

次に、医療データを保持する 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 つの新しいテーブルが表示されます。

table-explorer.png

まだデータがありません。追加しましょう。

サンプルデータを挿入する

+ アイコンをクリックして、Spanner Studio で新しいクエリタブを開きます。次の SQL をコピーして、4 つのテーブルにそれぞれ 10 行のダミーデータを挿入します。

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] タブに移動して、データのプレビューを表示します。

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 テーブルの [Data] タブに移動すると、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 エディタを開きます。この 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 に渡します。エージェントは、この認証情報を使用して Spanner データベースにアクセスします。
  • SpannerToolSettings をインスタンス化し、DATA_READ アクセス権を付与します。これにより、エージェントは Spanner インスタンス内のすべてのテーブルに対する読み取りアクセス権を持つことができます。エージェントが特定のテーブルにアクセスできないように制限するには、この Codelab の最後にあるオプションの手順をご覧ください。
  • 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 の URL をクリックして、ブラウザで新しいタブを開きます。上部のプルダウンから、作成した basic_spanner_agent を選択します。チャット UI が開き、エージェントにクエリを送信できます。「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: エージェントがベクトル類似検索を実行する方法のカスタマイズ。詳細については、ドキュメントをご覧ください。

セマンティック検索エージェントをテストする

セマンティック検索エージェントを定義したら、基本的な Spanner エージェントをテストしたときと同じように、ADK Web を使用してテストできます。

Cloud Shell ターミナルで次のコマンドを実行します。

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

今回は、プルダウンから [semantic_agent] を選択します。チャット UI で、「Which patients have notes involving food?」と質問します。エージェントが 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 ウェブでテストしたのと同じチャット UI でエージェントが自動的にデプロイされます。エージェントを REST API としてのみ使用できるようにする場合は、このフラグを指定せずにデプロイできます。

上記のコマンドを実行すると、デプロイを続行するかどうかを確認するメッセージが表示されます。確定するには、「Y」と入力します。

deploy コマンドが完了すると、エージェント UI の URL が出力に表示されます。URL をクリックして開き、以前と同じようにエージェントにクエリを実行します。

9. 省略可: データベース アクセスが制限されたエージェントを作成する

本番環境では、エージェントのアクセスを特定のデータベース テーブルと SQL クエリに制限することをおすすめします。このセクションでは、Spanner インスタンス内の特定のツールとテーブルにのみアクセスできるエージェントを作成する方法について説明します。

エージェントの定義

まず、このエージェント用の新しいディレクトリを作成します。

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

このコードと以前のエージェント コードの違いをいくつか取り上げます。

  • SpannerToolSettings を定義したときに、capabilities をエージェントに渡さなかった
  • Agent を定義するときに、GoogleTool を渡します。これには、定義した secure_count_rows_tool というカスタム関数が含まれます。
  • この secure_count_rows_tool 関数は、execute_sql という 1 つの Spanner ツール呼び出しのみを使用します。このツールが実行できる SQL クエリを定義しました。この場合、単純なクエリを使用して行数をカウントし、エージェントがテーブル名をこの関数に渡します。
  • 追加のガードレールとして、この関数は、指定された table_name が事前定義された ALLOWED_TABLES リストにない場合にエラーを発生させることで、エージェントが未承認のテーブルに対してクエリを実行できないようにします。

ローカルでのエージェントのテスト

ADK Web を使用してこのエージェントをテストしてみましょう。

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

今回は、プルダウンから [secure_agent] を選択します。チャット UI で、次のプロンプトを使用して、未承認のテーブルと承認済みのテーブルの両方から行をカウントするようエージェントに依頼します。

  • 「予約テーブルを要約して」
  • 「patients テーブルを要約する」

appointments テーブルを要約する最初のプロンプトでは、そのテーブルの行数が返されます。patients テーブルを要約する 2 番目のプロンプトでは、エージェントにそのテーブルへのアクセス権がないことを示すメッセージが返されます。

このエージェントはローカルでのみテストされていますが、前のステップと同じワークフローを使用してデプロイできます。

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

ローカル ファイルをクリーンアップする

この Codelab で作成した Cloud Shell ファイルをクリーンアップするには、次のコマンドを実行します。

rm -rf ~/healthcare_agents

11. 完了

おめでとうございます!ADK を使用して、Spanner データベースから読み取る AI エージェントを構築、テスト、デプロイしました。

学習した内容

  • Cloud Spanner インスタンスをプロビジョニングし、テーブルを作成して、Spanner Studio を使用してデータを追加しました。
  • Spanner テーブルの非構造化テキスト列からベクトル エンベディングを生成しました。
  • ADK の Spanner インテグレーションを使用して、Spanner データベースとテーブルを要約するエージェントを構築しました。
  • ADK の SpannerVectorStoreSettings とベクトル類似検索ツールを使用して、セマンティック検索エージェントを構築しました。
  • ADK Web を使用してエージェントをテストしました。
  • ADK CLI を使用してエージェントをデプロイした。

次のステップ