跳转到内容

适用于 ADK 的 Java 快速入门指南

本指南将向您展示如何开始使用 Java 版的 Agent Development Kit(Agent 开发工具包)。在开始之前,请确保您已经安装了以下软件:

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

创建一个代理项目(Agent Project)。

创建一个代理项目(agent project),该项目包含以下文件和目录结构:

my_agent/
    src/main/java/com/example/agent/
                        HelloTimeAgent.java # main agent code
                        AgentCliRunner.java # command-line interface
    pom.xml                                 # project configuration
    .env                                    # API keys or project IDs
使用命令行创建这个项目结构。
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

定义代理代码(Agent Code)。

编写一个基本代理的代码,其中包括对 ADK(Audio Development Kit)的简单实现。 Function Tool被称为…… 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-flash-latest")
            .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."
        );
    }
}

注意:Gemini 3 的兼容性问题需要特别注意。

ADK Java v0.3.0 及更低版本与……不兼容。 Gemini 3 Pro 预览版 由于函数调用时的签名发生了变化,请使用 Gemini 2.5 或更低版本的型号。

配置项目及其依赖项。

一个 ADK 代理项目需要依赖这个组件(或库)。 pom.xml 项目文件:

my_agent/pom.xml (partial)
<dependencies>
    <dependency>
        <groupId>com.google.adk</groupId>
        <artifactId>google-adk</artifactId>
        <version>1.14.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>1.14.0</version>
        </dependency>
        <!-- The ADK dev web UI to debug your agent -->
        <dependency>
            <groupId>com.google.adk</groupId>
            <artifactId>google-adk-dev</artifactId>
            <version>1.14.0</version>
        </dependency>
    </dependencies>

</project>

请设置您的 API 密钥。

该项目使用了 Gemini API,因此需要一个 API 密钥。如果您还没有 Gemini API 密钥,请在 Google AI Studio 中创建一个密钥。 API 密钥 page.

在终端窗口中,输入您的 API 密钥。 .env 您的项目文件 用于设置环境变量:

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

ADK 支持使用许多生成式 AI 模型。有关在 ADK 代理中配置其他模型的更多信息,请参阅…… 模型与身份验证(Models & Authentication).

创建一个用于管理代理的命令行界面(Command-Line Interface, CLI)。

创建一个…… 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());
                    }
                });
            }
        }
    }
}

运行你的代理程序。

您可以使用交互式的命令行界面来运行您的 ADK 代理程序。 AgentCliRunner 你可以自定义的类,或者由 ADK 提供的 ADK Web 用户界面。 AdkWebServer 这两个选项都允许你测试并与你的代理程序进行交互。

通过命令行界面运行

通过命令行界面运行您的代理程序。 AgentCliRunner 使用以下 Maven 命令来创建一个类:

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

adk-run.png

通过 Web 界面运行该程序。

使用以下 Maven 命令,通过 ADK Web 界面运行您的代理程序:

# 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"

此命令会启动一个带有聊天界面的 Web 服务器,供您的代理使用。您可以通过以下地址访问该 Web 界面: http://localhost:8000在左上角选择您的代理,然后输入请求内容。

adk-web-dev-ui-chat.png

注意:ADK Web 仅适用于开发用途。

ADK Web 是 不适用于生产环境中的部署。您应该仅将 ADK Web 用于开发和调试目的。

下一步:构建你的代理程序(agent)。

既然您已经安装了 ADK 并让您的第一个代理程序成功运行了,现在可以尝试根据我们的构建指南来创建自己的代理程序了。