Java 快速开始Java quick start
本页对应 agentscope-core 2.0.4 与 agentscope-extensions-model-openai 2.0.4。Java 版使用 Project Reactor:call 返回 Mono<Msg>,stream 返回 Flux<Event>,因此示例不依赖阻塞式 API。
1. Maven 依赖
<properties>
<agentscope.version>2.0.4</agentscope.version>
</properties>
<dependencies>
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-core</artifactId>
<version>${agentscope.version}</version>
</dependency>
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-extensions-model-openai</artifactId>
<version>${agentscope.version}</version>
</dependency>
</dependencies>
如果使用 Gradle:
dependencies {
implementation("io.agentscope:agentscope-core:2.0.4")
implementation("io.agentscope:agentscope-extensions-model-openai:2.0.4")
}
所有官方扩展的坐标都可以在 构件列表 中查到;模型供应商、RAG 存储、A2A、AG-UI、沙箱等都在独立构件中,按需引入。
2. 创建模型
供应商模型通过 Builder 构造:
import io.agentscope.extensions.model.openai.OpenAIChatModel;
OpenAIChatModel model = OpenAIChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.stream(true)
.build();
需要兼容端点时加 .baseUrl("https://your-endpoint/v1")。其他供应商使用对应扩展,例如 DashScopeChatModel、AnthropicChatModel、GeminiChatModel、OllamaChatModel。
3. 定义工具
工具是带注解的普通方法。Toolkit.registerTool(Object) 会扫描 @Tool 方法,@ToolParam 描述参数:
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import io.agentscope.core.tool.Toolkit;
public final class WeatherTools {
@Tool(name = "get_weather", description = "Return the current weather for a city.")
public String getWeather(
@ToolParam(name = "city", description = "The city name, for example Hangzhou")
String city) {
// Call a real weather API in production
return city + ": sunny, 24C";
}
}
Toolkit toolkit = new Toolkit();
toolkit.registerTool(new WeatherTools());
@Tool 还支持 readOnly、concurrencySafe、strict、externalTool、stateInjected 等属性。需要把一组工具动态启用/停用时,使用工具分组(createToolGroup、updateToolGroups)。
4. 构建智能体并调用
import io.agentscope.core.ReActAgent;
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.message.Msg;
ReActAgent agent = ReActAgent.builder()
.name("assistant")
.sysPrompt("You are a concise assistant. Use tools when needed.")
.model(model)
.toolkit(toolkit)
.maxIters(10)
.build();
RuntimeContext context = RuntimeContext.builder()
.sessionId("demo-session")
.userId("demo-user")
.build();
Msg reply = agent.call("What's the weather in Hangzhou?", context).block();
System.out.println(reply.getTextContent());
agent.close();
RuntimeContext 是单次调用的元数据:会话/用户标识、可选的 AgentState、工具执行上下文与属性包。它不会被持久化;跨调用保留的状态在 AgentState 中。
5. 流式事件
import io.agentscope.core.event.TextBlockDeltaEvent;
agent.streamEvents("Explain ReAct in two sentences.", context)
.doOnNext(event -> {
if (event instanceof TextBlockDeltaEvent delta) {
System.out.print(delta.getDelta());
}
})
.blockLast();
需要过滤事件类型时,用 StreamOptions.builder().eventTypes(...) 控制订阅范围。事件模型(思考、工具调用、工具结果、回复结束等)定义在 io.agentscope.core.event 包。
6. 结构化输出
把结果类传给 call,即可获得类型安全的输出:
public record WeatherReport(String city, double temperatureC, String condition) {}
Msg reply = agent.call(
"Report the weather in Hangzhou as structured data.",
WeatherReport.class,
context
).block();
WeatherReport report = reply.getStructuredData(WeatherReport.class);
实现方式与 Python 版一致:循环内注入结构化输出工具,模型必须调用它并给出符合 schema 的参数。getStructuredData 使用 Jackson 反序列化,因此结果类需要可被 Jackson 处理(record、POJO 或带注解的类)。
7. 状态持久化
Java 版通过 AgentStateStore 持久化会话状态。内置 JSON 文件存储适合本地开发:
import io.agentscope.core.state.JsonFileAgentStateStore;
JsonFileAgentStateStore store = new JsonFileAgentStateStore(Path.of("./agent-state"));
ReActAgent agent = ReActAgent.builder()
.name("assistant")
.sysPrompt("You are a helpful assistant.")
.model(model)
.stateStore(store)
.defaultSessionId("demo-session")
.build();
生产环境可使用 MysqlSession、RedisSession 或自行实现 AgentStateStore。注意 RuntimeContext 只是调用参数,真正的上下文在 AgentState 里;两者不要混用。
8. 加入 RAG
Java 的 RAG 由 Reader、向量库和 Knowledge 组成。以内存向量库为例:
import io.agentscope.core.rag.knowledge.SimpleKnowledge;
import io.agentscope.core.rag.model.RetrieveConfig;
import io.agentscope.core.rag.reader.ReaderInput;
import io.agentscope.core.rag.reader.TextReader;
import io.agentscope.core.rag.store.InMemoryStore;
// embeddingModel 例如 DashScopeTextEmbedding / OpenAITextEmbedding
SimpleKnowledge knowledge = SimpleKnowledge.builder()
.embeddingModel(embeddingModel)
.embeddingStore(InMemoryStore.builder().dimensions(1536).build())
.build();
knowledge.addDocuments(
new TextReader().read(ReaderInput.fromString(handbookText)).block()
).block();
var hits = knowledge.retrieve(
"deployment checklist",
RetrieveConfig.builder().limit(5).build()
).block();
把 Knowledge 交给 ReActAgent.builder().knowledge(knowledge),或使用 GenericRAGHook 显式控制检索时机。生产环境通常使用 MilvusStore、QdrantStore、PgVectorStore 或 ElasticsearchStore。
9. 使用 Spring Boot Starter
如果项目已经是 Spring Boot,引入:
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-openai-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
OpenAIAutoConfiguration 会基于 OpenAIProperties 自动创建 OpenAIChatModel bean。你可以直接注入模型,再自行构建 ReActAgent;需要定制 Builder 时实现 OpenAIChatModelBuilderCustomizer。其他 starter(DashScope、Anthropic、Gemini、Ollama、A2A、AG-UI 等)遵循同样的模式。
10. 下一步
- 在
ReActAgent页面查看 Builder 的全部配置项; - 在
Toolkit页面查看工具、MCP、工具分组与元工具; - 在
AgentState与AgentStateStore页面查看持久化; - 阅读
io.agentscope.core.memory下的长期记忆实现; - 需要将智能体暴露为 HTTP 服务时,查看 A2A server 与 AG-UI 扩展。
This page targets agentscope-core 2.0.4 and agentscope-extensions-model-openai 2.0.4. The Java edition is built on Project Reactor: call returns Mono<Msg> and stream returns Flux<Event>, so the examples never rely on blocking APIs.
1. Maven dependencies
<properties>
<agentscope.version>2.0.4</agentscope.version>
</properties>
<dependencies>
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-core</artifactId>
<version>${agentscope.version}</version>
</dependency>
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-extensions-model-openai</artifactId>
<version>${agentscope.version}</version>
</dependency>
</dependencies>
Gradle:
dependencies {
implementation("io.agentscope:agentscope-core:2.0.4")
implementation("io.agentscope:agentscope-extensions-model-openai:2.0.4")
}
Coordinates for every official extension are listed in Artifacts. Model providers, RAG stores, A2A, AG-UI and sandboxes are separate artifacts; add only what you need.
2. Create a model
Vendor models are constructed with builders:
import io.agentscope.extensions.model.openai.OpenAIChatModel;
OpenAIChatModel model = OpenAIChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.stream(true)
.build();
Add .baseUrl("https://your-endpoint/v1") for compatible endpoints. Other vendors use their own extensions, such as DashScopeChatModel, AnthropicChatModel, GeminiChatModel or OllamaChatModel.
3. Define a tool
A tool is a plain method with annotations. Toolkit.registerTool(Object) scans @Tool methods and @ToolParam describes parameters:
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import io.agentscope.core.tool.Toolkit;
public final class WeatherTools {
@Tool(name = "get_weather", description = "Return the current weather for a city.")
public String getWeather(
@ToolParam(name = "city", description = "The city name, for example Hangzhou")
String city) {
// Call a real weather API in production
return city + ": sunny, 24C";
}
}
Toolkit toolkit = new Toolkit();
toolkit.registerTool(new WeatherTools());
@Tool also supports readOnly, concurrencySafe, strict, externalTool and stateInjected. To enable/disable groups dynamically, use tool groups (createToolGroup, updateToolGroups).
4. Build the agent and call it
import io.agentscope.core.ReActAgent;
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.message.Msg;
ReActAgent agent = ReActAgent.builder()
.name("assistant")
.sysPrompt("You are a concise assistant. Use tools when needed.")
.model(model)
.toolkit(toolkit)
.maxIters(10)
.build();
RuntimeContext context = RuntimeContext.builder()
.sessionId("demo-session")
.userId("demo-user")
.build();
Msg reply = agent.call("What's the weather in Hangzhou?", context).block();
System.out.println(reply.getTextContent());
agent.close();
RuntimeContext carries per-call metadata: session/user identity, an optional AgentState, tool execution context and an attribute bag. It is not persisted; state that survives between calls lives in AgentState.
5. Streaming events
import io.agentscope.core.event.TextBlockDeltaEvent;
agent.streamEvents("Explain ReAct in two sentences.", context)
.doOnNext(event -> {
if (event instanceof TextBlockDeltaEvent delta) {
System.out.print(delta.getDelta());
}
})
.blockLast();
Use StreamOptions.builder().eventTypes(...) to filter which events you subscribe to. The event model (thinking, tool calls, tool results, reply completion, ...) lives in io.agentscope.core.event.
6. Structured output
Pass a result class to call to get type-safe output:
public record WeatherReport(String city, double temperatureC, String condition) {}
Msg reply = agent.call(
"Report the weather in Hangzhou as structured data.",
WeatherReport.class,
context
).block();
WeatherReport report = reply.getStructuredData(WeatherReport.class);
The mechanism matches Python: a structured-output tool is injected into the loop and the model must call it with schema-conforming arguments. getStructuredData uses Jackson, so the result type must be Jackson-friendly (a record, POJO or annotated class).
7. State persistence
Java persists session state through AgentStateStore. The built-in JSON-file store is convenient for local development:
import io.agentscope.core.state.JsonFileAgentStateStore;
JsonFileAgentStateStore store = new JsonFileAgentStateStore(Path.of("./agent-state"));
ReActAgent agent = ReActAgent.builder()
.name("assistant")
.sysPrompt("You are a helpful assistant.")
.model(model)
.stateStore(store)
.defaultSessionId("demo-session")
.build();
Production deployments can use MysqlSession, RedisSession or a custom AgentStateStore. Remember that RuntimeContext is a call argument while the real conversation state lives in AgentState; do not confuse the two.
8. Add RAG
Java RAG is composed of Reader, a vector store and Knowledge. With the in-memory store:
import io.agentscope.core.rag.knowledge.SimpleKnowledge;
import io.agentscope.core.rag.model.RetrieveConfig;
import io.agentscope.core.rag.reader.ReaderInput;
import io.agentscope.core.rag.reader.TextReader;
import io.agentscope.core.rag.store.InMemoryStore;
// embeddingModel is e.g. DashScopeTextEmbedding / OpenAITextEmbedding
SimpleKnowledge knowledge = SimpleKnowledge.builder()
.embeddingModel(embeddingModel)
.embeddingStore(InMemoryStore.builder().dimensions(1536).build())
.build();
knowledge.addDocuments(
new TextReader().read(ReaderInput.fromString(handbookText)).block()
).block();
var hits = knowledge.retrieve(
"deployment checklist",
RetrieveConfig.builder().limit(5).build()
).block();
Pass it via ReActAgent.builder().knowledge(knowledge), or use GenericRAGHook to control retrieval timing. Production usually replaces the in-memory store with MilvusStore, QdrantStore, PgVectorStore or ElasticsearchStore.
9. Use the Spring Boot starter
For Spring Boot projects, add:
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope-openai-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
OpenAIAutoConfiguration creates an OpenAIChatModel bean from OpenAIProperties. Inject the model and build your ReActAgent; implement OpenAIChatModelBuilderCustomizer to customize the builder. Other starters (DashScope, Anthropic, Gemini, Ollama, A2A, AG-UI, ...) follow the same pattern.
10. Next steps
- See
ReActAgentfor every builder option. - See
Toolkitfor tools, MCP, tool groups and meta tools. - See
AgentStateandAgentStateStorefor persistence. - Browse
io.agentscope.core.memoryfor long-term memory implementations. - To expose an agent over HTTP, look at the A2A server and AG-UI extensions.