AgentScope Java 入门到进阶指南
一、什么是 AgentScope Java?
AgentScope Java 是一个面向智能体的编程框架,用于构建基于大语言模型(LLM)的应用。它提供了构建智能体所需的一切功能:ReAct 推理、工具调用、记忆管理、多智能体协作等,让你能够快速开发生产级的 AI 智能体应用。
二、环境准备
1. 系统要求
- JDK 17 或更高版本
- Maven 或 Gradle 构建工具
2. 添加依赖
在你的 pom.xml 中添加以下依赖:
<dependency>
<groupId>io.agentscope</groupId>
<artifactId>agentscope</artifactId>
<version>1.0.1</version>
</dependency>三、快速入门:创建第一个智能体
1. 最简单的智能体示例
下面是一个基础的智能体示例,它可以响应用户的问候:
import io.agentscope.core.ReActAgent;
import io.agentscope.core.message.Msg;
import io.agentscope.core.model.DashScopeChatModel;
public class FirstAgentExample {
public static void main(String[] args) {
// 获取API密钥(实际开发中建议使用环境变量)
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 创建智能体
ReActAgent agent = ReActAgent.builder()
.name("MyFirstAgent")
.sysPrompt("你是一个友好的AI助手,总是用简洁的语言回答问题。")
.model(DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-plus")
.build())
.build();
// 发送消息并获取响应
Msg userMessage = Msg.builder()
.name("User") // 设置发送者名称
.role(MsgRole.USER) // 指定角色为用户
.content(TextBlock.builder()
.text("你好,我叫小明,很高兴认识你!") // 设置消息内容
.build())
.build();
// 发送消息并获取响应
Msg response = agent.call(userMessage).block();
// 输出响应
assert response != null;
System.out.println("智能体回复:" + response.getTextContent());
}
}2. 代码解释
ReActAgent.builder():使用建造者模式创建智能体name():设置智能体名称sysPrompt():设置系统提示,定义智能体的角色和行为model():配置底层LLM模型,这里使用了阿里云的DashScope服务agent.call():发送消息给智能体并获取响应
四、基础功能:智能体与工具
1. 创建自定义工具
工具是智能体与外部世界交互的桥梁。下面创建一个简单的计算器工具:
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import reactor.core.publisher.Mono;
public class CalculatorTool {
@Tool(name = "calculator", description = "进行数学计算,支持加减乘除")
public Mono<String> calculate(
@ToolParam(name = "expression", description = "数学表达式,如1+2*3") String expression
) {
try {
// 简单的表达式计算逻辑
double result = evaluateExpression(expression);
return Mono.just(expression + " = " + result);
} catch (Exception e) {
return Mono.just("计算错误: " + e.getMessage());
}
}
private double evaluateExpression(String expr) {
// 实际项目中可以使用更完善的表达式解析库
expr = expr.replaceAll("\\s+", "");
// 简化实现,仅处理加减乘除
// ... 实现计算逻辑 ...
return 0; // 实际计算结果
}
}2. 在智能体中使用工具
import io.agentscope.core.ReActAgent;
import io.agentscope.core.tool.Toolkit;
public class AgentWithToolExample {
public static void main(String[] args) {
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 创建工具集并注册工具
Toolkit toolkit = new Toolkit();
toolkit.registerTool(new CalculatorTool());
// 创建带工具的智能体
ReActAgent agent = ReActAgent.builder()
.name("CalculatorAgent")
.sysPrompt("你是一个计算器助手,当需要进行数学计算时,使用calculator工具。")
.model(DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-plus")
.build())
.toolkit(toolkit) // 配置工具集
.build();
Msg userMessage = Msg.builder()
.name("User") // 设置发送者名称
.role(MsgRole.USER) // 指定角色为用户
.content(TextBlock.builder()
.text("请计算:(25 + 75) * 3 / 2") // 设置消息内容
.build())
.build();
// 测试计算功能
Msg response = agent.call(userMessage).block();
assert response != null;
System.out.println("计算结果:" + response.getTextContent());
}
}五、进阶功能:多智能体协作
1. 顺序管道(Sequential Pipeline)
顺序管道让多个智能体按顺序处理任务,前一个智能体的输出作为后一个的输入:
import io.agentscope.core.pipeline.SequentialPipeline;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.message.Msg;
public class SequentialPipelineExample {
public static void main(String[] args) {
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 创建三个不同功能的智能体
ReActAgent translator = createTranslator(apiKey);
ReActAgent summarizer = createSummarizer(apiKey);
ReActAgent sentimentAnalyzer = createSentimentAnalyzer(apiKey);
// 构建顺序管道
SequentialPipeline pipeline = SequentialPipeline.builder()
.addAgent(translator)
.addAgent(summarizer)
.addAgent(sentimentAnalyzer)
.build();
// 输入文本
String inputText = "Artificial Intelligence has revolutionized the technology industry...";
Msg userMessage = Msg.builder()
.name("User") // 设置发送者名称
.role(MsgRole.USER) // 指定角色为用户
.content(TextBlock.builder()
.text(inputText) // 设置消息内容
.build())
.build();
// 执行管道
Msg result = pipeline.execute(userMessage).block();
// 输出最终结果
System.out.println("最终分析结果:" + result.getTextContent());
}
// 创建翻译智能体
private static ReActAgent createTranslator(String apiKey) {
return ReActAgent.builder()
.name("Translator")
.sysPrompt("将输入的英文文本准确翻译成中文,只输出翻译结果。")
.model(DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-plus")
.build())
.build();
}
// 创建摘要智能体
private static ReActAgent createSummarizer(String apiKey) {
return ReActAgent.builder()
.name("Summarizer")
.sysPrompt("将输入文本总结为2-3句话,保留核心信息。")
.model(DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-plus")
.build())
.build();
}
// 创建情感分析智能体
private static ReActAgent createSentimentAnalyzer(String apiKey) {
return ReActAgent.builder()
.name("SentimentAnalyzer")
.sysPrompt("分析输入文本的情感倾向,分为积极、消极、中性或混合。")
.model(DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-plus")
.build())
.build();
}
}2. 并行管道(Fanout Pipeline)
并行管道让多个智能体同时处理同一输入,适用于需要多视角分析的场景:
import io.agentscope.core.pipeline.FanoutPipeline;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.message.Msg;
import java.util.List;
public class FanoutPipelineExample {
public static void main(String[] args) {
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 创建三个专家智能体
ReActAgent techExpert = createTechExpert(apiKey);
ReActAgent uxExpert = createUXExpert(apiKey);
ReActAgent bizAnalyst = createBusinessAnalyst(apiKey);
// 构建并行管道
FanoutPipeline pipeline = FanoutPipeline.builder()
.addAgent(techExpert)
.addAgent(uxExpert)
.addAgent(bizAnalyst)
.concurrent() // 并行执行
.build();
// 产品创意
String productIdea = "一个使用AI分析日常照片并自动生成个性化视频日记的移动应用...";
Msg userMessage = Msg.builder()
.name("User") // 设置发送者名称
.role(MsgRole.USER) // 指定角色为用户
.content(TextBlock.builder()
.text(productIdea) // 设置消息内容
.build())
.build();
// 执行管道
List<Msg> results = pipeline.execute(userMessage).block();
// 输出结果
for (Msg result : results) {
System.out.println("=== " + result.getName() + " 分析 ===");
System.out.println(result.getTextContent() + "\n");
}
}
// 创建技术专家智能体
private static ReActAgent createTechExpert(String apiKey) {
// 实现与前面类似
// ...
}
// 创建UX专家智能体
private static ReActAgent createUXExpert(String apiKey) {
// 实现与前面类似
// ...
}
// 创建业务分析师智能体
private static ReActAgent createBusinessAnalyst(String apiKey) {
// 实现与前面类似
// ...
}
}六、高级功能:计划与记忆
1. 使用 PlanNotebook 进行任务规划
FileTool:操作文件的工具
/**
* 这是一个文件工具类,用于处理文件相关的功能
*/
public class FileTool {
/**
* 读取文件内容
*/
@Tool(name = "readFile", description = "读取指定文件的内容")
public String readFile(@ToolParam(name = "filePath", description = "文件路径") String filePath) {
try {
Path path = Paths.get(filePath);
// 使用BufferedReader进行缓冲读取,提高大文件读取效率
StringBuilder content = new StringBuilder();
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append(System.lineSeparator());
}
}
return content.toString();
} catch (IOException e) {
return "读取文件失败: " + e.getMessage();
}
}
/**
* 写入文件内容
*/
@Tool(name = "writeFile", description = "写入文件内容")
public String writeFile(@ToolParam(name = "filePath", description = "文件路径") String filePath,
@ToolParam(name = "content", description = "文件内容") String content) {
try {
Path path = Paths.get(filePath);
// 确保父目录存在
if (path.getParent() != null && !Files.exists(path.getParent())) {
Files.createDirectories(path.getParent());
}
// 使用BufferedWriter进行缓冲写入,提高写入效率
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
writer.write(content);
}
return "文件写入成功";
} catch (IOException e) {
return "写入文件失败: " + e.getMessage();
}
}
}PlanNotebook 帮助智能体分解复杂任务并跟踪执行进度:
import io.agentscope.core.ReActAgent;
import io.agentscope.core.plan.PlanNotebook;
import io.agentscope.core.tool.Toolkit;
public class PlanNotebookExample {
public static void main(String[] args) {
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 创建工具集
Toolkit toolkit = new Toolkit();
toolkit.registerTool(new FileTool());
// 创建计划笔记本
PlanNotebook planNotebook = PlanNotebook.builder().build();
// 创建带计划能力的智能体
ReActAgent agent = ReActAgent.builder()
.name("PlannerAgent")
.sysPrompt("你是一个有条理的助手,对于多步骤任务,先创建计划再执行。")
.model(DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-plus")
.build())
.toolkit(toolkit)
.planNotebook(planNotebook) // 配置计划笔记本
.build();
// 发送多步骤任务
Msg userMessage = Msg.builder()
.name("User") // 设置发送者名称
.role(MsgRole.USER) // 指定角色为用户
.content(TextBlock.builder()
.text(task) // 设置消息内容
.build())
.build();
Msg response = agent.call(userMessage).block();
System.out.println("任务结果:" + response.getTextContent());
}
}2. 检索增强生成(RAG)
RAG 技术让智能体能够利用外部知识库回答问题:
package org.example.agentScope.test;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.message.Msg;
import io.agentscope.core.message.MsgRole;
import io.agentscope.core.message.TextBlock;
import io.agentscope.core.model.DashScopeChatModel;
import io.agentscope.core.rag.Knowledge;
import io.agentscope.core.rag.RAGMode;
import io.agentscope.core.rag.knowledge.SimpleKnowledge;
import io.agentscope.core.embedding.dashscope.DashScopeTextEmbedding;
import io.agentscope.core.rag.store.InMemoryStore;
import io.agentscope.core.rag.model.Document;
import io.agentscope.core.rag.reader.ReaderInput;
import io.agentscope.core.rag.reader.SplitStrategy;
import io.agentscope.core.rag.reader.TextReader;
import java.util.List;
public class RAGExample {
public static void main(String[] args) {
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 创建嵌入模型
var embeddingModel = DashScopeTextEmbedding.builder()
.apiKey(apiKey)
.modelName("text-embedding-v3")
.dimensions(1024)
.build();
// 创建向量存储
var vectorStore = InMemoryStore.builder().dimensions(1024).build();
// 创建知识库
Knowledge knowledge = SimpleKnowledge.builder()
.embeddingModel(embeddingModel)
.embeddingStore(vectorStore)
.build();
// 向知识库添加文档
addDocumentsToKnowledge(knowledge);
// 创建带RAG能力的智能体
ReActAgent agent = ReActAgent.builder()
.name("RAGAgent")
.sysPrompt("你是一个知识丰富的助手,使用提供的知识库回答问题。")
.model(DashScopeChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-max")
.build())
.knowledge(knowledge) // 配置知识库
.ragMode(RAGMode.AGENTIC) // 智能体自主决定何时检索
.build();
// 测试RAG功能
// 快速创建用户消息
Msg userMsg = Msg.builder()
.role(MsgRole.USER) // 明确指定角色为用户
.content(TextBlock.builder()
.text("AgentScope有哪些核心功能?") // 设置消息内容
.build())
.build();
Msg response = agent.call(userMsg).block();
System.out.println("回答:" + response.getTextContent());
}
private static void addDocumentsToKnowledge(Knowledge knowledge) {
// 1. 创建文本阅读器(设置分块参数:最大长度512,按段落分割,重叠长度50)
TextReader reader = new TextReader(512, SplitStrategy.PARAGRAPH, 50);
// 2. 准备示例文档内容(可替换为实际文档)
String[] documentTexts = {
"AgentScope 是一个多智能体框架,支持同步和异步通信," +
"提供统一的接口用于构建和管理多智能体应用。框架支持多种智能体类型," +
"包括 ReActAgent 等实现了推理与行动循环的智能体。",
"RAG(检索增强生成)技术通过从知识库中检索相关信息来增强语言模型的生成能力," +
"帮助模型获取最新信息并减少幻觉。AgentScope 中的 RAG 模块支持多种向量存储," +
"包括内存存储和外部向量数据库。"
};
// 3. 处理并添加每个文档到知识库
for (String text : documentTexts) {
try {
// 将文本转换为阅读器输入
ReaderInput input = ReaderInput.fromString(text);
// 读取并分块文档(block() 用于同步获取结果)
List<Document> documents = reader.read(input).block();
if (documents != null && !documents.isEmpty()) {
// 向知识库添加文档(block() 用于同步等待完成)
knowledge.addDocuments(documents).block();
System.out.println("成功添加文档:" + text.substring(0, Math.min(50, text.length())) + "...");
}
} catch (Exception e) {
System.err.println("添加文档失败:" + e.getMessage());
}
}
}
}七、调试与监控
AgentScope 提供了 Studio 工具用于可视化调试,但要安装Studio ,详情可查看
https://github.com/agentscope-ai/agentscope-studio
import io.agentscope.core.ReActAgent;
import io.agentscope.core.message.Msg;
import io.agentscope.core.model.DashScopeChatModel;
import io.agentscope.core.studio.StudioManager;
import io.agentscope.core.studio.StudioMessageHook;
import io.agentscope.core.studio.StudioUserAgent;
import java.util.List;
public class StudioDebugExample {
public static void main(String[] args) {
// 1. 初始化 Studio 连接(默认端口 5173)
StudioManager.init()
.studioUrl("http://localhost:5173") // Studio 服务地址
.project("MyFirstProject") // 项目名称(用于分类调试记录)
.runName("debug_run_" + System.currentTimeMillis()) // 本次运行名称(建议唯一)
.initialize()
.block(); // 同步等待初始化完成
try {
// 2. 创建带 Studio 钩子的智能体(自动上报消息)
ReActAgent agent = ReActAgent.builder()
.name("Assistant")
.sysPrompt("你是一个调试助手")
.model(DashScopeChatModel.builder() // 配置实际使用的模型
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.modelName("qwen-plus")
.build())
.hooks(List.of(new StudioMessageHook(StudioManager.getClient()))) // 绑定 Studio 钩子
.build();
// 3. 创建 Studio 用户代理(通过 Web UI 输入消息)
StudioUserAgent user = StudioUserAgent.builder()
.name("User")
.studioClient(StudioManager.getClient())
.webSocketClient(StudioManager.getWebSocketClient())
.build();
// 4. 运行交互循环(通过 Studio Web UI 输入消息)
Msg msg = null;
while (true) {
msg = user.call(msg).block(); // 等待 Web UI 输入
if (msg == null || "exit".equalsIgnoreCase(msg.getTextContent())) {
break; // 输入 exit 退出
}
msg = agent.call(msg).block(); // 智能体处理消息
}
} finally {
// 5. 关闭 Studio 连接
StudioManager.shutdown();
}
}
}八、总结与进阶学习
通过本教程,你已经了解了 AgentScope Java 的核心能:
- 基础智能体创建与使用
- 工具开发与集成
- 多智能体协作(顺序与并行)
- 任务规划与记忆管理
- 检索增强生成(RAG)
- 调试与监控
进阶学习资源
尝试扩展本教程中的示例,例如:
- 创建更复杂的工具集成外部API
- 构建多智能体协作系统解决复杂问题
- 集成自己的知识库实现领域专家智能体
到此这篇关于AgentScope Java 入门到进阶的文章就介绍到这了,更多相关AgentScope Java 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot+MyBatis处理JSON字段的完整指南
本文主要介绍了SpringBoot+MyBatis处理JSON字段的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2026-03-03


最新评论