Run Your First Java AI Agent in 5 Minutes with AgentScope
This article walks Java developers through setting up AgentScope Java 2.0, explains the core ReActAgent and HarnessAgent classes, shows how to configure a DashScope model key, and provides a complete Maven project and code example that streams a typed‑out response from the AI agent.
1. What Is AgentScope Java and Why Java Developers Should Use It
AgentScope Java turns the task of writing an AI agent into a JVM‑based framework. It abstracts away HTTP calls, JSON parsing, multi‑turn state machines, and conversation history handling, exposing a Java‑flavored API such as ReActAgent.builder().
The comparison matrix highlights that, unlike manual model calls, AgentScope lets you invoke a model with a single line agent.call(msg), provides built‑in ReAct loops, automatic memory management, and simple model switching by editing a single string.
2. Two Core Classes: ReActAgent and HarnessAgent
ReActAgent : the core intelligent agent that implements the ReAct loop – Reason → Action → Observe – for both ordinary dialogue and tool usage.
HarnessAgent : sits on top of ReActAgent and adds engineering capabilities such as Workspace, long‑term memory, context compression, and sandbox isolation, targeting production‑grade agents.
Both share the same inference kernel; HarnessAgent injects extra functionality via a Hook mechanism. Day 1 uses only the lightweight ReActAgent, leaving Harness for later.
3. Prerequisites: JDK 17+ and a DashScope API Key
JDK 17 or newer is required.
Obtain a DashScope (Qwen‑Plus) API key from dashscope.aliyun.com, store it in the environment variable DASHSCOPE_API_KEY. The framework reads the key automatically.
To switch models, replace the string "dashscope:qwen-plus" with another provider:model pair such as "openai:gpt-5.5" , "anthropic:claude-sonnet-4-5" , "gemini:gemini-2.0-flash" , or "ollama:llama3" . No code changes are needed.
4. Create a Maven Project with a Single Dependency
Add the following dependency to pom.xml:
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope</artifactId>
<version>2.0.0-RC3</version>
</dependency>The agentscope artifact is an all‑in‑one package that bundles the core framework, DashScope SDK, and MCP. For a slimmer footprint you can use agentscope-core plus optional agentscope-harness as needed.
Version 2.0.0-RC3 is a release candidate; the API is stable for learning, but production use should wait for the GA release. Chinese developers may speed up Maven downloads by adding an Alibaba mirror to settings.xml .
5. Write the First Agent: Streaming Typing Effect
In a main method, create a ReActAgent, set its name, system prompt, model, and an empty toolkit, then stream events to the console:
import io.agentscope.core.ReActAgent;
import io.agentscope.core.event.TextBlockDeltaEvent;
import io.agentscope.core.message.UserMessage;
import io.agentscope.core.tool.Toolkit;
public class FirstAgent {
public static void main(String[] args) {
ReActAgent agent = ReActAgent.builder()
.name("Assistant")
.sysPrompt("你是一个友好、简洁的 AI 助手。")
.model("dashscope:qwen-plus")
.toolkit(new Toolkit())
.build();
System.out.print("Assistant: ");
agent.streamEvents(new UserMessage("用一句话介绍你自己,再讲个程序员冷笑话"))
.doOnNext(event -> {
if (event instanceof TextBlockDeltaEvent e) {
System.out.print(e.getDelta());
}
})
.blockLast();
System.out.println();
}
}Key observations:
The .model("dashscope:qwen-plus") string is a concise provider:model shortcut; the framework’s ModelRegistry reads the key from the environment.
All inputs to the agent are Message objects; UserMessage for user input, AssistantMessage for model replies, and ToolResultMessage for tool outputs. streamEvents(...) returns a Flux<Event> stream; each TextBlockDeltaEvent carries a text fragment, enabling a typewriter‑style output.
For a non‑streaming full response, use Msg resp = agent.call(msg).block(); resp.getTextContent();. The trade‑off between call and streamEvents is covered in Day 3.
6. Run the Agent
export DASHSCOPE_API_KEY=sk-你的key # set environment variable
mvn exec:java -Dexec.mainClass=FirstAgent # run from Maven or IDEThe console prints the assistant’s reply character by character, e.g.:
Assistant: 我是你的 AI 助手,有问题尽管问。冷笑话:为什么程序员分不清万圣节和圣诞节?因为 Oct 31 == Dec 25。The underlying flow is:
your code → agent.streamEvents(new UserMessage(...)) → ReActAgent (Reason → Act → Observe) → DashScopeChatModel (qwen‑plus) → DashScope API → streaming TextBlockDeltaEvent → consoleSince no tool is configured, the Act step is skipped and the agent answers in a single round. Day 4 will demonstrate multi‑turn reasoning with tools.
7. Day 1 Summary
AgentScope Java is a JVM‑based agent framework (JDK 17+). ReActAgent provides the core ReAct loop. HarnessAgent adds production‑grade engineering features.
Model selection uses a simple provider:model string that reads the API key automatically.
Messages are typed as UserMessage, AssistantMessage, or ToolResultMessage. streamEvents + TextBlockDeltaEvent enables real‑time incremental output.
8. Next Episode Preview
Day 2 will cover the five building blocks of AgentScope: Message (unified message structure), Agent, Model, Memory, and Tool, explaining their roles and how they fit together.
9. Related Links
AgentScope Java documentation, quick‑start guide, GitHub repository, and the DashScope open platform are listed for further reference.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tech Ocean
Focused on AI programming, sharing ready-to-use development efficiency solutions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
