跳转到内容

用于 Android Development Kit (ADK) 的 Google Cloud Spanner 工具

在 ADK 中得到支持。Python v1.11.0

Google Cloud Spanner ADK Spanner 是一个完全托管的、分布式的数据库,支持 SQL 查询和向量搜索功能。ADK Spanner 提供的工具允许用户查看数据库架构、执行 SQL 语句,并对数据库中的数据进行向量相似性搜索。

可用的工具

The SpannerToolset 提供了以下工具:

  • list_table_names:获取 GCP Spanner 数据库中存在的表名。
  • list_table_indexes:从 GCP Spanner 数据库中获取表索引信息。
  • list_table_index_columns:从 GCP 的 Spanner 数据库中获取表格索引列的信息。
  • list_named_schemas:用于获取 Spanner 数据库的命名模式(即数据库的结构信息)。
  • get_table_schema:获取 Spanner 数据库表的架构(schema)以及元数据(metadata)信息。
  • execute_sql在 Spanner 数据库中执行 SQL 查询并获取结果。
  • query_result_mode:用于确定数据的显示格式。 execute_sql 该工具用于返回数据库查询的结果。将此参数设置为…… QueryResultMode.DICT_LIST 该配置使得工具能够将结果以字典列表的形式返回。请导入相关模块。 QueryResultMode from google.adk.tools.spanner.settings.
  • similarity_search在 Spanner 中使用文本查询进行相似性搜索。

安装

这些 Spanner 工具依赖于 Google Cloud 客户端库,而这些库并不包含在基础软件包中。 google-adk **安装方法:** 使用相应的工具或命令将它们安装到位。 gcp extra:

pip install "google-adk[gcp]"

与代理程序(agent)一起使用。

# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio

from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
# from google.adk.sessions import DatabaseSessionService
from google.adk.tools.google_tool import GoogleTool
from google.adk.tools.spanner import query_tool
from google.adk.tools.spanner.settings import SpannerToolSettings
from google.adk.tools.spanner.settings import Capabilities
from google.adk.tools.spanner.spanner_credentials import SpannerCredentialsConfig
from google.adk.tools.spanner.spanner_toolset import SpannerToolset
from google.genai import types
from google.adk.tools.tool_context import ToolContext
import google.auth
from google.auth.credentials import Credentials

# Define constants for this example agent
AGENT_NAME = "spanner_agent"
APP_NAME = "spanner_app"
USER_ID = "user1234"
SESSION_ID = "1234"
GEMINI_MODEL = "gemini-2.5-flash"

# Define Spanner tool config with read capability set to allowed.
tool_settings = SpannerToolSettings(capabilities=[Capabilities.DATA_READ])

# Define a credentials config - in this example we are using application default
# credentials
# https://cloud.google.com/docs/authentication/provide-credentials-adc
application_default_credentials, _ = google.auth.default()
credentials_config = SpannerCredentialsConfig(
    credentials=application_default_credentials
)

# Instantiate a Spanner toolset
spanner_toolset = SpannerToolset(
    credentials_config=credentials_config, spanner_tool_settings=tool_settings
)

# Optional
# Create a wrapped function tool for the agent on top of the built-in
# `execute_sql` tool in the Spanner toolset.
# For example, this customized tool can perform a dynamically-built query.
# `query_tool.execute_sql` is a coroutine function, so the wrapper must be
# `async def` and `await` it; GoogleTool supports async tool functions.
async def count_rows_tool(
    table_name: str,
    credentials: Credentials,  # GoogleTool handles `credentials`
    settings: SpannerToolSettings,  # GoogleTool handles `settings`
    tool_context: ToolContext,  # GoogleTool handles `tool_context`
):
  """Counts the total number of rows for a specified table.

  Args:
    table_name: The name of the table for which to count rows.

  Returns:
      The total number of rows in the table.
  """

  # Replace the following settings for a specific Spanner database.
  PROJECT_ID = "<PROJECT_ID>"
  INSTANCE_ID = "<INSTANCE_ID>"
  DATABASE_ID = "<DATABASE_ID>"

  query = f"""
  SELECT count(*) FROM {table_name}
    """

  return await query_tool.execute_sql(
      project_id=PROJECT_ID,
      instance_id=INSTANCE_ID,
      database_id=DATABASE_ID,
      query=query,
      credentials=credentials,
      settings=settings,
      tool_context=tool_context,
  )

# Agent Definition
spanner_agent = Agent(
    model=GEMINI_MODEL,
    name=AGENT_NAME,
    description=(
        "Agent to answer questions about Spanner database and execute SQL queries."
    ),
    instruction="""
        You are a data assistant agent with access to several Spanner tools.
        Make use of those tools to answer the user's questions.
    """,
    tools=[
        spanner_toolset,
        # Add customized Spanner tool based on the built-in Spanner toolset.
        GoogleTool(
            func=count_rows_tool,
            credentials_config=credentials_config,
            tool_settings=tool_settings,
        ),
    ],
)


# Session and Runner
session_service = InMemorySessionService()

# Optionally, Spanner can be used as the Database Session Service for production.
# Note that it's suggested to use a dedicated instance/database for storing sessions.
# session_service_spanner_db_url = "spanner+spanner:///projects/PROJECT_ID/instances/INSTANCE_ID/databases/my-adk-session"
# session_service = DatabaseSessionService(db_url=session_service_spanner_db_url)

session = asyncio.run(
    session_service.create_session(
        app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
    )
)
runner = Runner(
    agent=spanner_agent, app_name=APP_NAME, session_service=session_service
)


# Agent Interaction
def call_agent(query):
    """
    Helper function to call the agent with a query.
    """
    content = types.Content(role="user", parts=[types.Part(text=query)])
    events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    print("USER:", query)
    for event in events:
        if event.is_final_response() and event.content and event.content.parts:
            final_response = event.content.parts[0].text
            print("AGENT:", final_response)

# Replace the Spanner database and table names below with your own.
call_agent("List all tables in projects/<PROJECT_ID>/instances/<INSTANCE_ID>/databases/<DATABASE_ID>")
call_agent("Describe the schema of <TABLE_NAME>")
call_agent("List the top 5 rows in <TABLE_NAME>")

The vector_store_similarity_search 该工具使代理能够对配置为向量存储的 Spanner 表进行语义搜索。这一功能对于构建具有上下文感知能力的 RAG(Retrieval with Adaptive Grammars)应用程序至关重要;它允许 AI 模型根据语义含义而非精确的关键词匹配来检索数据库中的相关信息。通过相应的配置设置, SpannerVectorStoreSettings通过这种方式,您的代理可以更好地理解用户查询的意图,并根据最相关的 Spanner 数据来生成相应的响应。

以下示例将 Spanner 表配置为向量存储(vector store),并完成了相应的连接(wiring)操作。 vector_store_similarity_search 将这个工具转换为一个 RAG(Retrieval, Adaptation, and Generation)代理:

import google.auth
from google.adk.agents import LlmAgent
from google.adk.tools.spanner import SpannerCredentialsConfig, SpannerToolset
from google.adk.tools.spanner.settings import (
    Capabilities,
    SpannerToolSettings,
    SpannerVectorStoreSettings,
)

# 1. Define Spanner tool config with vector store settings
my_vector_store_settings = SpannerVectorStoreSettings(
    project_id="your-gcp-project",
    instance_id="your-spanner-instance",
    database_id="your-database",
    table_name="my_products",
    content_column="productDescription",
    embedding_column="productDescriptionEmbedding",
    vector_length=768,
    vertex_ai_embedding_model_name="text-embedding-005",
    selected_columns=["productId", "productName", "productDescription"],
    nearest_neighbors_algorithm="EXACT_NEAREST_NEIGHBORS",
    top_k=3,
    distance_type="COSINE",
    additional_filter="inventoryCount > 0",
)

my_tool_settings = SpannerToolSettings(
    capabilities=[Capabilities.DATA_READ],
    vector_store_settings=my_vector_store_settings,
)

# 2. Initialize the Spanner toolset. SpannerCredentialsConfig requires
# credentials, an external access token key, or a client ID and secret.
credentials, _ = google.auth.default()
credentials_config = SpannerCredentialsConfig(credentials=credentials)
my_spanner_toolset = SpannerToolset(
    credentials_config=credentials_config,
    spanner_tool_settings=my_tool_settings,
    tool_filter=["vector_store_similarity_search"],
)

# 3. Use the toolset in your RAG agent
my_rag_agent = LlmAgent(
    model="gemini-flash-latest",
    name="product_search_agent",
    instruction="""
    You are a helpful assistant that answers user questions by finding similar products.
    1. Always use the `vector_store_similarity_search` tool to find relevant product information.
    2. If no relevant information is found, state that no matching products were found.
    3. Present the relevant product details clearly in your response.
    """,
    tools=[my_spanner_toolset],
)

配置

The SpannerVectorStoreSettings 上面使用的类定义了相关内容的实现方式(即如何完成特定的功能或操作)。 vector_store_similarity_search 该功能可以执行相应的操作,并接受以下参数:

必填参数

  • project_id:需要您的 Google Cloud 项目 ID 进行身份验证。
  • instance_id:Spanner 实例的 ID。
  • database_id:Spanner 数据库的 ID。
  • table_name:`Spanner` 表中存储了向量嵌入(vector embeddings)数据。
  • embedding_column: The ARRAY<FLOAT> 或者 ARRAY<DOUBLE> 存储向量嵌入(vector embeddings)的列。
  • content_column该列包含需要检索的原始文本或内容。
  • vector_length你的嵌入向量的维度必须与你的模型相匹配。
  • vertex_ai_embedding_model_name用于生成嵌入值的模型,例如 “text-embedding-005”。

可选参数

  • selected_columns:您可以包含在搜索结果中的列列表,例如元数据或标识符。
  • nearest_neighbors_algorithm您用于搜索的算法,例如: EXACT_NEAREST_NEIGHBORS 和 APPROXIMATE_NEAREST_NEIGHBORS.
    • num_leaves_to_search:搜索到的索引叶子节点的数量。仅在与……一起使用时才有意义。 APPROXIMATE_NEAREST_NEIGHBORS.
    • vector_search_index_settings:向量索引设置(Vector index settings)。仅在以下情况下需要设置: APPROXIMATE_NEAREST_NEIGHBORS.
  • top_k每次查询时需要检索的最近邻居的数量。
  • distance_type用于计算相似度的距离度量标准,例如…… COSINE 或者 EUCLIDEAN.
  • additional_filter:一个可选的 SQL 过滤字符串,用于在搜索过程中进行筛选。例如:`"inventoryCount > 0"`。

Spanner 管理工具集

The SpannerAdminToolset 该功能允许对您的 Spanner 实例和数据库执行管理操作。请注意,这需要单独导入相应的库文件。

请谨慎使用。

这套工具集可以创建、检查以及修改 Spanner 实例和数据库,并能谨慎地控制访问权限。请确保执行环境(例如应用程序默认凭据或服务账户密钥)仅被授权项目使用,并且仅授予最低限度的必要 IAM 权限(例如 `spanner.admin` 角色)。

可用的工具

  • list_instances:列出项目中的 Spanner 实例。
  • get_instance:检索 Spanner 实例的详细信息。
  • create_database:创建一个新的 Spanner 数据库。
  • list_databases:列出实例中的 Spanner 数据库。
  • create_instance:创建一个新的 Spanner 实例。
  • list_instance_configs:列出可用的 Spanner 实例配置。
  • get_instance_config:检索 Spanner 实例配置的详细信息。

配置

在使用此工具集之前,请先设置所需的环境变量:

  • SPANNER_PROJECT:用于操作的 GCP 项目 ID。
  • SPANNER_INSTANCE (可选):默认的 Spanner 实例 ID。
  • SPANNER_DATABASE (可选):默认的数据库 ID。

与代理程序(agent)一起使用。

初始化 SpannerAdminToolset 要访问 Google Cloud Spanner 的管理功能,首先需要获取相应的访问凭据(例如 API 密钥)。然后,将这些凭据传递给相应的系统或服务。 tools 您的……列表 LlmAgent 为了让您的代理能够管理 Spanner 资源。

from google.adk.agents import LlmAgent
from google.adk.tools.spanner import SpannerAdminToolset

# Initialize the Spanner admin toolset
spanner_admin_tools = SpannerAdminToolset()

# Register the toolset with your agent, ensuring model and instructions are provided
agent = LlmAgent(
    name="SpannerAdminAgent",
    model="gemini-flash-latest",
    instruction=(
        "You are a helpful database administrator. Use the SpannerAdminToolset "
        "to manage and query Spanner instances and databases in the project."
    ),
    tools=[spanner_admin_tools]
)