Getting Started with AgentScope-Java: Build Enterprise AI Agents in Minutes
This guide introduces AgentScope-Java, Alibaba's open‑source Java framework for building production‑grade AI agents, explains how it solves the lack of Java‑native agent tools, compares it with Spring AI Alibaba, walks through core concepts, installation, tool registration, multi‑agent orchestration, underlying architecture, distributed deployment, real‑world examples, and evaluates its strengths and limitations.
What is AgentScope-Java
AgentScope-Java is an open‑source Java framework for programming AI agents that run on large language models (LLM). It bundles the ReAct reasoning loop, tool calling, memory management, multi‑agent coordination and distributed deployment into a single library, allowing Java developers to build production‑grade agents without learning Python.
Difference from Spring AI Alibaba
Spring AI Alibaba focuses on AI capability integration (easy access to various LLM APIs) and is suitable for RAG or simple chatbots.
AgentScope-Java focuses on agent engineering (autonomous reasoning, tool calling, multi‑agent collaboration). The two can be used together: AgentScope provides the agent "brain" while Spring AI Alibaba supplies the "senses".
Core concepts
ReActAgent – lightweight reasoning core
ReActAgent implements the full ReAct (Reasoning → Acting) loop, suitable for lightweight, single‑turn conversations that do not require persistent state.
HarnessAgent – production‑grade entry
HarnessAgent builds on ReActAgent and adds engineering capabilities required for long‑running agents.
Workspace : unified storage for persona, knowledge, skills and memory.
Memory : cross‑session persistence with semantic retrieval.
Session : automatic dialogue state saving and seamless recovery.
Sub‑Agent orchestration : the main agent can delegate tasks to multiple sub‑agents.
Sandbox : tool execution runs in an isolated environment for safety.
Compaction : long conversations are automatically compressed to avoid context overflow.
The key distinction is that ReActAgent solves "how to run a single conversation", while HarnessAgent solves "how to run a stable, safe and scalable long‑running agent".
Run your first agent in 5 minutes
Prerequisites
java -version
# output should be 17 or higherAdd Maven dependencies
Core and model extensions are separated. Add the core harness dependency:
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-harness</artifactId>
<version>2.0.0</version>
</dependency>This pulls agentscope-core, which contains ReActAgent and HarnessAgent implementations.
Add a model extension, for example Alibaba DashScope:
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-extensions-model-dashscope</artifactId>
<version>2.0.0</version>
</dependency>Configure API key
export DASHSCOPE_API_KEY="sk-YourApiKey"For OpenAI‑compatible services use OPENAI_API_KEY instead.
Minimal hello‑world agent
package com.example;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.formatter.openai.OpenAIChatFormatter;
import io.agentscope.core.message.UserMessage;
import io.agentscope.core.model.GenerateOptions;
import io.agentscope.core.model.OpenAIChatModel;
import io.agentscope.core.tool.Toolkit;
import io.agentscope.harness.HarnessAgent;
import java.nio.file.Path;
public class FirstAgent {
public static void main(String[] args) {
// 1. Create model (example with DeepSeek)
String apiKey = System.getenv("DEEPSEEK_API_KEY");
OpenAIChatModel model = OpenAIChatModel.builder()
.apiKey(apiKey)
.modelName("deepseek-chat")
.baseUrl("https://api.deepseek.com")
.stream(true) // enable streaming
.enableThinking(true) // enable thinking mode
.formatter(new OpenAIChatFormatter())
.defaultOptions(GenerateOptions.builder()
.thinkingBudget(1024) // token budget for thinking
.build())
.build();
// 2. Build HarnessAgent
HarnessAgent agent = HarnessAgent.builder()
.name("Assistant")
.sysPrompt("You are a helpful AI assistant, answer concisely.")
.model(model)
.workspace(Path.of("./workspace"))
.build();
// 3. Send a message and get reply
UserMessage userMsg = new UserMessage("Hello, introduce yourself.");
String reply = agent.call(userMsg, RuntimeContext.empty())
.block()
.getTextContent();
System.out.println(reply);
}
}Steps:
Step 1 : create an OpenAIChatModel with API key, endpoint, streaming flag and thinking mode.
Step 2 : build a HarnessAgent specifying name, system prompt, model and workspace directory.
Step 3 : construct a UserMessage, invoke agent.call() and print the response.
Tool system – giving agents "hands and feet"
Agents can call any Java method annotated with @Tool. The annotation registers the method as a callable tool.
Define a tool
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
public class WeatherTools {
@Tool(name = "get_weather", description = "Get current weather for a city")
public String getWeather(@ToolParam(name = "city", description = "City name, e.g., 'Beijing'") String city) {
// Real weather API call could go here
return city + " today is sunny, 25°C";
}
@Tool(name = "calculate", description = "Execute a math expression")
public double calculate(@ToolParam(name = "expression", description = "Math expression") String expression) {
// Integration with an expression engine could go here
return 42.0;
}
}Key points: @Tool name is the unique identifier used by the agent. @Tool description guides the LLM on when to invoke the tool. @ToolParam annotates method parameters with human‑readable descriptions.
Register the tool
Toolkit toolkit = new Toolkit();
toolkit.registerTool(new WeatherTools());
HarnessAgent agent = HarnessAgent.builder()
.name("Assistant")
.sysPrompt("You are a tool‑enabled assistant.")
.model(model)
.toolkit(toolkit)
.workspace(Path.of("./workspace"))
.build();Using tools in an agent
UserMessage userMsg = new UserMessage("What’s the weather in Beijing?");
String reply = agent.call(userMsg, RuntimeContext.empty())
.block()
.getTextContent();
System.out.println(reply); // Expected output: "Beijing today is sunny, 25°C"The agent decides autonomously whether to call get_weather based on the description.
Multi‑agent collaboration
AgentScope 2.0 introduces an orchestrator + workers model where a main agent delegates tasks to sub‑agents defined via markdown files.
Core pattern
The main agent (host) receives the user request, decomposes it, spawns appropriate sub‑agents, and aggregates results.
Define sub‑agents (file‑driven)
# workspace/subagents/weather.md
id: weather
description: |
Get city weather. Input: city name + date. Output: temperature range, rain?, umbrella?
sysPrompt: |
You are a weather assistant. When given a city and date, return:
- temperature (high/low)
- rain status
- umbrella recommendation
Strictly three lines, ≤60 characters. # workspace/subagents/flight.md
id: flight
description: |
Mock flight lookup. Input: departure city + arrival city + date.
sysPrompt: |
You are a flight assistant. Provide a mock flight number and times.The description acts as a routing rule; the main agent spawns the sub‑agent when the description matches the user intent.
Java‑side enhancement
SubagentDeclaration weather = SubagentDeclaration.builder()
.name("weather")
.description("Get city weather; input city+date, output temperature and umbrella")
.inlineAgentsBody("You are a weather assistant that calls real tools.")
.build();
HarnessAgent agent = HarnessAgent.builder()
.name("TravelAssistant")
.model(model)
.toolkit(toolkit)
.subagent(weather) // Java‑side enhancement
.workspace(Path.of("./workspace"))
.build();The main agent decides at runtime which sub‑agents to invoke and in which order, without hard‑coded pipelines.
Underlying architecture
Layered design
Model adaptation layer : communicates with various LLM providers (OpenAI, DashScope, Claude, Gemini).
ReAct reasoning layer : implements the ReAct loop (think → act → observe → think again).
Harness engineering layer : adds workspace, memory, session, sub‑agent orchestration, sandbox, etc.
Application layer : business code.
ReAct loop execution flow
When a user message arrives, the ReAct loop proceeds through reasoning, tool execution, observation and further reasoning. HarnessAgent injects hooks for workspace loading, memory read/write and session persistence.
Distributed deployment
In single‑node development the state lives in the local workspace directory. For production, switch the storage backend to Redis, MySQL, PostgreSQL, etc.; the same code runs unchanged, enabling horizontal scaling.
Real‑world case: Travel Assistant (weather + flight + attraction)
travel-assistant/
├── pom.xml
└── workspace/
├── MEMORY.md
├── subagents/
│ ├── weather.md
│ ├── flight.md
│ └── attraction.md
└── state/
└── session-*.json # generated by JsonFileAgentStateStoreEach sub‑agent markdown defines its id, description and sysPrompt. The main agent decides which sub‑agents to spawn based on user intent, e.g., "I’m flying from Beijing to Hangzhou tomorrow, will it rain at West Lake?".
Java code can augment the weather sub‑agent with a real weather API tool as shown earlier.
MCP (Model Context Protocol) integration
MCP is an open protocol (released by Anthropic in 2024) that lets LLM‑driven applications discover and invoke external tools uniformly.
Declare an MCP server (JSON)
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_PERSONAL_ACCESS_TOKEN": "${env:GITHUB_TOKEN}"}
}
}
}When the harness starts, it scans this file, launches the server, and automatically registers all exposed tools (e.g., create_issue, list_repos).
Supported transport protocols
stdio : local process (most common).
sse : remote HTTP Server‑Sent Events.
ws : bidirectional WebSocket.
Example of an SSE‑based knowledge‑base server:
{
"mcpServers": {
"remote-knowledge": {
"url": "https://mcp.example.com/sse",
"headers": {"Authorization": "Bearer ${env:MCP_TOKEN}"}
}
}
}Java‑side configuration (optional)
ToolsConfig cfg = new ToolsConfig();
Map<String, McpServerConfig> servers = new LinkedHashMap<>();
McpServerConfig github = new McpServerConfig();
github.setTransport("stdio");
github.setCommand("npx");
github.setArgs(List.of("-y", "@modelcontextprotocol/server-github"));
github.setEnv(Map.of("GITHUB_PERSONAL_ACCESS_TOKEN", System.getenv("GITHUB_TOKEN")));
servers.put("github", github);
cfg.setMcpServers(servers);
// Pass cfg to HarnessAgent.builder().toolsConfig(cfg)This programmatic approach yields the same effect as the JSON file.
Pros and cons
Advantages
Seamless Java ecosystem integration : works with Spring Boot, Spring Cloud, Maven.
Dual‑agent architecture : ReActAgent for prototypes, HarnessAgent for production.
Rich tool system : @Tool annotation makes any Java method a callable tool.
Native multi‑agent collaboration : orchestrator + workers model.
Production‑grade engineering features : workspace, long‑term memory, session persistence, context compression, sandbox isolation.
Distributed deployment support : pluggable state stores (Redis, MySQL, PostgreSQL) and Kubernetes scaling.
Multi‑model support : OpenAI‑compatible, DashScope, Claude, Gemini.
MCP/A2A protocol support : easy integration with external tool ecosystems.
Disadvantages
Relatively new (released Dec 2025, GA July 2026); community smaller than Spring AI.
Learning curve for HarnessAgent’s engineering concepts (workspace, memory, sub‑agents).
Ecosystem not as extensive as Spring AI Alibaba.
Documentation partly in English; some deep topics lack Chinese translation.
Recommended scenarios
Intelligent customer service : strongly recommended – multi‑agent collaboration + RAG knowledge base.
Operations diagnostic agent : strongly recommended – autonomous reasoning, tool calling, log analysis.
Financial analysis agent : strongly recommended – structured output, multi‑step reasoning.
Code assistance agent : recommended – tool calling + sandboxed code execution.
Enterprise knowledge assistant : recommended – RAG + long‑term memory.
Simple chatbot : may be over‑engineered – Spring AI Alibaba suffices.
Existing Spring AI ecosystem : evaluate – both can be combined.
Conclusion
AgentScope‑Java answers the core question: How can Java developers build AI agents without learning Python? It provides a lightweight ReActAgent for rapid prototyping and a production‑ready HarnessAgent for enterprise deployments. The @Tool annotation makes tool definition as natural as writing ordinary Java methods, and the sub‑agent system enables clear, scalable multi‑agent orchestration. Combined with MCP support, the framework extends the agent’s reach to any external service.
Resources
GitHub: https://github.com/agentscope-ai/agentscope-java
Documentation: https://java.agentscope.io/
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.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
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.
