📝

Google ADK公式ドキュメントを日本語で読む - Get Started

に公開

はじめに

本記事では、Google ADKのページに翻訳ツールを適用して日本語にしながら読み進めていきます。

https://google.github.io/adk-docs/

他部分の翻訳は、以下のリンクから確認できます。

Google ADK公式ドキュメントを日本語で読む - まとめ

Google ADK とは

Google ADK (Agent Development Kit) は、AIエージェントの開発と展開のための柔軟でモジュール式のフレームワークです。
GeminiやGoogleエコシステムに最適化されていますが、モデルに依存せず、展開方法にも依存しないように設計されています。ADKは、エージェント開発をソフトウェア開発のように感じさせることを目的としており、開発者が単純なタスクから複雑なワークフローまで、エージェントアーキテクチャを簡単に作成、展開、およびオーケストレーションできるようにします。

Quickstart

Agent Development Kit (ADK) のインストール、複数のツールを持つ基本的なエージェントのセットアップおよびローカルでの実行方法(ターミナルまたはブラウザベースの開発UI)について説明します。

補足: Python 3.9以上かつ、uvがインストールされていることを前提としています。
uvがインストールされていない場合は、以下のリンクを参照してインストールしてください。
https://docs.astral.sh/uv/getting-started/installation/

1. Set up Environment & Install ADK

まず、ADKをインストールするための環境をセットアップします。
以下のコマンドを実行して、ADKをインストールします。

$ uv init
$ uv add google-adk

2. Create Agent Project

次に、ADKを使用してエージェントプロジェクトを作成します。
以下のようなディレクトリ構造を持つプロジェクトを作成します。

.
└── multi_tool_agent/
    ├── __init__.py
    ├── agent.py
    └── .env

multi_tool_agent ディレクトリを作成し、その中に __init__.pyagent.py.env ファイルを作成します。

$ mkdir multi_tool_agent
$ touch multi_tool_agent/__init__.py
$ touch multi_tool_agent/agent.py
$ touch multi_tool_agent/.env

次に、__init__.pyagent.py ファイルに以下のコードを追加します。

# multi_tool_agent/__init__.py
from . import agent
# multi_tool_agent/agent.py
import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent

def get_weather(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city for which to retrieve the weather report.

    Returns:
        dict: status and result or error msg.
    """
    if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
    else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not available.",
        }


def get_current_time(city: str) -> dict:
    """Returns the current time in a specified city.

    Args:
        city (str): The name of the city for which to retrieve the current time.

    Returns:
        dict: status and result or error msg.
    """

    if city.lower() == "new york":
        tz_identifier = "America/New_York"
    else:
        return {
            "status": "error",
            "error_message": (
                f"Sorry, I don't have timezone information for {city}."
            ),
        }

    tz = ZoneInfo(tz_identifier)
    now = datetime.datetime.now(tz)
    report = (
        f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
    )
    return {"status": "success", "report": report}


root_agent = Agent(
    name="weather_time_agent",
    model="gemini-2.0-flash",
    description=(
        "Agent to answer questions about the time and weather in a city."
    ),
    instruction=(
        "You are a helpful agent who can answer user questions about the time and weather in a city."
    ),
    tools=[get_weather, get_current_time],
)

envの中身に関しては次の章で説明します。

3. Set up the model

あなたのエージェントが、応答を生成する能力は、LLMによって支えられています。
エージェントは、この外部LLMサービスに安全にアクセスする必要があり、そのためには認証情報が必要です。
有効な認証情報がない場合、エージェントは機能しなくなります。

ここでは、Gemini - Google AI StudioGemini - Google Cloud Vertex AI の2つのモデルを使用する方法を説明します。

Gemini - Google AI Studio

  1. Google AI StudioからAPIキーを取得します。
  2. .env ファイルに以下の内容を追加します。
GOOGLE_GENAI_USE_VERTEXAI=FALSE
GOOGLE_API_KEY=PASTE_YOUR_ACTUAL_API_KEY_HERE

Gemini - Google Cloud Vertex AI

前提: Google Cloud の アカウントとプロジェクトが必要です。

  1. Google Cloud projectのセットアップをします
  2. gcloud CLIのセットアップをします
  3. ターミナルから gcloud auth login を実行して、Google Cloudに認証します。
    .env ファイルを開き、以下のコードをコピーして、プロジェクトIDとロケーションを更新します。
GOOGLE_GENAI_USE_VERTEXAI=TRUE
GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
GOOGLE_CLOUD_LOCATION=LOCATION

3. Run Your Agent

次に、エージェントを実行します。
エージェントの実行には3つの方法があります。

1. Dev UI

Dev UIを使用すると、ブラウザベースの開発UIでエージェントを実行できます。
以下のコマンドを実行して、Dev UIを起動します。

$ uv run adk web

もし、make_subprocess_transport NotImplementedErrorが発生した場合は、以下のコマンドを実行してください。
uv run adk web --no-reload

  1. ブラウザで http://localhost:8000 にアクセスします。
  2. ドロップダウンからmulti_tool_agent を選択します。
  3. テキストボックスに質問を入力します。
  4. 左側のイベントタブを使用して、個々の関数呼び出し、応答、およびモデル応答をアクションをクリックして検査できます。
  5. マイクを有効にして、音声入力を使用することもできます。

2. Terminal

ターミナルでエージェントを実行するには、以下のコマンドを実行します。

$ uv run adk run multi_tool_agent

3. API Server

adk api_serverは、ローカルFastAPIサーバーを作成できるようにし、エージェントをデプロイする前にローカルのcURLリクエストをテストできるようにします。

$ uv run adk api_server

adk api_serverを使用してテストする方法については、次の章で解説します。

Testing

エージェントをデプロイする前に、意図した通りに動作していることを確認するためにテストする必要があります。
開発環境でエージェントをテストする最も簡単な方法は、以下のコマンドを使用してADK Web UIを使用することです。

$ uv run adk api_server
INFO:     Started server process
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

1. Sessionを作成する

セッションを作成するには、以下のcURLコマンドを実行します

$ curl -X POST http://localhost:8000/apps/multi_tool_agent/users/test_user_123/sessions/session_123 \
  -H "Content-Type: application/json" \
  -d '{"state": {"key1": "value1", "key2": 42}}'

これで、セッションが作成され、session_123というIDが割り当てられます。

http://localhost:8000/apps/multi_tool_agent/users/test_user_123/sessions/session_123 は、エージェント multi_tool_agent の新しいセッションを作成します。ここで、test_user_123 はユーザーID、session_123 はセッションIDです。これらは任意の値に置き換えることができます。
{"state": {"key1": "value1", "key2": 42}} はオプションで、セッションを作成する際にエージェントの既存の状態(辞書)をカスタマイズするために使用できます。
セッションが正常に作成された場合、セッション情報が返されます。

{
    "id": "session_123",
    "appName": "multi_tool_agent",
    "userId": "test_user_123",
    "state":
        {
            "state": {
                "key1":"value1",
                "key2":42
            }
        },
    "events": [],
    "lastUpdateTime": 1751301352.88756
}

補足: 同じユーザーIDで複数のセッションを作成することはできません。

2. Queryを送信する

セッションを作成したら、エージェントにクエリを送信できます。
/run または /run_sse エンドポイントを使用して、エージェントにクエリを送信します。

補足: run_sseは、サーバー送信イベントとして返され、イベントオブジェクトのストリームです。イベントが利用可能になるとすぐに通知を受け取りたい人に適しています。run_sseを使用すると、トークンレベルのストリーミングを有効にするために、ストリーミングをtrueに設定することもできます。

/run

/run エンドポイントを使用して、エージェントにクエリを送信します。

$ curl -X POST http://localhost:8000/run \
-H "Content-Type: application/json" \
-d '{
"appName": "multi_tool_agent",
"userId": "test_user_123",
"sessionId": "session_123",
"newMessage": {
    "role": "user",
    "parts": [{
    "text": "Hey whats the weather in new york today"
    }]
}
}'

このコマンドは、multi_tool_agent エージェントに対して、ユーザーID test_user_123 とセッションID session_123 を使用してクエリを送信します。
クエリの内容は「Hey whats the weather in new york today」です。
エージェントは、クエリに対する応答を生成し、以下のようなJSONレスポンスを返します。

[{"content":{"parts":[{"functionCall":{"id":"adk-cc868751-308e-4ea0-9ad3-65e8217b6d81","args":{"city":"new york"},"name":"get_weather"}}],"role":"model"},"usageMetadata":{"candidatesTokenCount":6,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":6}],"promptTokenCount":247,"promptTokensDetails":[{"modality":"TEXT","tokenCount":247}],"totalTokenCount":253},"invocationId":"e-9392d0ff-09ad-4419-a65d-d994dda4f4d3","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":[],"id":"flMsELcB","timestamp":1751303040.912205},{"content":{"parts":[{"functionResponse":{"id":"adk-cc868751-308e-4ea0-9ad3-65e8217b6d81","name":"get_weather","response":{"status":"success","report":"The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit)."}}}],"role":"user"},"invocationId":"e-9392d0ff-09ad-4419-a65d-d994dda4f4d3","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"D00mQykr","timestamp":1751303041.837428},{"content":{"parts":[{"text":"OK. The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit).\n"}],"role":"model"},"usageMetadata":{"candidatesTokenCount":25,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":25}],"promptTokenCount":281,"promptTokensDetails":[{"modality":"TEXT","tokenCount":281}],"totalTokenCount":306},"invocationId":"e-9392d0ff-09ad-4419-a65d-d994dda4f4d3","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"Rj4QATcK","timestamp":1751303041.839026}]

/run_sse

/run_sse エンドポイントを使用して、エージェントにクエリを送信します。

$ curl -X POST http://localhost:8000/run_sse \
-H "Content-Type: application/json" \
-d '{
"appName": "multi_tool_agent",
"userId": "test_user_123",
"sessionId": "session_123",
"newMessage": {
    "role": "user",
    "parts": [{
    "text": "Hey whats the weather in new york today"
    }]
},
"streaming": false
}'

streamingをtrueに設定すると、トークンレベルのストリーミングが有効になり、応答が複数のチャンクで返されます。
また、出力は以下のようになります。

data: {"content":{"parts":[{"functionCall":{"id":"adk-9a0d8977-6fbb-4c9e-82b2-66b73f415cc4","args":{"city":"new york"},"name":"get_weather"}}],"role":"model"},"usageMetadata":{"candidatesTokenCount":6,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":6}],"promptTokenCount":180,"promptTokensDetails":[{"modality":"TEXT","tokenCount":180}],"totalTokenCount":186},"invocationId":"e-7e24ee97-d5b2-471a-9a4e-ecb56387c173","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":[],"id":"kMFfFVNh","timestamp":1751303268.535192}

data: {"content":{"parts":[{"functionResponse":{"id":"adk-9a0d8977-6fbb-4c9e-82b2-66b73f415cc4","name":"get_weather","response":{"status":"success","report":"The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit)."}}}],"role":"user"},"invocationId":"e-7e24ee97-d5b2-471a-9a4e-ecb56387c173","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"KXyGWzmZ","timestamp":1751303269.315019}

data: {"content":{"parts":[{"text":"OK. The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit).\n"}],"role":"model"},"usageMetadata":{"candidatesTokenCount":25,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":25}],"promptTokenCount":214,"promptTokensDetails":[{"modality":"TEXT","tokenCount":214}],"totalTokenCount":239},"invocationId":"e-7e24ee97-d5b2-471a-9a4e-ecb56387c173","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"gyIeeIj4","timestamp":1751303269.317399}

Discussion