Skip to content

Build a streaming agent with Java

使用 Java 构建流式传输智能体

This quickstart guide will walk you through the process of creating a basic agent and leveraging ADK Streaming with Java to facilitate low-latency, bidirectional voice interactions.

本快速入门指南将引导您完成创建基本智能体并使用 Java ADK 流式传输实现低延迟、双向语音交互的过程。

You'll begin by setting up your Java and Maven environment, structuring your project, and defining necessary dependencies. Following this, you'll create a simple ScienceTeacherAgent, test its text-based streaming capabilities using the Dev UI, and then progress to enabling live audio communication, transforming your agent into an interactive voice-driven application.

您将从设置 Java 和 Maven 环境、构建项目结构以及定义必要的依赖项开始。之后,您将创建一个简单的 ScienceTeacherAgent,使用 Dev UI 测试其基于文本的流式传输功能,然后继续启用实时音频通信,将您的智能体转换为交互式语音驱动的应用程序。

Create your first agent

创建您的第一个智能体

Prerequisites

先决条件

  • In this getting started guide, you will be programming in Java. Check if Java is installed on your machine. Ideally, you should be using Java 17 or more (you can check that by typing java -version)

在本入门指南中,您将使用 Java 进行编程。检查您的机器上是否安装了 Java。理想情况下,您应该使用 Java 17 或更高版本(您可以通过输入 java -version 来检查)

  • You'll also be using the Maven build tool for Java. So be sure to have Maven installed on your machine before going further (this is the case for Cloud Top or Cloud Shell, but not necessarily for your laptop).

您还将使用 Java 的 Maven 构建工具。因此,请确保在进行下一步之前在您的机器上安装了 Maven(这对于 Cloud Top 或 Cloud Shell 是成立的,但不一定适用于您的笔记本电脑)。

Prepare the project structure

准备项目结构

To get started with ADK Java, let's create a Maven project with the following directory structure:

要开始使用 ADK Java,让我们创建一个具有以下目录结构的 Maven 项目:

adk-agents/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── agents/
                └── ScienceTeacherAgent.java

Follow instructions in Installation page to add pom.xml for using the ADK package.

按照 安装 页面中的说明添加用于使用 ADK 包的 pom.xml

Note

Feel free to use whichever name you like for the root directory of your project (instead of adk-agents)

随意使用您喜欢的任何名称作为项目的根目录(而不是 adk-agents)

Running a compilation

运行编译

Let's see if Maven is happy with this build, by running a compilation (mvn compile command):

让我们通过运行编译(mvn compile 命令)来看看 Maven 是否对此构建感到满意:

$ mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< adk-agents:adk-agents >--------------------
[INFO] Building adk-agents 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ adk-demo ---
[INFO] skip non existing resourceDirectory /home/user/adk-demo/src/main/resources
[INFO]
[INFO] --- compiler:3.13.0:compile (default-compile) @ adk-demo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /home/user/adk-demo/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.234 s
[INFO] Finished at: 2025-01-19T10:00:00+00:00
[INFO] ------------------------------------------------------------------------

Great! If the build is successful, let's now create a simple agent.

太好了!如果构建成功,现在让我们创建一个简单的智能体。

Create a Science Teacher Agent

创建科学老师智能体

Let's create a simple agent that acts as a science teacher. It will be able to answer questions about science topics using the Gemini model.

让我们创建一个扮演科学老师的简单智能体。它将能够使用 Gemini 模型回答有关科学主题的问题。

Add the following code to ScienceTeacherAgent.java:

将以下代码添加到 ScienceTeacherAgent.java:

package agents;

import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.Runner;
import com.google.adk.models.Gemini;
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.sessions.Session;

/**
 * A science teacher agent that can answer questions about science.
 * 一个能够回答科学问题的科学老师智能体。
 */
public class ScienceTeacherAgent {

    public static LlmAgent createAgent() {
        // Create a Gemini model instance
        // 创建 Gemini 模型实例
        Gemini model = new Gemini("gemini-2.5-flash");

        // Create the science teacher agent
        // 创建科学老师智能体
        return LlmAgent.builder()
            .name("science_teacher")
            .model(model)
            .instruction(
                "You are a helpful science teacher. " +
                "Explain scientific concepts in a clear, " +
                "easy-to-understand way. Use simple language " +
                "and examples when possible."
            )
            .build();
    }

    public static void main(String[] args) {
        // Create the agent
        // 创建智能体
        LlmAgent agent = createAgent();

        // Create session service
        // 创建会话服务
        InMemorySessionService sessionService = new InMemorySessionService();

        // Create a session
        // 创建会话
        Session session = sessionService.createSession(
            "user_001",
            "session_001"
        );

        // Create a runner
        // 创建运行器
        Runner runner = Runner.builder()
            .agent(agent)
            .sessionService(sessionService)
            .build();

        System.out.println("Science Teacher Agent created successfully!");
    }
}

Compile the agent

编译智能体

Compile the agent again to make sure everything is working:

再次编译智能体以确保一切正常:

$ mvn compile
[INFO] BUILD SUCCESS

Test the Agent with Dev UI

使用 Dev UI 测试智能体

Start the Dev UI

启动 Dev UI

ADK Java provides a Dev UI for testing your agent. Start it with:

ADK Java 提供了一个用于测试智能体的 Dev UI。使用以下命令启动它:

java -cp target/classes:$(mvn dependency:build-classpath -Dmdep.outputFile=/dev/stdout -q) \
  agents.ScienceTeacherAgent

Or if you're using Maven exec plugin:

或者如果您使用的是 Maven exec 插件:

mvn exec:java -Dexec.mainClass="agents.ScienceTeacherAgent"

Test with Dev UI

使用 Dev UI 测试

Open your browser and navigate to http://localhost:8080. You should see the Dev UI where you can interact with your agent.

打开浏览器并导航到 http://localhost:8080。您应该看到 Dev UI,可以在其中与智能体交互。

Try asking the agent some science questions:

尝试问智能体一些科学问题:

  • "What is photosynthesis?" (什么是光合作用?)
  • "How do stars form?" (恒星是如何形成的?)
  • "What is quantum mechanics?" (什么是量子力学?)

Enable Streaming Capabilities

启用流式传输功能

Now, let's enable streaming to see real-time responses from the agent.

现在,让我们启用流式传输以查看来自智能体的实时响应。

Update the Agent for Streaming

更新智能体以支持流式传输

Modify the ScienceTeacherAgent.java to add a streaming method:

修改 ScienceTeacherAgent.java 以添加流式传输方法:

package agents;

import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.Runner;
import com.google.adk.models.Gemini;
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.sessions.Session;
import com.google.genai.types.LiveRequestQueue;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Subscriber;

/**
 * A science teacher agent with streaming capabilities.
 * 具有流式传输功能的科学老师智能体。
 */
public class ScienceTeacherAgent {

    public static LlmAgent createAgent() {
        Gemini model = new Gemini("gemini-2.5-flash");

        return LlmAgent.builder()
            .name("science_teacher")
            .model(model)
            .instruction(
                "You are a helpful science teacher. " +
                "Explain scientific concepts in a clear, " +
                "easy-to-understand way. Use simple language " +
                "and examples when possible."
            )
            .build();
    }

    /**
     * Run the agent with streaming.
     * 以流式传输方式运行智能体。
     */
    public static void runWithStreaming(String userMessage) {
        LlmAgent agent = createAgent();
        InMemorySessionService sessionService = new InMemorySessionService();
        Session session = sessionService.createSession("user_001", "session_001");

        // Create a live request queue
        // 创建实时请求队列
        LiveRequestQueue liveRequestQueue = new LiveRequestQueue();

        // Create a runner
        // 创建运行器
        Runner runner = Runner.builder()
            .agent(agent)
            .sessionService(sessionService)
            .liveRequestQueue(liveRequestQueue)
            .build();

        // Run live
        // 实时运行
        Flowable<Event> eventStream = runner.runLive(session);

        // Subscribe to the stream
        // 订阅流
        eventStream.subscribe(new Subscriber<Event>() {
            @Override
            public void onSubscribe(Subscription s) {
                s.request(Long.MAX_VALUE);
            }

            @Override
            public void onNext(Event event) {
                if (event.getDelta() != null) {
                    System.out.print(event.getDelta().getText());
                }
            }

            @Override
            public void onError(Throwable t) {
                System.err.println("Error: " + t.getMessage());
            }

            @Override
            public void onComplete() {
                System.out.println("\nStream completed.");
            }
        });
    }

    public static void main(String[] args) {
        // Test with streaming
        // 使用流式传输测试
        runWithStreaming("What is gravity?");
    }
}

Test Streaming

测试流式传输

Compile and run the updated agent:

编译并运行更新后的智能体:

mvn compile exec:java -Dexec.mainClass="agents.ScienceTeacherAgent"

You should see the response streaming in real-time, word by word.

您应该看到响应逐字实时流式传输。

Next Steps

下一步

Congratulations! You've successfully created a streaming agent with Java ADK. Here are some things you can explore next:

恭喜!您已成功使用 Java ADK 创建了流式传输智能体。接下来您可以探索以下内容: