当前位置: 首页 > news >正文

506-Spring AI Alibaba Multi-Agent OpenManus 功能完整案例

本案例将引导您一步步构建一个基于多智能体系统的 Spring Boot 应用,演示如何利用 Spring AI Alibaba 的 Graph 功能,实现一个类似 OpenManus 的多智能体协作系统,能够处理复杂任务并自主规划执行步骤。

1. 案例目标

我们将创建一个包含多个核心功能的 Web 应用,实现多智能体协作系统:

  1. 工作流示例 (/customer/chat):实现一个客户评价处理系统,根据评论内容自动进行问题分类和处理。
  2. React Agent 示例 (/react/chat):实现一个能够调用工具的智能体,如天气查询服务。
  3. Multi-agent OpenManus 示例 (/manus/chat):实现一个多智能体系统,包含规划代理、监督代理和执行代理,协作完成复杂任务。
  4. BigTool 示例 (/bigtool/search):实现能够从大量工具中精准匹配并高效调用所需工具的智能体。
  5. Reflection 示例 (/reflection/chat):实现一个能够自我反思和改进的智能体系统。

2. 技术栈与核心依赖

  • Spring Boot 3.x
  • Spring AI Alibaba (用于对接阿里云 DashScope 通义大模型)
  • Spring AI Graph (用于构建状态图和工作流)
  • Maven (项目构建工具)

在 pom.xml 中,你需要引入以下核心依赖:

<dependencies><!-- Spring AI Alibaba 核心依赖 --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-graph-core</artifactId></dependency><!-- Spring Boot Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- OpenAI 兼容模型 --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-openai</artifactId></dependency><!-- 文档解析 --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-document-parser-tika</artifactId></dependency><!-- 工具调用 --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-tool-calling-tavilysearch</artifactId></dependency><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-tool-calling-baidusearch</artifactId></dependency><!-- 其他工具依赖 --><dependency><groupId>net.sourceforge.plantuml</groupId><artifactId>plantuml-mit</artifactId><version>1.2024.4</version></dependency><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.18.3</version></dependency>
</dependencies>

3. 项目配置

在 src/main/resources/application.yml 文件中,配置你的 API Key 和其他设置。

server:port: 18080
spring:application:name: spring-ai-alibaba-graph-exampleai:dashscope:api-key: ${AI_DASHSCOPE_API_KEY}openai:base-url: https://dashscope.aliyuncs.com/compatible-modeapi-key: ${AI_DASHSCOPE_API_KEY}chat:options:model: qwen-max-latestembedding:options:model: text-embedding-v1alibaba:toolcalling:weather:enabled: trueapi-key: ${WEATHER_API_KEY}baidu:search:enabled: truetavilysearch:api-key: ${TAVILY_API_KEY}enabled: true

重要提示:请将以下环境变量设置为你获取的有效 API Key:

  • AI_DASHSCOPE_API_KEY:阿里云 DashScope API Key
  • WEATHER_API_KEY:天气服务 API Key(可选)
  • TAVILY_API_KEY:Tavily 搜索 API Key(可选)

4. Multi-Agent OpenManus 系统架构

Multi-Agent OpenManus 系统由三个核心智能体组成,它们互相协作完成用户任务:

4.1 核心智能体

  1. Planning Agent(规划代理):负责任务规划,将用户输入的复杂任务分解为可执行的步骤序列。
  2. Supervisor Agent(监督代理):负责监督 Executor Agent 完成规划的任务,判断任务是否完成或需要继续执行下一步。
  3. Executor Agent(执行代理):负责执行每一步任务,可以调用各种工具(如浏览器、Python执行器、文件操作等)来完成具体任务。

5. 核心组件实现

5.1 提示词定义 (OpenManusPrompt.java)

定义了两个核心提示词模板,分别用于规划代理和执行代理:

public interface OpenManusPrompt {String PLANNING_SYSTEM_PROMPT = """# Manus AI Assistant Capabilities## OverviewI am an AI assistant designed to help users with a wide range of tasks, for every task given by the user, I should make detailed plans on how to complete the task step by step. That means the output should be structured steps in sequential.## Task Approach Methodology### Understanding Requirements- Analyzing user requests to identify core needs- Asking clarifying questions when requirements are ambiguous- Breaking down complex requests into manageable components- Identifying potential challenges before beginning work### Planning and Execution- Creating structured plans for task completion- Selecting appropriate tools and approaches for each step- Executing steps methodically while monitoring progress- Adapting plans when encountering unexpected challenges- Providing regular updates on task status### Tool usageYou are given access to a planning tool, which can be used to generate a plan for the task given by the user. The tool will return a structured plan with steps in sequential.## Example outputTask given by the user: 帮我查询阿里巴巴最近一周的股价信息并生成图表。Output:```json{"planId": "1","steps": ["1. 打开浏览器并导航到百度首页","2. 输入"阿里巴巴最近一周股价"并开始搜索","3. 根据搜索结果,采集页面信息,获得阿里巴巴的近一周的股价信息","4. 执行脚本生成图标"]}```""";String STEP_SYSTEM_PROMPT = """You are OpenManus, an all-capable AI assistant, aimed at solving any task presented by the user. You have various tools at your disposal that you can call upon to efficiently complete complex requests. Whether it's programming, information retrieval, file processing, or web browsing, you can handle it all.You can interact with the computer using PythonExecute, save important content and information files through FileSaver, open browsers with BrowserUseTool, and retrieve information using GoogleSearch.PythonExecute: Execute Python code to interact with the computer system, data processing, automation tasks, etc.FileSaver: Save files locally, such as txt, py, html, etc.BrowserUseTool: Open, browse, and use web browsers.If you open a local HTML file, you must provide the absolute path to the file.Terminate : Record  the result summary of the task , then terminate the task.DocLoader: List all the files in a directory or get the content of a local file at a specified path. Use this tool when you want to get some related information at a directory or file asked by the user.Based on user needs, proactively select the most appropriate tool or combination of tools. For complex tasks, you can break down the problem and use different tools step by step to solve it. After using each tool, clearly explain the execution results and suggest the next steps.When you are done with the task, you can finalize the plan by summarizing the steps taken and the output of each step, call Terminate tool to record the result.""";
}

5.2 控制器实现 (OpenmanusController.java)

实现多智能体系统的控制器,负责初始化状态图和处理用户请求:

@RestController
@RequestMapping("/manus")
public class OpenmanusController {private final ChatClient planningClient;private final ChatClient stepClient;private CompiledGraph compiledGraph;public OpenmanusController(ChatModel chatModel) throws GraphStateException {// 初始化规划客户端this.planningClient = ChatClient.builder(chatModel).defaultSystem(PLANNING_SYSTEM_PROMPT).defaultAdvisors(new SimpleLoggerAdvisor()).defaultToolCallbacks(Builder.getToolCallList()).defaultOptions(OpenAiChatOptions.builder().internalToolExecutionEnabled(false).build()).build();// 初始化执行客户端this.stepClient = ChatClient.builder(chatModel).defaultSystem(STEP_SYSTEM_PROMPT).defaultToolCallbacks(Builder.getManusAgentToolCalls()).defaultAdvisors(new SimpleLoggerAdvisor()).defaultOptions(OpenAiChatOptions.builder().internalToolExecutionEnabled(false).build()).build();initGraph();}public void initGraph() throws GraphStateException {// 创建状态工厂OverAllStateFactory stateFactory = () -> {OverAllState state = new OverAllState();state.registerKeyAndStrategy("plan", new ReplaceStrategy());state.registerKeyAndStrategy("step_prompt", new ReplaceStrategy());state.registerKeyAndStrategy("step_output", new ReplaceStrategy());state.registerKeyAndStrategy("final_output", new ReplaceStrategy());return state;};// 创建智能体SupervisorAgent supervisorAgent = new SupervisorAgent(PlanningTool.INSTANCE);ReactAgent planningAgent = new ReactAgent("planningAgent", planningClient, Builder.getFunctionCallbackList(), 10);ReactAgent stepAgent = new ReactAgent("stepAgent", stepClient, Builder.getManusAgentFunctionCallbacks(), 10);// 构建状态图StateGraph graph = new StateGraph(stateFactory).addNode("planning_agent", planningAgent.asAsyncNodeAction("input", "plan")).addNode("supervisor_agent", node_async(supervisorAgent)).addNode("step_executing_agent", stepAgent.asAsyncNodeAction("step_prompt", "step_output")).addEdge(START, "planning_agent").addEdge("planning_agent", "supervisor_agent").addConditionalEdges("supervisor_agent", edge_async(supervisorAgent::think),Map.of("continue", "step_executing_agent", "end", END)).addEdge("step_executing_agent", "supervisor_agent");this.compiledGraph = graph.compile();}@GetMapping("/chat")public String simpleChat(String query) throws GraphRunnerException {return compiledGraph.invoke(Map.of("input", query)).get().data().toString();}
}

5.3 监督代理实现 (SupervisorAgent.java)

实现监督代理,负责协调规划代理和执行代理的工作:

public class SupervisorAgent implements NodeAction {private final PlanningTool planningTool;public SupervisorAgent(PlanningTool planningTool) {this.planningTool = planningTool;}@Overridepublic Map<String, Object> apply(OverAllState t) throws Exception {String planStr = (String) t.value("plan").orElseThrow();Plan tempPlan = parsePlan(planStr);Plan plan = planningTool.getGraphPlan(tempPlan.getPlan_id());Optional<Object> optionalOutput = t.value("step_output");if (optionalOutput.isPresent()) {String finalStepOutput = String.format("This is the final output of step %s:\n %s", plan.getCurrentStep(), optionalOutput.get());plan.updateStepStatus(plan.getCurrentStep(), finalStepOutput);}String promptForNextStep;if (!plan.isFinished()) {promptForNextStep = plan.nextStepPrompt();} else {promptForNextStep = "Plan completed.";}return Map.of("step_prompt", promptForNextStep);}public String think(OverAllState state) {String nextPrompt = (String) state.value("step_prompt").orElseThrow();if (nextPrompt.equalsIgnoreCase("Plan completed.")) {state.updateState(Map.of("final_output", state.value("step_output").orElseThrow()));return "end";}return "continue";}
}

5.4 规划工具实现 (PlanningTool.java)

实现规划工具,用于创建和管理任务计划:

public class PlanningTool implements BiFunction<String, ToolContext, String> {private Map<String, Map<String, Object>> plans = new HashMap<>();private Map<String, Plan> graphPlans = new HashMap<>();private String currentPlanId;public String createPlan(String planId, String title, List<String> steps, ToolContext context) {OverAllState state = (OverAllState) context.getContext().get("state");if (plans.containsKey(planId)) {throw new RuntimeException("A plan with ID '" + planId + "' already exists.");}Map<String, Object> plan = new HashMap<>();plan.put("plan_id", planId);plan.put("title", title);plan.put("steps", steps);plan.put("step_statuses", new ArrayList<>(Collections.nCopies(steps.size(), "not_started")));plan.put("step_notes", new ArrayList<>(Collections.nCopies(steps.size(), "")));plans.put(planId, plan);this.currentPlanId = planId;List<Message> messages = (List<Message>) state.value("messages").get();Plan plan2 = new Plan(messages.get(0).getText(), planId, steps);graphPlans.put(planId, plan2);return planId;}public Plan getGraphPlan(String planId) {if (planId == null || planId.isEmpty()) {if (currentPlanId == null) {throw new RuntimeException("No active plan. Please specify a plan_id or set an active plan.");}planId = currentPlanId;}if (!plans.containsKey(planId)) {throw new RuntimeException("No plan found with ID: " + planId);}return graphPlans.get(planId);}
}

6. 运行与测试

  1. 启动应用:运行 GraphApplication 类启动示例应用。
  2. 配置 API Key:设置必要的环境变量。
  3. 使用浏览器或 API 工具进行测试

测试 1:Multi-Agent OpenManus 示例

访问以下 URL,测试多智能体系统的功能:

http://localhost:18080/manus/chat?query=帮我查询阿里巴巴近一周的股票信息

预期工作流程

  1. Planning Agent 接收用户查询,生成任务计划。
  2. Supervisor Agent 接收计划,决定下一步执行。
  3. Executor Agent 执行具体步骤,可能调用浏览器工具、搜索工具等。
  4. Supervisor Agent 评估执行结果,决定是否继续下一步或结束任务。
  5. 循环步骤 3-4,直到所有计划步骤完成。

测试 2:工作流示例(客户评价处理)

访问以下 URL,测试客户评价处理系统:

http://localhost:18080/customer/chat?query=我收到的产品有快递破损,需要退换货?

预期工作流程

  1. 系统接收用户评论,识别为 negative 评论。
  2. 进行第二级分类,识别问题类型为 "transportation"。
  3. 将问题分流到具体的问题处理节点。
  4. 处理节点进行处理并记录后,流程结束。

测试 3:React Agent 示例

访问以下 URL,测试 React Agent 的功能:

http://localhost:18080/react/chat?query=分别帮我查询杭州、上海和南京的天气

预期工作流程

  1. React Agent 接收用户查询,识别需要调用天气查询工具。
  2. 调用天气查询工具,获取杭州、上海和南京的天气信息。
  3. 将工具执行结果返回给用户。

测试 4:BigTool 示例

访问以下 URL,测试 BigTool 的功能:

http://localhost:18080/bigtool/search?query=计算0.5的余弦

预期工作流程

  1. Tool Agent 接收用户查询,从大量工具中筛选出最适合的工具(如 Math.cos)。
  2. CalculateAgent 使用筛选出的工具执行计算任务。
  3. 将计算结果返回给用户。

测试 5:Reflection 示例

访问以下 URL,测试 Reflection 的功能:

http://localhost:18080/reflection/chat?query=写一篇论文,题目是东北经济落后分析

预期工作流程

  1. Assistant Node 生成初始论文。
  2. Judge Node 评判论文并提供改进建议。
  3. Assistant Node 根据反馈生成改进版论文。
  4. 重复步骤 2-3,直到达到最大迭代次数或论文质量满足要求。

7. 实现思路与扩展建议

实现思路

本案例的核心思想是"多智能体协作"。我们将复杂任务分解为多个子任务,每个子任务由专门的智能体负责处理,通过状态图协调各智能体之间的工作流程。这种架构使得:

  • 模块化设计:每个智能体专注于特定功能,职责明确,便于维护和扩展。
  • 灵活的工作流:通过状态图可以灵活定义各种复杂的工作流程,适应不同场景需求。
  • 工具集成:智能体可以调用各种工具(如浏览器、Python执行器、文件操作等),扩展了系统的能力边界。

扩展建议

  • 增加更多智能体:可以根据需要增加更多专门的智能体,如数据分析智能体、图像处理智能体等。
  • 优化工具库:扩展工具库,增加更多实用工具,如数据库操作工具、API调用工具等。
  • 引入记忆机制:为智能体引入长期记忆机制,使其能够记住历史交互和学到的知识。
  • 增加人机交互:在关键决策点引入人机交互,让人类可以参与决策过程,提高系统的可控性。
  • 多模态支持:扩展系统以支持多模态输入输出,如文本、图像、音频等。
http://www.dtcms.com/a/557915.html

相关文章:

  • 做的比较好的网站有哪些从化区住房和建设局网站
  • 软件测试大赛web测试-python【备赛4 复盘待完善】
  • 37_AI智能体工具插件之Agent决策状态模型和JSON输出解析器数据模型设计实战
  • <项目代码>yolo织物缺陷识别<目标检测>
  • 构建AI智能体:八十一、SVD模型压缩的艺术:如何科学选择K值实现最佳性能
  • Megatron-LM张量并行详解:原理、实现与应用
  • systemd timer定时任务 —— 筑梦之路
  • win7 iis7 添加网站百度竞价网站建设
  • js网站分页怎么做wordpress怎么保存图片
  • linux-系统启动-8
  • 数码商城系统|电子|基于SprinBoot+vue的商城推荐系统(源码+数据库+文档)
  • 第10讲:导航与路由:在页面间穿梭
  • Linux 磁盘空间“消失”之谜:文件已删,空间却不释放?
  • P1990 覆盖墙壁(dp)
  • 计算机操作系统理论学习
  • 胶州建网站推广游戏的平台
  • 未来之窗昭和仙君(四十九)集成电路芯片生产管理出库——东方仙盟筑基期
  • 哈尔滨公司网站建设科技企业网站源码
  • 行业网站推广怎么做wordpress-3.7
  • Pandas 简介与安装
  • openpnp - 吸嘴的单独校准
  • 程序员除了做软件是不是就做网站县 两学一做网站
  • 企业网站制作公司有哪些口碑营销的本质是什么
  • 北京住房和建设部网站首页网站开发结构图
  • 最新电子电气架构(EEA)调研-4
  • Google Chrome (dev beta)
  • SimPy经典案例分析
  • 跨端开发实践:多端适配指南
  • 索引的知识总结
  • 外贸汽车网站制作设计类专业笔记本电脑推荐