1. はじめに
この Codelab では、Agent Development Kit(ADK)を使用してマルチエージェント システムを構築し、BigQuery Agent Analytics プラグインを使用してエージェントのオブザーバビリティを有効にします。エージェントに一連の質問を行い、BigQuery を使用して会話のトレースとエージェント ツールの使用状況を分析します。

演習内容
- ADK を使用してマルチエージェント小売アシスタントを構築する
- BigQuery Agent Analytics プラグインを初期化して、このエージェントの実行に関するトレースデータをキャプチャし、BigQuery に保存する
- BigQuery でエージェントのログデータを分析する
必要なもの
- ウェブブラウザ(Chrome など)
- 課金が有効になっている Google Cloud プロジェクト
- Gmail アカウント。次のセクションでは、この Codelab で使用できる 5 ドルの無料クレジットを利用して、新しいプロジェクトを設定する方法について説明します。
この Codelab は、初心者を含むあらゆるレベルのデベロッパーを対象としています。ADK 開発には、Google Cloud Shell のコマンドライン インターフェースと Python コードを使用します。Python の専門家である必要はありませんが、コードの読み取り方法に関する基本的な知識があると、コンセプトを理解するのに役立ちます。
2. 始める前に
Google Cloud プロジェクトの作成
- Google Cloud コンソールのプロジェクト選択ページで、クラウド プロジェクトを選択または作成します。

- Cloud プロジェクトに対して課金が有効になっていることを確認します。詳しくは、プロジェクトで課金が有効になっているかどうかを確認する方法をご覧ください。
Cloud Shell の起動
Cloud Shell は、必要なツールがプリロードされた Google Cloud で動作するコマンドライン環境です。
- Google Cloud コンソールの上部にある [Cloud Shell をアクティブにする] をクリックします。

- Cloud Shell に接続したら、次のコマンドを実行して Cloud Shell で認証を確認します。
gcloud auth list
- 次のコマンドを実行して、プロジェクトが gcloud で使用するように構成されていることを確認します。
gcloud config get project
- プロジェクトが想定どおりに構成されていない場合は、次のコマンドを使用してプロジェクトを設定します。
export PROJECT_ID=<YOUR_PROJECT_ID>
gcloud config set project $PROJECT_ID
API を有効にする
- 次のコマンドを実行して、必要なすべての API とサービスを有効にします。
gcloud services enable bigquery.googleapis.com \
cloudresourcemanager.googleapis.com \
aiplatform.googleapis.com
- コマンドが正常に実行されると、次のようなメッセージが表示されます。
Operation "operations/..." finished successfully.
3. インストールとセットアップ
Cloud Shell に戻り、ホーム ディレクトリにいることを確認します。
Cloud Shell で次のコマンドを実行して、BigQuery に adk_logs という名前の新しいデータセットを作成します。
bq mk --dataset --location=US adk_logs
次に、仮想 Python 環境を作成し、必要なパッケージをインストールします。
- Cloud Shell で新しいターミナルタブを開き、次のコマンドを実行して
adk-agent-observabilityという名前のフォルダを作成して移動します。
mkdir adk-agent-observability
cd adk-agent-observability
- 仮想 Python 環境を作成します。
python -m venv .venv
- 仮想環境をアクティブにします。
source .venv/bin/activate
- ADK をインストールします。
pip install --upgrade google-adk
4. ADK アプリケーションを作成する
それでは、小売アシスタント エージェントを作成しましょう。このエージェントは、...
- ADK 作成ユーティリティ コマンドを実行して、必要なフォルダとファイルを含む新しいエージェント アプリケーションをスキャフォールディングします。
adk create retail_assistant_app
画面上の指示に沿って操作します。
- モデルとして gemini-2.5-flash を選択します。
- バックエンドに Vertex AI を選択します。
- デフォルトの Google Cloud プロジェクト ID とリージョンを確認します。
以下にやり取りの例を示します。

- Cloud Shell で [エディタを開く] ボタンをクリックして Cloud Shell エディタを開き、新しく作成したフォルダとファイルを表示します。

生成されたファイルを確認します。
retail_assistant_app/
├── .venv/
└── retail_assistant_app/
├── __init__.py
├── agent.py
└── .env
- init.py: フォルダを Python モジュールとしてマークします。
- agent.py: 初期エージェントの定義が含まれています。
- .env: このファイルを表示するには、[View] > [Toggle Hidden Files] をクリックする必要がある場合があります。

- .env ファイルにはプロジェクトの環境変数が含まれています。プロンプトで正しく設定されなかった変数を更新します。
GOOGLE_GENAI_USE_VERTEXAI=1
GOOGLE_CLOUD_PROJECT=<YOUR_GOOGLE_PROJECT_ID>
GOOGLE_CLOUD_LOCATION=<YOUR_GOOGLE_CLOUD_REGION>
5. エージェントを定義する
次に、階層型のマルチエージェント システムを定義します。
- リアルタイム トレンド エージェント: Google 検索を使用して、現在のファッション トレンドを検索します。
- 在庫データ エージェント: BigQuery ツールセットを使用して、一般公開されている thelook_ecommerce データセットをクエリし、利用可能な商品を確認します。
- 小売アシスタント(ルート)エージェント: トレンド エージェントにアドバイスを求め、在庫エージェントに一致する商品を尋ねることで、ワークフローをオーケストレーションします。
retail_assistant_app/agent.py の内容全体を次のコードに置き換えます。
import os
import uuid
import asyncio
import google.auth
import dotenv
from google.genai import types
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.runners import InMemoryRunner
from google.adk.tools import AgentTool, google_search
from google.adk.tools.bigquery import BigQueryCredentialsConfig, BigQueryToolset
from google.adk.plugins.bigquery_agent_analytics_plugin import BigQueryAgentAnalyticsPlugin
dotenv.load_dotenv()
# --- Configuration ---
PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT', 'project_not_set')
DATASET_ID = "adk_logs"
TABLE_ID = "retail_assistant_agent_logs"
APP_NAME = "retail_assistant_agent"
USER_ID = "test_user"
# --- Toolsets ---
credentials, _ = google.auth.default()
credentials_config = BigQueryCredentialsConfig(credentials=credentials)
bigquery_toolset = BigQueryToolset(
credentials_config=credentials_config
)
# --- Agents ---
# 1. Trend Spotter
real_time_agent = Agent(
name="real_time_agent",
model="gemini-2.5-flash",
description="Researches external factors like weather, local events, and current fashion trends.",
instruction="""
You are a real-time research agent.
Use Google Search to find real-time information relevant to the user's request,
such as the current weather in their location or trending styles.
""",
tools=[google_search]
)
# 2. Inventory Manager
inventory_data_agent = Agent(
name="inventory_data_agent",
model="gemini-2.5-flash",
description="Oversees product inventory in the BigQuery `thelook_ecommerce` dataset to find available items and prices.",
instruction=f"""
You manage the inventory. You have access to the `bigquery-public-data.thelook_ecommerce` dataset via the BigQuery toolset.
Run all BigQuery queries the project id of: '{PROJECT_ID}'
Your workflow:
1. Look at the products table.
2. Find items that match the requirements, factor in the results from the trend_setter agent if there are any.
3. Return with a user friendly response, including the list of specific products and prices.
""",
tools=[bigquery_toolset]
)
# 3. Root Orchestrator
root_agent = Agent(
name="retail_assistant",
model="gemini-2.5-flash",
description="The primary orchestrator, responsible for handling user input, delegating to sub-agents, and synthesizing the final product recommendation.",
instruction="""
You are a Retail Assistant.
You can ask the 'real_time_agent' agent for any realtime information needed, or style advice, include any information provided by the user.
You should ask the 'inventory_data_agent' agent to find a maximum of 3 available items matching that style.
Combine the results into a recommendation.
""",
tools=[AgentTool(agent=real_time_agent)],
sub_agents=[inventory_data_agent]
)
6. BigQuery Agent Analytics プラグインでログを生成する
次に、実行データをキャプチャするように BigQuery Agent Analytics プラグインを構成します。
これを行うには、App クラスのインスタンスを作成します。このクラスは、エージェントのランタイム コンテナとして機能します。会話ループを管理し、ユーザーの状態を処理し、接続されたプラグイン(エージェント分析ロガーなど)をオーケストレートします。
以下のコード:
- ロギング プラグインの初期化: 必要な接続情報を使用して
BigQueryAgentAnalyticsPluginを作成します。 - プラグインの統合: 初期化された BigQuery プラグインを
Appコンストラクタに渡して、エージェント実行時のイベントが自動的にキャプチャされ、ログに記録されるようにします。 - エージェントの実行とロギング:
runner.run_asyncを介して会話フローを実行します。このとき、プラグインが同時にイベントのシーケンス全体を収集して BigQuery に送信し、最後にリソースを閉じます。
次のコードをコピーして、agent.py ファイルのエージェント定義の下に貼り付けます。
async def main(prompt: str):
"""Runs a conversation with the BigQuery agent using the ADK Runner."""
bq_logger_plugin = BigQueryAgentAnalyticsPlugin(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID
)
app = App(name=APP_NAME, root_agent=root_agent, plugins=[bq_logger_plugin])
runner = InMemoryRunner(app=app)
try:
session_id = f"{USER_ID}_{uuid.uuid4().hex[:8]}"
my_session = await runner.session_service.create_session(
app_name=APP_NAME, user_id=USER_ID, session_id=session_id
)
async for event in runner.run_async(
user_id=USER_ID,
new_message=types.Content(
role="user", parts=[types.Part.from_text(text=prompt)]
),
session_id=my_session.id,
):
if event.content.parts and event.content.parts[0].text:
print(f"** {event.author}: {event.content.parts[0].text}")
except Exception as e:
print(f"Error in main: {e}")
finally:
print("Closing BQ Plugin...")
await bq_logger_plugin.close()
print("BQ Plugin closed.")
async def run_all_prompts():
"""Runs all prompts in a single event loop."""
prompts = [
"what outfits do you have available that are suitable for the weather in london this week?",
"You are such a cool agent! I need a gift idea for my friend who likes yoga.",
"I'd like to complain - the products sold here are not very good quality!"
]
for prompt in prompts:
await main(prompt)
if __name__ == "__main__":
asyncio.run(run_all_prompts())
計測が完了したので、エージェントの動作を確認しましょう。スクリプトを実行して会話ワークフローをトリガーします。
python retail_assistant_app/agent.py
小売アシスタントが次のようにワークフローをオーケストレーションします。
- リアルタイム トレンド エージェント(real_time_agent)に、ロンドンの天気を特定し、適切なファッション トレンドを検索するよう指示します。
- その後、これらのトレンドに一致する特定の商品を
thelook_ecommerceBigQuery データセットでクエリするよう、在庫データ エージェント(inventory_data_agent)に委任します。 - 最後に、ルート オーケストレーターが結果を統合して最終的な推奨事項を提示します。
この一連の処理の間、プラグインはエージェントの実行トレースを BigQuery にストリーミングします。
7. エージェント ログを分析する
ツールの使用状況
これで、エージェントが舞台裏で何を行っていたかを確認できるようになりました。データが BigQuery にストリーミングされ、分析の準備が整いました。
- Google Cloud コンソールで「BigQuery」を検索します。
- [エクスプローラ] ペインでプロジェクトを探します。
adk_logsデータセットを開きます。retail_assitant_agent_logsテーブルを開き、[クエリ] をクリックします。

エージェントが行ったツール呼び出しを確認し、ツールエラーをキャプチャするには、BigQuery エディタで次のクエリを実行します。
SELECT
-- Extract the tool name directly from the JSON key "tool"
JSON_VALUE(content, '$.tool') AS tool_name,