クイックスタート¶
このクイックスタートでは、Agent Development Kit (ADK) のインストール、複数のツールを持つ基本的なエージェントのセットアップ、そしてターミナルまたは対話型のブラウザベース開発UIでローカルに実行する方法を説明します。
このクイックスタートは、Python 3.9以上またはJava 17以上とターミナルアクセスが可能なローカルIDE(VS Code、PyCharm、IntelliJ IDEAなど)を前提としています。この方法は、アプリケーションを完全にあなたのマシン上で実行し、内部開発に推奨されます。
1. 環境のセットアップとADKのインストール¶
2. エージェントプロジェクトの作成¶
プロジェクト構造¶
以下のプロジェクト構造を作成する必要があります:
multi_tool_agent
フォルダを作成します:
Windowsユーザーへの注意
次のいくつかのステップでWindows上でADKを使用する場合、mkdir
やecho
のようなコマンドは通常、nullバイトや不正なエンコーディングのファイルを生成するため、ファイルエクスプローラーまたはIDEを使用してPythonファイルを作成することをお勧めします。
__init__.py
¶
次に、フォルダ内に__init__.py
ファイルを作成します:
これで__init__.py
は以下のようになります:
agent.py
¶
同じフォルダにagent.py
ファイルを作成します:
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
ファイルを作成します:
このファイルに関する詳細は、次のセクションモデルのセットアップで説明します。
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
に以下のコードをコピー&ペーストします:
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()));
}
}
}
}
3. モデルのセットアップ¶
エージェントがユーザーのリクエストを理解し、応答を生成する能力は、大規模言語モデル(LLM)によって支えられています。エージェントは、この外部のLLMサービスに対して安全な呼び出しを行う必要があり、そのためには認証情報が必要です。有効な認証がなければ、LLMサービスはエージェントのリクエストを拒否し、エージェントは機能できなくなります。
- Google AI StudioからAPIキーを取得します。
-
Pythonを使用する場合、(
multi_tool_agent/
内にある).env
ファイルを開き、以下のコードをコピー&ペーストします。Javaを使用する場合、環境変数を定義します:
-
ここに実際のAPIキーを貼り付けてください
を実際のAPIキー
に置き換えます。
- 既存のGoogle Cloudアカウントとプロジェクトが必要です。
- Google Cloudプロジェクトのセットアップ
- gcloud CLIのセットアップ
- ターミナルから
gcloud auth login
を実行してGoogle Cloudに認証します。 - Vertex AI APIを有効にする。
-
Pythonを使用する場合、(
multi_tool_agent/
内にある).env
ファイルを開きます。以下のコードをコピー&ペーストし、プロジェクトIDとロケーションを更新します。multi_tool_agent/.envGOOGLE_GENAI_USE_VERTEXAI=TRUE GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID GOOGLE_CLOUD_LOCATION=LOCATION
Javaを使用する場合、環境変数を定義します:
4. エージェントの実行¶
ターミナルを使用して、エージェントプロジェクトの親ディレクトリに移動します(例:cd ..
を使用):
エージェントと対話するには複数の方法があります:
以下のコマンドを実行して開発UIを起動します。
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: これで、テキストボックスを使用してエージェントとチャットできます:
ステップ4: 左側のEvents
タブを使用すると、アクションをクリックすることで、個々の関数呼び出し、応答、モデルの応答を検査できます:
Events
タブで、Trace
ボタンをクリックすると、各関数呼び出しのレイテンシを示す各イベントのトレースログを確認できます:
ステップ5: マイクを有効にしてエージェントと話すこともできます:
音声/ビデオストリーミングのモデルサポート
ADKで音声/ビデオストリーミングを使用するには、Live APIをサポートするGeminiモデルを使用する必要があります。Gemini Live APIをサポートするモデルIDは、ドキュメントで確認できます:
その後、以前に作成したagent.py
ファイルのroot_agent
内のmodel
文字列を置き換えることができます(セクションへジャンプ)。コードは次のようになります:
adk api_server
を使用すると、単一のコマンドでローカルのFastAPIサーバーを作成でき、エージェントをデプロイする前にローカルのcURLリクエストをテストできます。
adk api_server
を使用してテストする方法については、テストに関するドキュメントを参照してください。
ターミナルを使用して、エージェントプロジェクトの親ディレクトリに移動します(例:cd ..
を使用):
project_folder/ <-- このディレクトリに移動
├── pom.xml (または build.gradle)
├── src/
├── └── main/
│ └── java/
│ └── agents/
│ └── multitool/
│ └── MultiToolAgent.java
└── test/
ターミナルから以下のコマンドを実行して開発UIを起動します。
開発UIサーバーのメインクラス名を変更しないでください。
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: これで、テキストボックスを使用してエージェントとチャットできます:
ステップ4: アクションをクリックすることで、個々の関数呼び出し、応答、モデルの応答を検査することもできます:
Mavenを使用する場合、以下のコマンドでJavaクラスのmain()
メソッドを実行します:
📝 試してみるプロンプトの例¶
- 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を使用して初めてのエージェントを作成し、対話することに成功しました!