用于 ADK 的 BigQuery 工具¶
这是一组用于实现与 BigQuery 集成的工具,具体包括:
list_dataset_ids:获取 GCP 项目中存在的 BigQuery 数据集的 ID。get_dataset_info:获取有关 BigQuery 数据集的元数据。list_table_ids:获取 BigQuery 数据集中存在的表格 ID。get_table_info:获取有关 BigQuery 表的元数据信息。get_job_info:获取有关 BigQuery 作业的元数据信息(如任务槽的使用情况、配置信息、统计数据、作业状态等)。execute_sql:在 BigQuery 中运行 SQL 查询并获取结果。forecast:使用该工具运行 BigQuery AI 的时间序列预测功能。AI.FORECASTfunction.analyze_contribution:执行 BigQuery ML 的贡献度分析,以了解导致指标变化的原因。detect_anomalies该工具用于训练 ARIMAPLUS 模型,并检测时间序列数据中的异常值。ask_data_insights:使用自然语言回答关于 BigQuery 表中数据的问题。search_catalog:通过 Dataplex,利用自然语言语义搜索功能来查找 BigQuery 中的数据集和表格。
这些组件被打包在工具集中(即它们被一起放入同一个软件包或工具集中)。 BigQueryToolset.
位置设置
要选择一个 BigQuery 数据库的位置,请传递相应的参数。 BigQueryToolConfig(location="US")
from google.adk.integrations.bigquery.config 作为该工具集的……
bigquery_tool_config1. 选择一个 位置
该参数需要与你的数据集相匹配;如果将其设置为“未设置”(unset),则 BigQuery 会自动决定数据存储的位置。
安装¶
BigQuery 工具依赖于 Google Cloud 客户端库,而这些库并不包含在基础软件包中。 google-adk **安装方法:** 使用相应的工具或命令将它们安装到位。 gcp extra:
身份验证(Authentication)¶
The BigQueryToolset 支持多种身份验证机制(通过……实现)。 BigQueryCredentialsConfig.
应用程序默认凭据(Application Default Credentials)¶
你应该在本地开发以及使用 Google Cloud 服务(如 Cloud Run 和 GKE)时采用这种方法。
import google.auth
from google.adk.integrations.bigquery import BigQueryToolset, BigQueryCredentialsConfig
# Load Application Default Credentials
credentials, project_id = google.auth.default()
# Configure the toolset
credentials_config = BigQueryCredentialsConfig(credentials=credentials)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)
服务账户(Service Account)¶
您可以明确提供一个服务账户文件或相关信息。
from google.oauth2 import service_account
from google.adk.integrations.bigquery import BigQueryToolset, BigQueryCredentialsConfig
# Load Service Account credentials
credentials = service_account.Credentials.from_service_account_file('path/to/key.json')
# Configure the toolset
credentials_config = BigQueryCredentialsConfig(credentials=credentials)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)
外部访问令牌(External Access Token)¶
对于那些需要代表最终用户执行操作的应用程序来说,您可以直接使用从访问令牌(例如通过 OAuth2 流程或外部 IDP 获得的访问令牌)中提取的用户凭据。
from google.oauth2.credentials import Credentials
from google.adk.integrations.bigquery import BigQueryToolset, BigQueryCredentialsConfig
# Assume 'user_token' is obtained via an external OAuth flow
credentials = Credentials(token=user_token)
# Configure the toolset
credentials_config = BigQueryCredentialsConfig(credentials=credentials)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)
外部身份验证提供商(External Auth Providers)¶
如果您正在与外部身份验证提供商进行集成(在该提供商中,令牌由平台本身管理,例如 Gemini Enterprise),请使用以下方法: external_access_token_key.
from google.adk.integrations.bigquery import BigQueryToolset, BigQueryCredentialsConfig
# The key used to look up the access token in the session state
credentials_config = BigQueryCredentialsConfig(
external_access_token_key="YOUR_AUTH_ID"
)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)
交互式身份验证(ADK Web)¶
在使用该功能时,请确保遵循以下步骤: adk web 该接口用于实现交互式会话;您可以通过提供 OAuth 2.0 客户端凭据来触发登录流程。该机制既适用于本地开发环境,也适用于将 ADK 代理部署到 Cloud Run 等环境中的情况。
from google.adk.integrations.bigquery import BigQueryToolset, BigQueryCredentialsConfig
# Provide OAuth 2.0 Client ID and Secret
credentials_config = BigQueryCredentialsConfig(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET"
)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)
示例代码¶
以下示例代码展示了如何使用该功能。 BigQueryToolset 在 ADK 代理中,使用应用程序默认凭据(Application Default Credentials,简称 ADC)进行身份验证。
# 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.integrations.bigquery import BigQueryCredentialsConfig
from google.adk.integrations.bigquery import BigQueryToolset
from google.adk.integrations.bigquery.config import BigQueryToolConfig
from google.adk.integrations.bigquery.config import WriteMode
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
import google.auth
# Define constants for this example agent
AGENT_NAME = "bigquery_agent"
APP_NAME = "bigquery_app"
USER_ID = "user1234"
SESSION_ID = "1234"
GEMINI_MODEL = "gemini-2.0-flash"
# Define a tool configuration to block any write operations
tool_config = BigQueryToolConfig(write_mode=WriteMode.BLOCKED)
# Use Application Default Credentials (ADC) for BigQuery authentication
# https://cloud.google.com/docs/authentication/provide-credentials-adc
application_default_credentials, _ = google.auth.default()
credentials_config = BigQueryCredentialsConfig(
credentials=application_default_credentials
)
# Instantiate a BigQuery toolset
bigquery_toolset = BigQueryToolset(
credentials_config=credentials_config, bigquery_tool_config=tool_config
)
# Agent Definition
bigquery_agent = Agent(
model=GEMINI_MODEL,
name=AGENT_NAME,
description=(
"Agent to answer questions about BigQuery data and models and execute"
" SQL queries."
),
instruction="""\
You are a data science agent with access to several BigQuery tools.
Make use of those tools to answer the user's questions.
""",
tools=[bigquery_toolset],
)
# Session and Runner
async def setup_session_and_runner():
session_service = InMemorySessionService()
await session_service.create_session(
app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
)
return Runner(
agent=bigquery_agent, app_name=APP_NAME, session_service=session_service
)
# Agent Interaction
async def call_agent_async(runner, query):
"""
Helper function to call the agent with a query.
"""
content = types.Content(role="user", parts=[types.Part(text=query)])
events = runner.run_async(
user_id=USER_ID, session_id=SESSION_ID, new_message=content
)
print("USER:", query)
async 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)
async def main():
runner = await setup_session_and_runner()
await call_agent_async(
runner, "Are there any ml datasets in bigquery-public-data project?"
)
await call_agent_async(runner, "Tell me more about ml_datasets.")
await call_agent_async(runner, "Which all tables does it have?")
await call_agent_async(runner, "Tell me more about the census_adult_income table.")
await call_agent_async(runner, "How many rows are there per income bracket?")
await call_agent_async(
runner,
"What is the statistical correlation between education_num, age, and the"
" income_bracket?",
)
# Note: In Colab or another notebook, an event loop is already running, so call
# `await main()` directly instead of `asyncio.run(main())`.
asyncio.run(main())
示例代理(Sample Agent)¶
如需一个完整的、可直接运行的 BigQuery 驱动代理示例(其中包含详细的身份验证流程),请参阅…… BigQuery 示例代理(BigQuery Sample Agent) 在 GitHub 上。
注意:如果您想将 BigQuery 数据代理作为工具来使用,请参阅…… 用于 ADK 的 Data Agents 工具.