Skip to content

ADK 的 Java 快速入门

本指南展示了如何开始使用 Java Agent Development Kit (ADK)。开始之前,请确保你已安装了以下软件:

  • Java 17 或更高版本
  • Maven 3.9 或更高版本

Create an agent project

创建一个包含以下文件和目录结构的智能体项目:

my_agent/
    src/main/java/com/example/agent/
                        HelloTimeAgent.java # 主智能体代码
                        AgentCliRunner.java # 命令行界面
    pom.xml                                 # 项目配置
    .env                                    # API 密钥或项目 ID
使用命令行创建此项目结构
mkdir my_agent\src\main\java\com\example\agent
type nul > my_agent\src\main\java\com\example\agent\HelloTimeAgent.java
type nul > my_agent\src\main\java\com\example\agent\AgentCliRunner.java
type nul > my_agent\pom.xml
type nul > my_agent\.env
mkdir -p my_agent/src/main/java/com/example/agent && \
    touch my_agent/src/main/java/com/example/agent/HelloTimeAgent.java \
    touch my_agent/src/main/java/com/example/agent/AgentCliRunner.java \
    touch my_agent/pom.xml my_agent/.env

Define the agent code

为基本智能体创建代码,包括 ADK 函数工具的简单实现,名为 getCurrentTime()。 将以下代码添加到项目目录中的 HelloTimeAgent.java 文件中:

my_agent/src/main/java/com/example/agent/HelloTimeAgent.java
package com.example.agent;

import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;

import java.util.Map;

public class HelloTimeAgent {

    public static BaseAgent ROOT_AGENT = initAgent();

    private static BaseAgent initAgent() {
        return LlmAgent.builder()
            .name("hello-time-agent")
            .description("Tells the current time in a specified city")
            .instruction("""
                You are a helpful assistant that tells the current time in a city.                
                Use the 'getCurrentTime' tool for this purpose.
                """)
            .model("gemini-2.5-flash")
            .tools(FunctionTool.create(HelloTimeAgent.class, "getCurrentTime"))
            .build();
    }

    /** Mock tool implementation */
    @Schema(description = "Get the current time for a given city")
    public static Map<String, String> getCurrentTime(
        @Schema(name = "city", description = "Name of the city to get the time for") String city) {
        return Map.of(
            "city", city,
            "forecast", "The time is 10:30am."
        );
    }
}

Configure project and dependencies

ADK 智能体项目需要在你的 pom.xml 项目文件中添加此依赖项:

my_agent/pom.xml (partial)
<dependencies>
    <dependency>
        <groupId>com.google.adk</groupId>
        <artifactId>adk-core</artifactId>
        <version>0.3.0</version>
    </dependency>
</dependencies>

更新 pom.xml 项目文件,将此依赖项和 额外设置添加到以下配置代码中:

项目的完整 pom.xml 配置

以下代码显示了此项目的完整 pom.xml 配置:

my_agent/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example.agent</groupId>
    <artifactId>adk-agents</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- Specify the version of Java you'll be using -->
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- The ADK core dependency -->
        <dependency>
            <groupId>com.google.adk</groupId>
            <artifactId>google-adk</artifactId>
            <version>0.3.0</version>
        </dependency>
        <!-- The ADK dev web UI to debug your agent -->
        <dependency>
            <groupId>com.google.adk</groupId>
            <artifactId>google-adk-dev</artifactId>
            <version>0.3.0</version>
        </dependency>
    </dependencies>

</project>

Set your API key

此项目使用需要 API 密钥的 Gemini API。如果你 还没有 Gemini API 密钥,请在 Google AI Studio 上的 API 密钥 页面创建一个。

在终端窗口中,将你的 API 密钥写入项目的 .env 文件以设置环境变量:

Update: my_agent/.env
echo 'export GOOGLE_API_KEY="YOUR_API_KEY"' > .env
Update: my_agent/.env
echo 'set GOOGLE_API_KEY="YOUR_API_KEY"' > env.bat
使用 ADK 的其他 AI 模型

ADK 支持使用许多生成式 AI 模型。有关在 ADK 智能体中配置其他模型的更多信息,请参阅 模型与身份验证

Create an agent command-line interface

创建一个 AgentCliRunner.java 类,以便你能够从命令行运行和与 HelloTimeAgent 交互。此代码展示了如何创建一个 RunConfig 对象来运行智能体和一个 Session 对象来与 运行中的智能体交互。

my_agent/src/main/java/com/example/agent/AgentCliRunner.java
package com.example.agent;

import com.google.adk.agents.RunConfig;
import com.google.adk.events.Event;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.util.Scanner;

import static java.nio.charset.StandardCharsets.UTF_8;

public class AgentCliRunner {

    public static void main(String[] args) {
        RunConfig runConfig = RunConfig.builder().build();
        InMemoryRunner runner = new InMemoryRunner(HelloTimeAgent.ROOT_AGENT);

        Session session = runner
                .sessionService()
                .createSession(runner.appName(), "user1234")
                .blockingGet();

        try (Scanner scanner = new Scanner(System.in, 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(session.userId(), session.id(), userMsg, runConfig);

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

Run your agent

你可以使用你定义的交互式命令行界面 AgentCliRunner 类或 ADK 提供的 ADK 网页用户界面 使用 AdkWebServer 类来运行你的 ADK 智能体。这两个选项都允许你测试和 与你的智能体交互。

Run with command-line interface

使用以下 Maven 命令通过命令行界面 AgentCliRunner 类 运行你的智能体:

# Remember to load keys and settings: source .env OR env.bat
mvn compile exec:java -Dexec.mainClass="com.example.agent.AgentCliRunner"

adk-run.png

Run with web interface

使用以下 Maven 命令通过 ADK 网页界面运行你的智能体:

# Remember to load keys and settings: source .env OR env.bat
mvn compile exec:java \
    -Dexec.mainClass="com.google.adk.web.AdkWebServer" \
    -Dexec.args="--adk.agents.source-dir=target --server.port=8000"

此命令启动一个带有所述智能体聊天界面的网页服务器。你可以在 (http://localhost:8000) 访问网页界面。在 右上角选择你的智能体并键入请求。

adk-web-dev-ui-chat.png

Next: Build your agent

现在你已经安装了 ADK 并运行了你的第一个智能体,尝试使用我们的构建指南 构建你自己的智能体: