コンテンツにスキップ

クイックスタート

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

このクイックスタートは、Python 3.9以上またはJava 17以上とターミナルアクセスが可能なローカルIDE(VS Code、PyCharm、IntelliJ IDEAなど)を前提としています。この方法は、アプリケーションを完全にあなたのマシン上で実行し、内部開発に推奨されます。

1. 環境のセットアップとADKのインストール

仮想環境の作成と有効化(推奨):

# 作成
python -m venv .venv
# 有効化(新しいターミナルごと)
# macOS/Linux: source .venv/bin/activate
# Windows CMD: .venv\Scripts\activate.bat
# Windows PowerShell: .venv\Scripts\Activate.ps1

ADKのインストール:

pip install google-adk

ADKをインストールし、環境をセットアップするには、次の手順に進んでください。

2. エージェントプロジェクトの作成

プロジェクト構造

以下のプロジェクト構造を作成する必要があります:

parent_folder/
    multi_tool_agent/
        __init__.py
        agent.py
        .env

multi_tool_agentフォルダを作成します:

mkdir multi_tool_agent/

Windowsユーザーへの注意

次のいくつかのステップでWindows上でADKを使用する場合、mkdirechoのようなコマンドは通常、nullバイトや不正なエンコーディングのファイルを生成するため、ファイルエクスプローラーまたはIDEを使用してPythonファイルを作成することをお勧めします。

__init__.py

次に、フォルダ内に__init__.pyファイルを作成します:

echo "from . import agent" > multi_tool_agent/__init__.py

これで__init__.pyは以下のようになります:

multi_tool_agent/__init__.py
from . import agent

agent.py

同じフォルダにagent.pyファイルを作成します:

touch multi_tool_agent/agent.py

agent.pyに以下のコードをコピー&ペーストします:

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

同じフォルダに.envファイルを作成します:

touch multi_tool_agent/.env

このファイルに関する詳細は、次のセクションモデルのセットアップで説明します。

Javaプロジェクトは通常、以下のプロジェクト構造を持ちます:

project_folder/
├── pom.xml (または build.gradle)
├── src/
├── └── main/
│       └── java/
│           └── agents/
│               └── multitool/
└── test/

MultiToolAgent.javaの作成

src/main/java/agents/multitool/ディレクトリ内のagents.multitoolパッケージにMultiToolAgent.javaソースファイルを作成します。

MultiToolAgent.javaに以下のコードをコピー&ペーストします:

agents/multitool/MultiToolAgent.java
package agents.multitool;

import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Scanner;

public class MultiToolAgent {

    private static String USER_ID = "student";
    private static String NAME = "multi_tool_agent";

    // The run your agent with Dev UI, the ROOT_AGENT should be a global public static variable.
    public static BaseAgent ROOT_AGENT = initAgent();

    public static BaseAgent initAgent() {
        return LlmAgent.builder()
            .name(NAME)
            .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(
                FunctionTool.create(MultiToolAgent.class, "getCurrentTime"),
                FunctionTool.create(MultiToolAgent.class, "getWeather"))
            .build();
    }

    public static Map<String, String> getCurrentTime(
        @Schema(description = "The name of the city for which to retrieve the current time")
        String city) {
        String normalizedCity =
            Normalizer.normalize(city, Normalizer.Form.NFD)
                .trim()
                .toLowerCase()
                .replaceAll("(\\p{IsM}+|\\p{IsP}+)", "")
                .replaceAll("\\s+", "_");

        return ZoneId.getAvailableZoneIds().stream()
            .filter(zid -> zid.toLowerCase().endsWith("/" + normalizedCity))
            .findFirst()
            .map(
                zid ->
                    Map.of(
                        "status",
                        "success",
                        "report",
                        "The current time in "
                            + city
                            + " is "
                            + ZonedDateTime.now(ZoneId.of(zid))
                            .format(DateTimeFormatter.ofPattern("HH:mm"))
                            + "."))
            .orElse(
                Map.of(
                    "status",
                    "error",
                    "report",
                    "Sorry, I don't have timezone information for " + city + "."));
    }

    public static Map<String, String> getWeather(
        @Schema(description = "The name of the city for which to retrieve the weather report")
        String city) {
        if (city.toLowerCase().equals("new york")) {
            return Map.of(
                "status",
                "success",
                "report",
                "The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees"
                    + " Fahrenheit).");

        } else {
            return Map.of(
                "status", "error", "report", "Weather information for " + city + " is not available.");
        }
    }

    public static void main(String[] args) throws Exception {
        InMemoryRunner runner = new InMemoryRunner(ROOT_AGENT);

        Session session =
            runner
                .sessionService()
                .createSession(NAME, USER_ID)
                .blockingGet();

        try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) {
            while (true) {
                System.out.print("\nYou > ");
                String userInput = scanner.nextLine();

                if ("quit".equalsIgnoreCase(userInput)) {
                    break;
                }

                Content userMsg = Content.fromParts(Part.fromText(userInput));
                Flowable<Event> events = runner.runAsync(USER_ID, session.id(), userMsg);

                System.out.print("\nAgent > ");
                events.blockingForEach(event -> System.out.println(event.stringifyContent()));
            }
        }
    }
}

intro_components.png

3. モデルのセットアップ

エージェントがユーザーのリクエストを理解し、応答を生成する能力は、大規模言語モデル(LLM)によって支えられています。エージェントは、この外部のLLMサービスに対して安全な呼び出しを行う必要があり、そのためには認証情報が必要です。有効な認証がなければ、LLMサービスはエージェントのリクエストを拒否し、エージェントは機能できなくなります。

  1. Google AI StudioからAPIキーを取得します。
  2. Pythonを使用する場合、(multi_tool_agent/内にある).envファイルを開き、以下のコードをコピー&ペーストします。

    multi_tool_agent/.env
    GOOGLE_GENAI_USE_VERTEXAI=FALSE
    GOOGLE_API_KEY=ここに実際のAPIキーを貼り付けてください
    

    Javaを使用する場合、環境変数を定義します:

    terminal
    export GOOGLE_GENAI_USE_VERTEXAI=FALSE
    export GOOGLE_API_KEY=ここに実際のAPIキーを貼り付けてください
    
  3. ここに実際のAPIキーを貼り付けてくださいを実際のAPIキーに置き換えます。

  1. 既存のGoogle Cloudアカウントとプロジェクトが必要です。
  2. Pythonを使用する場合、(multi_tool_agent/内にある).envファイルを開きます。以下のコードをコピー&ペーストし、プロジェクトIDとロケーションを更新します。

    multi_tool_agent/.env
    GOOGLE_GENAI_USE_VERTEXAI=TRUE
    GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
    GOOGLE_CLOUD_LOCATION=LOCATION
    

    Javaを使用する場合、環境変数を定義します:

    terminal
    export GOOGLE_GENAI_USE_VERTEXAI=TRUE
    export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
    export GOOGLE_CLOUD_LOCATION=LOCATION
    

4. エージェントの実行

ターミナルを使用して、エージェントプロジェクトの親ディレクトリに移動します(例:cd ..を使用):

parent_folder/      <-- このディレクトリに移動
    multi_tool_agent/
        __init__.py
        agent.py
        .env

エージェントと対話するには複数の方法があります:

以下のコマンドを実行して開発UIを起動します。

adk web

Windowsユーザーへの注意

_make_subprocess_transport NotImplementedErrorが発生した場合、代わりにadk web --no-reloadの使用を検討してください。

ステップ1: 提供されたURL(通常はhttp://localhost:8000またはhttp://127.0.0.1:8000)をブラウザで直接開きます。

ステップ2: UIの左上隅にあるドロップダウンで、エージェントを選択できます。「multi_tool_agent」を選択します。

トラブルシューティング

ドロップダウンメニューに「multi_tool_agent」が表示されない場合は、adk webをエージェントフォルダの親フォルダ(つまり、multi_tool_agentの親フォルダ)で実行していることを確認してください。

ステップ3: これで、テキストボックスを使用してエージェントとチャットできます:

adk-web-dev-ui-chat.png

ステップ4: 左側のEventsタブを使用すると、アクションをクリックすることで、個々の関数呼び出し、応答、モデルの応答を検査できます:

adk-web-dev-ui-function-call.png

Eventsタブで、Traceボタンをクリックすると、各関数呼び出しのレイテンシを示す各イベントのトレースログを確認できます:

adk-web-dev-ui-trace.png

ステップ5: マイクを有効にしてエージェントと話すこともできます:

音声/ビデオストリーミングのモデルサポート

ADKで音声/ビデオストリーミングを使用するには、Live APIをサポートするGeminiモデルを使用する必要があります。Gemini Live APIをサポートするモデルIDは、ドキュメントで確認できます:

その後、以前に作成したagent.pyファイルのroot_agent内のmodel文字列を置き換えることができます(セクションへジャンプ)。コードは次のようになります:

root_agent = Agent(
    name="weather_time_agent",
    model="モデルIDに置き換えてください", #例: gemini-2.0-flash-live-001
    ...

adk-web-dev-ui-audio.png

以下のコマンドを実行して、天気エージェントとチャットします。

adk run multi_tool_agent

adk-run.png

終了するには、Cmd/Ctrl+Cを使用します。

adk api_serverを使用すると、単一のコマンドでローカルのFastAPIサーバーを作成でき、エージェントをデプロイする前にローカルのcURLリクエストをテストできます。

adk-api-server.png

adk api_serverを使用してテストする方法については、テストに関するドキュメントを参照してください。

ターミナルを使用して、エージェントプロジェクトの親ディレクトリに移動します(例:cd ..を使用):

project_folder/                <-- このディレクトリに移動
├── pom.xml (または build.gradle)
├── src/
├── └── main/
│       └── java/
│           └── agents/
│               └── multitool/
│                   └── MultiToolAgent.java
└── test/

ターミナルから以下のコマンドを実行して開発UIを起動します。

開発UIサーバーのメインクラス名を変更しないでください。

terminal
mvn exec:java \
    -Dexec.mainClass="com.google.adk.web.AdkWebServer" \
    -Dexec.args="--adk.agents.source-dir=src/main/java" \
    -Dexec.classpathScope="compile"

ステップ1: 提供されたURL(通常はhttp://localhost:8080またはhttp://127.0.0.1:8080)をブラウザで直接開きます。

ステップ2: UIの左上隅にあるドロップダウンで、エージェントを選択できます。「multi_tool_agent」を選択します。

トラブルシューティング

ドロップダウンメニューに「multi_tool_agent」が表示されない場合は、Javaソースコードがある場所(通常はsrc/main/java)でmvnコマンドを実行していることを確認してください。

ステップ3: これで、テキストボックスを使用してエージェントとチャットできます:

adk-web-dev-ui-chat.png

ステップ4: アクションをクリックすることで、個々の関数呼び出し、応答、モデルの応答を検査することもできます:

adk-web-dev-ui-function-call.png

Mavenを使用する場合、以下のコマンドでJavaクラスのmain()メソッドを実行します:

terminal
mvn compile exec:java -Dexec.mainClass="agents.multitool.MultiToolAgent"

Gradleを使用する場合、build.gradleまたはbuild.gradle.ktsビルドファイルには、pluginsセクションに以下のJavaプラグインが必要です:

plugins {
    id("java")
    // 他のプラグイン
}

次に、ビルドファイルのトップレベルで、エージェントのmain()メソッドを実行するための新しいタスクを作成します:

task runAgent(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    mainClass = "agents.multitool.MultiToolAgent"
}

最後に、コマンドラインで以下のコマンドを実行します:

gradle runAgent

📝 試してみるプロンプトの例

  • What is the weather in New York?
  • What is the time in New York?
  • What is the weather in Paris?
  • What is the time in Paris?

🎉 おめでとうございます!

ADKを使用して初めてのエージェントを作成し、対話することに成功しました!


🛣️ 次のステップ

  • チュートリアルに進む: エージェントにメモリ、セッション、状態を追加する方法を学びます: チュートリアル
  • 高度な設定を掘り下げる: プロジェクト構造、設定、およびその他のインターフェースに関する詳細については、セットアップセクションを参照してください。
  • コアコンセプトを理解する: エージェントの概念について学びます。