Skip to content

快速開始

本快速開始將引導你安裝 Agent Development Kit (ADK)、設定一個包含多個工具(tools)的基本 agent,並在本機端以終端機或互動式瀏覽器開發 UI 執行。

本快速開始假設你已在本機 IDE(如 VS Code、PyCharm、IntelliJ IDEA 等)安裝 Python 3.9+ 或 Java 17+,並具備終端機存取權限。此方法會讓應用程式完全在你的機器上執行,建議用於內部開發。

1. 設定環境並安裝 ADK

Create & Activate Virtual Environment (Recommended):

# Create
python -m venv .venv
# Activate (each new terminal)
# macOS/Linux: source .venv/bin/activate
# Windows CMD: .venv\Scripts\activate.bat
# Windows PowerShell: .venv\Scripts\Activate.ps1

Install ADK:

pip install google-adk

To install ADK and setup the environment, proceed to the following steps.

2. 建立 Agent 專案

專案結構

You will need to create the following project structure:

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

Create the folder multi_tool_agent:

mkdir multi_tool_agent/

Note for Windows users

When using ADK on Windows for the next few steps, we recommend creating Python files using File Explorer or an IDE because the following commands (mkdir, echo) typically generate files with null bytes and/or incorrect encoding.

__init__.py

Now create an __init__.py file in the folder:

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

Your __init__.py should now look like this:

multi_tool_agent/__init__.py
from . import agent

agent.py

Create an agent.py file in the same folder:

touch multi_tool_agent/agent.py
type nul > multi_tool_agent/agent.py

Copy and paste the following code into 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

Create a .env file in the same folder:

touch multi_tool_agent/.env
type nul > multi_tool_agent\.env

More instructions about this file are described in the next section on Set up the model.

Java projects generally feature the following project structure:

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

Create MultiToolAgent.java

Create a MultiToolAgent.java source file in the agents.multitool package in the src/main/java/agents/multitool/ directory.

Copy and paste the following code into 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 final variable.
    public static final 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(name = "city",
                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(name = "city",
                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. 設定模型

你的 agent 能夠理解使用者請求並產生回應,是由大型語言模型 (LLM) 所驅動。你的 agent 需要安全地呼叫這個外部的 LLM 服務,而這需要驗證憑證。如果沒有有效的驗證,LLM 服務將會拒絕 agent 的請求,導致 agent 無法運作。

模型驗證指南

如需詳細的模型驗證教學,請參閱 Authentication guide。 這是確保你的 agent 能夠呼叫 LLM 服務的關鍵步驟。

  1. Google AI Studio 取得 API KEY。
  2. 使用 Python 時,請開啟 (multi_tool_agent/) 資料夾內的 .env 檔案, 並將下列程式碼複製貼上。

    multi_tool_agent/.env
    GOOGLE_GENAI_USE_VERTEXAI=FALSE
    GOOGLE_API_KEY=PASTE_YOUR_ACTUAL_API_KEY_HERE
    

    When using Java, define environment variables:

    terminal
    export GOOGLE_GENAI_USE_VERTEXAI=FALSE
    export GOOGLE_API_KEY=PASTE_YOUR_ACTUAL_API_KEY_HERE
    
  3. Replace PASTE_YOUR_ACTUAL_API_KEY_HERE with your actual API KEY.

  1. 建立一個 Google Cloud 專案,並啟用 Vertex AI API
  2. 設定 gcloud 命令列介面 (Command Line Interface)
  3. 在終端機執行 gcloud auth application-default login,以驗證 Google Cloud 身份。
  4. 若使用 Python,請開啟 (multi_tool_agent/) 資料夾中的 .env 檔案。複製並貼上下列程式碼,並更新專案 ID 及 Location。

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

    When using Java, define environment variables:

    terminal
    export GOOGLE_GENAI_USE_VERTEXAI=TRUE
    export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
    export GOOGLE_CLOUD_LOCATION=LOCATION
    
  1. 你可以註冊一個免費的 Google Cloud 專案,並使用符合資格的帳戶免費體驗 Gemini!
  2. 使用 Python 時,請開啟 (multi_tool_agent/) 資料夾內的 .env 檔案。複製並貼上下列程式碼,並更新你的專案 ID 與 Location。

    multi_tool_agent/.env
    GOOGLE_GENAI_USE_VERTEXAI=TRUE
    GOOGLE_API_KEY=PASTE_YOUR_ACTUAL_EXPRESS_MODE_API_KEY_HERE
    

    When using Java, define environment variables:

    terminal
    export GOOGLE_GENAI_USE_VERTEXAI=TRUE
    export GOOGLE_API_KEY=PASTE_YOUR_ACTUAL_EXPRESS_MODE_API_KEY_HERE
    

4. 執行你的 agent

Using the terminal, navigate to the parent directory of your agent project (e.g. using cd ..):

parent_folder/      <-- navigate to this directory
    multi_tool_agent/
        __init__.py
        agent.py
        .env

There are multiple ways to interact with your agent:

Authentication Setup for Vertex AI Users

If you selected "Gemini - Google Cloud Vertex AI" in the previous step, you must authenticate with Google Cloud before launching the dev UI.

Run this command and follow the prompts:

gcloud auth application-default login

Note: Skip this step if you're using "Gemini - Google AI Studio".

Run the following command to launch the dev UI.

adk web

Note for Windows users

When hitting the _make_subprocess_transport NotImplementedError, consider using adk web --no-reload instead.

Step 1: Open the URL provided (usually http://localhost:8000 or http://127.0.0.1:8000) directly in your browser.

Step 2. In the top-left corner of the UI, you can select your agent in the dropdown. Select "multi_tool_agent".

Troubleshooting

If you do not see "multi_tool_agent" in the dropdown menu, make sure you are running adk web in the parent folder of your agent folder (i.e. the parent folder of multi_tool_agent).

Step 3. Now you can chat with your agent using the textbox:

adk-web-dev-ui-chat.png

Step 4. By using the Events tab at the left, you can inspect individual function calls, responses and model responses by clicking on the actions:

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

On the Events tab, you can also click the Trace button to see the trace logs for each event that shows the latency of each function calls:

adk-web-dev-ui-trace.png

Step 5. You can also enable your microphone and talk to your agent:

Model support for voice/video streaming

In order to use voice/video streaming in ADK, you will need to use Gemini models that support the Live API. You can find the model ID(s) that supports the Gemini Live API in the documentation:

You can then replace the model string in root_agent in the agent.py file you created earlier (jump to section). Your code should look something like:

root_agent = Agent(
    name="weather_time_agent",
    model="replace-me-with-model-id", #e.g. gemini-2.0-flash-live-001
    ...

adk-web-dev-ui-audio.png

Tip

When using adk run you can inject prompts into the agent to start by piping text to the command like so:

"Please start by listing files" | adk run file_listing_agent

Run the following command, to chat with your Weather agent.

adk run multi_tool_agent

adk-run.png

To exit, use Cmd/Ctrl+C.

adk api_server enables you to create a local FastAPI server in a single command, enabling you to test local cURL requests before you deploy your agent.

adk-api-server.png

To learn how to use adk api_server for testing, refer to the documentation on testing.

Using the terminal, navigate to the parent directory of your agent project (e.g. using cd ..):

project_folder/                <-- navigate to this directory
├── pom.xml (or build.gradle)
├── src/
├── └── main/
│       └── java/
│           └── agents/
│               └── multitool/
│                   └── MultiToolAgent.java
└── test/

Run the following command from the terminal to launch the Dev UI.

DO NOT change the main class name of the Dev UI server.

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

Step 1: Open the URL provided (usually http://localhost:8080 or http://127.0.0.1:8080) directly in your browser.

Step 2. In the top-left corner of the UI, you can select your agent in the dropdown. Select "multi_tool_agent".

Troubleshooting

If you do not see "multi_tool_agent" in the dropdown menu, make sure you are running the mvn command at the location where your Java source code is located (usually src/main/java).

Step 3. Now you can chat with your agent using the textbox:

adk-web-dev-ui-chat.png

Step 4. You can also inspect individual function calls, responses and model responses by clicking on the actions:

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

With Maven, run the main() method of your Java class with the following command:

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

With Gradle, the build.gradle or build.gradle.kts build file should have the following Java plugin in its plugins section:

plugins {
    id('java')
    // other plugins
}

Then, elsewhere in the build file, at the top-level, create a new task to run the main() method of your agent:

tasks.register('runAgent', JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    mainClass = 'agents.multitool.MultiToolAgent'
}

Finally, on the command-line, run the following command:

gradle runAgent

📝 範例提示語(prompts)試試看

  • 紐約的天氣如何?
  • 紐約現在幾點?
  • 巴黎的天氣如何?
  • 巴黎現在幾點?

🎉 恭喜!

你已經成功使用 Agent Development Kit (ADK) 建立並與你的第一個 agent 互動!


🛣️ 下一步

  • 前往教學課程:學習如何為你的 agent 增加記憶體(memory)、session、state: tutorial
  • 深入進階設定: 探索 setup 章節,深入了解專案結構、設定方式及其他介面。
  • 理解核心概念: 進一步認識 agents concepts