Building Agents to Analyze Structured and Unstructured Data

1. Before you begin

Let's imagine you work at a healthcare company with large amounts of data on appointment records. This includes structured data, like dates and provider IDs, along with unstructured data like doctor notes and patient messages. Rather than having staff sift through this data manually or write their own SQL queries, you need a way for them to use natural language to extract the information they need. For example, "Give me a list of all the patients prescribed ice cream in the last 30 days," or "Find all the patients of Dr. X who haven't had a follow-up visit in the last year."

In this codelab, you'll build and deploy an agent with the Agent Development Kit (ADK) that can interact with your Cloud Spanner database to provide both database overviews and do semantic reasoning.

The ADK is an open-source, code-first framework designed to build, evaluate, and deploy flexible multi-agent applications. Cloud Spanner is a fully managed, globally distributed, horizontally scalable database offering relational semantics with built-in vector search and AI capabilities.

By combining ADK with Spanner, your generative AI agents can dynamically discover database schemas, execute structured queries, and perform real-time semantic similarity searches across your operational data.

While this codelab uses a fictional healthcare example, there are many possible applications of this scenario, including: customer support tickets, ecommerce data, and more.

What you'll do

You will build a healthcare agent that connects to your Spanner database using ADK's SpannerToolset. The agent will inspect table schemas and generate SQL queries to answer natural language questions using vector similarity searches. After testing the agent locally, you will deploy it to Cloud Run.

What you'll learn

  • How to create a Spanner database and add an embedding column.
  • How to configure ADK's SpannerToolset and SpannerToolSettings.
  • How to enable database metadata inspection, SQL execution, and vector similarity search tools.
  • How to test the agent using adk web.
  • How to deploy the agent with Cloud Run and run queries to the production agent.

What you'll need

  • A Google Cloud project with billing enabled.
  • A web browser such as Google Chrome.
  • Familiarity with basic Python and SQL concepts.

2. Set up your environment

Create a Google Cloud Project

  1. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.
  2. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

Start Cloud Shell

Cloud Shell is an in-browser command-line environment running in Google Cloud that comes preloaded with gcloud, Python, and other essential developer tools.

  1. Click Activate Cloud Shell at the top of the Google Cloud console.

activate-cloud-shell.png

  1. Once connected to Cloud Shell, verify your active authentication:
    gcloud auth list
    
  2. Confirm your default project is configured:
    gcloud config get project
    
  3. If your project is not set, configure it with:
    export GOOGLE_CLOUD_PROJECT=<YOUR_GOOGLE_CLOUD_PROJECT>
    gcloud config set project $GOOGLE_CLOUD_PROJECT
    

Enable required Google Cloud APIs

You need access to a few services to run this lab. Enable all required APIs in Cloud Shell:

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

Verify that the operation completes successfully:

Operation "operations/..." finished successfully.

Set environment variables

Configure environment variables to tell the ADK to use your Google Cloud project and Spanner database:

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"

Authenticate with gcloud

To ensure your Cloud Shell environment is authenticated, run the following:

gcloud auth application-default login

3. Create your Spanner instance and database

In this codelab, you'll create your Spanner instance and database in the Cloud console. You can also create your database programmatically, for example using the Spanner Python client.

Create a Spanner instance and database

Navigate to the Spanner page in your Cloud console and create a free instance. Type healthcare as both the "Instance name" and "Instance ID" and select us-central1 as the region. Then click Create free-of-charge instance.

free-spanner-instance.png

Create the database and schema

Next, navigate to the page for the instance you just created and click Create database:

create-db.png

Name your database medical-db, leave Google Standard SQL selected, and click Create:

medical-db.png

Next you'll create tables and add sample data to your database.

4. Populate sample data and generate embedding column

With your database created, you'll use Spanner Studio in the Cloud console to create tables and insert sample data.

Create tables

On the left menu bar within your medical-db database, click Spanner Studio. Spanner Studio provides a UI for running SQL queries to create tables, insert, and query your data.

Click the Untitled query tab in Spanner Studio:

new-query.png

Next you'll create four tables to hold your healthcare data: Providers, Patients, Appointments, and Prescriptions. The Providers table will be independent, and the Patients table will be a parent table for Appointments and Prescriptions. The Appointments and Prescriptions tables will be interleaved, which means they'll be stored on the same server as their parent Patients table to make for faster querying.

Copy the following SQL queries into the editor to create four tables:

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

Click Run to run the CREATE TABLE queries. When the queries complete, you'll be able to see your four new tables in the left nav Explorer:

table-explorer.png

There's no data in them yet, let's add some!

Insert sample data

Open a new query tab in Spanner Studio by clicking the + icon. Copy the following SQL to insert ten rows of fake data into each of your four tables:

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');

Click Run. When the insert queries complete, you can preview the data for your tables by navigating to the Spanner Overview tab and then scrolling down to the Tables tab.

Click on any of your tables, for example Prescriptions and navigate to the Data tab on the left nav to see a preview of the data:

data-preview.png

Generate vector embeddings in Spanner

When you created and inserted data into your Appointments table, you created a DoctorNotesEmbedding column that is currently empty. In order for a model to understand the free-form text in your DoctorNotes column, you need to convert it to embeddings: numerical representations of text in arrays, or vectors.

To create the embedding column, you first need to create a text embedding model in your database. Navigate back to Spanner Studio, open a new query tab and paste the following:

-- 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'
);

Next, in a new query in Spanner Studio, you'll generate the embeddings from the DoctorNotes column using the model you just created and insert them into the DoctorNotesEmbedding column for each row:

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;

Preview the embedding data

Navigate to the Data tab for your Appointments table and you should see the DoctorNotesEmbedding column populated:

embedding-preview.png

Now that you've created your Spanner instance, database, and tables, you're ready to build an agent that can securely access and read from them.

5. Build an agent to summarize your Spanner database

Create directory structure

To start, you'll build a simple ADK agent that can summarize metadata about your tables.

First, make sure you have the latest version of google-adk installed. Run this in your Cloud Shell terminal:

pip install --upgrade google-adk

Then run the following to create a directory in Cloud Shell for your agents code:

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

This will create the following directory structure in Cloud Shell:

+ healthcare_agents
  + basic_spanner_agent
    + agent.py

To create additional agents, you can add directories under the root healthcare_agents/ following this format.

This is the directory structure ADK Web looks for. You'll use that to test your agent in the next step.

Add agent code

Open the Cloud Shell editor by clicking the Open editor button at the top of Cloud Shell. You'll use this to toggle back and forth between the terminal and editor throughout this codelab.

Open the healthcare_agents/basic_spanner_agent/agent.py file you just created and paste in the following code:

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

Here's what's happening in the code you just added:

  • You use the google.auth library to authenticate, and pass those credentials to SpannerCredentialsConfig, which your agent will use to access your Spanner database
  • You instantiate SpannerToolSettings and give it DATA_READ access. This allows your agent to have read access to all tables in your Spanner instances. To restrict the access your agent has to specific tables, see the optional step at the end of this codelab.
  • You instantiate a SpannerToolset. This gives your agent access to all of the available Spanner tools, for example list_table_names and get_table_schema. You can find the full list in the documentation.
  • You instantiate an Agent in ADK and provide a model, name, description, instruction, and give it access to the SpannerToolset we defined previously.

6. Test your agent in ADK Web

You can use ADK Web to test your agent locally. ADK Web is a visual UI for inspecting and debugging your agent. From your Cloud Shell terminal, run the following to navigate to the root directory:

cd ~

Then run this adk web command to open an ADK Web server. When you run this you may be prompted to enable telemetry. You can choose whether to enable it if prompted.

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

You should see a log similar to this:

+-----------------------------------------------------------------------------+
| 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)

Click CMD + the localhost URL to open a new tab in the browser. From the dropdown on the top, select the basic_spanner_agent you just created. This will open a chat UI where you can send a query to your agent. Type in "summarize the tables in medical-db".

You should see all the tools the agent is calling along with the response:

adk-web-summary.png

You can use ADK Web to test any additional queries about your database and tables.

To exit ADK Web, stop the process in your Cloud Shell terminal by typing CTRL + C.

7. Build a Spanner semantic search agent

Now that you've built a basic agent that can summarize info about your Spanner instance, database, and tables, let's build an agent that can analyze the unstructured text in your database. So that anyone on your team can analyze the patient records without needing to write SQL queries, your agent should be able to take a natural language query and use the vector embedding column you created earlier to perform vector search on your doctor notes data.

Writing the agent code

To create a new directory for your semantic agent, run the following in your Cloud Shell terminal:

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

Navigate to the Cloud Shell editor (you may need to reload it) and open the empty healthcare_agents/semantic_agent/agent.py file you just created, and add the following contents:

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

Here's how the semantic search agent works:

  • You define SpannerVectorStoreSettings to pass to your SpannerToolset, which tells the agent:
    • Basic metadata on your instance, db, and table.
    • embedding_column: The column that contains the embedding.
    • content_column: The column that contains the unstructured text that the embedding was generated from.
    • vertex_ai_embedding_model_name: The embedding model you are using, in this case text-embedding-005.
    • selected_columns: The other columns you want the agent to return in the vector similarity search result. For example, if you ask the agent to return all patients that were prescribed ice cream, you'll want the PatientID column included in this list.
    • nearest_neighbors_algorithm, top_k, and distance_type: Customizations for how your agent should perform vector similarity search. For more details, see the documentation.

Testing the semantic search agent

With your semantic search agent defined, you can test it using ADK Web, in the same way you tested your basic Spanner agent.

Run the following in your Cloud Shell terminal:

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

This time, select semantic_agent from the dropdown. In the chat UI, ask "Which patients have notes involving food?". You should see the agent use the spanner_vector_store_similarity_search tool and return data on a few patients:

adk-web-semantic.png

Optional: Building a multi-tool agent to support complex queries

Next, try asking the agent: "Give me a list of all patients who have been prescribed ice cream". You'll notice the agent is not able to find any records, even though your Prescriptions table has a row containing the text "Ice cream":

ice-cream-query.png

Why can't the agent find this? Earlier, you restricted the agent to only use the vector similarity search tool on the Appointments table, so it couldn't run dynamic SQL queries on other tables. To build an agent that can do both semantic search on unstructured text and standard SQL, you can define a toolset that can perform both tasks: vector search and basic SQL.

First, create a new directory in your Cloud Shell terminal:

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

Next, add the following code to the new agent.py file you just created:

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

Test your new multi-tool agent locally with ADK Web:

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

Choose multi_tool_agent from the dropdown and enter the prompt you tried before that failed: "Give me a list of all patients who have been prescribed ice cream". You should see something like the following:

ice-cream-patient.png

8. Deploy your semantic search agent in Cloud Run

So far you've tested your agent locally, but it would be useful if other team members across your fictional healthcare company could access it. To enable that, let's deploy your agent with Cloud Run. You can do this easily with the ADK CLI. To show you how to do this, you'll deploy your semantic search agent.

First, you need to add a requirements.txt file to the directory where you've defined your semantic search agent. In your Cloud Shell environment you have google-cloud-spanner installed, but you need to explicitly make this dependency available when you deploy your agent. From your root Cloud Shell directory, run the following in your terminal to create this file:

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

Next, run the following command to deploy your semantic search agent to 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

The --with_ui flag automatically deploys your agent with the same chat UI you tested previously in ADK Web. You can deploy without that flag if you only want your agent to be available as a REST API.

When running the command above, it will ask you to confirm you'd like to continue with the deploy. Type Y to confirm.

When the deploy command completes, you will see the URL of your agent UI logged in the output. Click on it to open the URL, and query your agent like you did previously.

9. Optional: Create an agent with restricted database access

In a production setting, you may want to restrict your agent's access to specific database tables and SQL queries. In this section, you'll learn how to create an agent that only has access to specific tools and tables in your Spanner instance.

Defining the agent

First, create a new directory for this agent:

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

Open the newly created healthcare_agents/secure_agent/agent.py file in your Cloud Shell editor and add the following code:

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

Let's highlight the differences between this and your previous agent code:

  • When you defined SpannerToolSettings, you didn't pass any capabilities to the agent
  • When you define the Agent, you pass in a GoogleTool, with a custom function you defined called secure_count_rows_tool
  • This secure_count_rows_tool function uses only one Spanner tool called execute_sql, and you've define the SQL query this tool can run. In this case you use a simple query to count rows, and the agent passes the table name to this function.
  • As an additional guardrail, the function restricts the agent from running the query on unauthorized tables by raising an error if the provided table_name is not in the predefined ALLOWED_TABLES list.

Testing the agent locally

Let's test this agent using ADK Web:

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

This time, select secure_agent from the dropdown. In the chat UI, try asking the agent to count rows from both an unauthorized and authorized table using the following prompts:

  • "summarize the appointments table"
  • "summarize the patients table"

The first prompt to summarize the appointments table should return a row count for that table, and the second prompt to summarize the patients table should return a message that the agent is unauthorized to access that table.

You have only tested this agent locally, but you can deploy it using the same workflow as the previous step.

10. Clean up resources

Delete the Spanner instance

Run the following command in Cloud Shell to delete the Spanner instance and its databases:

gcloud spanner instances delete ${SPANNER_INSTANCE_ID} --quiet

Verify the instance has been removed:

gcloud spanner instances list

Delete the Cloud Run service

To delete the Cloud Run service you deployed, run the following:

gcloud run services delete adk-default-service-name \
    --project=${GOOGLE_CLOUD_PROJECT} \
    --region=us-central1

Clean up local files

If you'd like to clean up the Cloud Shell files you created in this codelab, run the following:

rm -rf ~/healthcare_agents

11. Congratulations

Congratulations! You have successfully built, tested, and deployed an AI agent that reads from your Spanner database using the ADK.

What you covered

  • Provisioned a Cloud Spanner instance, created tables, and added data using Spanner Studio.
  • Generated vector embeddings from an unstructured text column in your Spanner table.
  • Used the ADK's Spanner integration to build an agent for summarizing your Spanner databases and tables.
  • Built a semantic search agent using the ADK's SpannerVectorStoreSettings and vector similarity search tool.
  • Tested your agents with ADK Web.
  • Deployed your agent with the ADK CLI.

Next steps