コンテンツにスキップ

ADK用 BigQuery ツール

ADKでサポートPython v1.1.0

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: AI.FORECAST 関数を使用して BigQuery AI 時系列予測を実行します。
  • analyze_contribution: メトリックの変化の要因を把握するために BigQuery ML 寄与度分析を実行します。
  • detect_anomalies: ARIMA_PLUS モデルをトレーニングし、時系列データの異常を検出します。
  • ask_data_insights: 自然言語を使用して BigQuery テーブル内のデータに関する質問に回答します。
  • search_catalog: Dataplex を介した自然言語セマンティック検索を使用して BigQuery データセットとテーブルを検索します。

これらは BigQueryToolset ツールセットとしてパッケージ化されています。

認証

BigQueryToolsetBigQueryCredentialsConfig を介して複数の認証メカニズムをサポートしています。

アプリケーションのデフォルト認証情報 (Application Default Credentials)

ローカル開発や、Cloud Run や GKE などの Google Cloud サービスで実行する場合は、このアプローチを使用してください。

import google.auth
from google.adk.tools.bigquery import BigQueryToolset, BigQueryCredentialsConfig

# アプリケーションのデフォルト認証情報をロード
credentials, project_id = google.auth.default()

# ツールセットの構成
credentials_config = BigQueryCredentialsConfig(credentials=credentials)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)

サービス アカウント (Service Account)

サービス アカウント ファイルまたは情報を明示的に提供できます。

from google.oauth2 import service_account
from google.adk.tools.bigquery import BigQueryToolset, BigQueryCredentialsConfig

# サービス アカウントの認証情報をロード
credentials = service_account.Credentials.from_service_account_file('path/to/key.json')

# ツールセットの構成
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.tools.bigquery import BigQueryToolset, BigQueryCredentialsConfig

# 外部 OAuth フローによって 'user_token' が取得されたと仮定
credentials = Credentials(token=user_token)

# ツールセットの構成
credentials_config = BigQueryCredentialsConfig(credentials=credentials)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)

外部認証プロバイダ (External Auth Providers)

Gemini Enterprise など、トークンがプラットフォームによって管理される外部認証プロバイダと統合する場合は、external_access_token_key を使用します。

from google.adk.tools.bigquery import BigQueryToolset, BigQueryCredentialsConfig

# セッション状態内のアクセス トークンを検索するために使用されるキー
credentials_config = BigQueryCredentialsConfig(
    external_access_token_key="YOUR_AUTH_ID"
)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)

対話型認証 (Interactive Auth - ADK Web)

対話型セッションに adk web インターフェースを使用する場合、OAuth 2.0 クライアント認証情報を提供してログイン フローをトリガーできます。このメカニズムは、ローカル開発と Cloud Run などの環境にデプロイされた ADK エージェントの両方で機能します。

from google.adk.tools.bigquery import BigQueryToolset, BigQueryCredentialsConfig

# OAuth 2.0 クライアント ID とシークレットを提供
credentials_config = BigQueryCredentialsConfig(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET"
)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)

サンプル コード

次のサンプル コードは、アプリケーションのデフォルト認証情報 (ADC) を使用して ADK エージェントで BigQueryToolset を使用する方法を示しています。

# 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.tools.bigquery import BigQueryCredentialsConfig
from google.adk.tools.bigquery import BigQueryToolset
from google.adk.tools.bigquery.config import BigQueryToolConfig
from google.adk.tools.bigquery.config import WriteMode
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
session_service = InMemorySessionService()
session = asyncio.run(
    session_service.create_session(
        app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
    )
)
runner = Runner(
    agent=bigquery_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():
            final_response = event.content.parts[0].text
            print("AGENT:", final_response)


call_agent("Are there any ml datasets in bigquery-public-data project?")
call_agent("Tell me more about ml_datasets.")
call_agent("Which all tables does it have?")
call_agent("Tell me more about the census_adult_income table.")
call_agent("How many rows are there per income bracket?")
call_agent(
    "What is the statistical correlation between education_num, age, and the income_bracket?"
)

サンプル エージェント

詳細な認証例を含む BigQuery 搭載エージェントの完全な実行可能なサンプルについては、GitHub の BigQuery Sample Agent を参照してください。

注: BigQuery データ エージェントをツールとして使用する場合は、ADK用 Data Agents ツールを参照してください。