Spring AI Alibaba Graph 实践

本文中将阐述下 AI 流程编排框架和 Spring AI Alibaba Graph 以及如何使用。

1. Agent 智能体

结合 Google 和 Authropic 对 Agent 的定义:Agent 的定义为:智能体(Agent)是能够独立运行,感知和理解现实世界并使用工具来实现最终目标的应用程序。

从架构上,可以将 Agent 分为两类:

  1. Workflows 系统:人类干预做整体决策,LLMs 作为 workflows 链路的节点。
    1. 具有明确语义的系统,预先定义好 workflows 流程;
    2. LLMs 通过各个 Node 节点对 Workflows 路径编排来达到最终效果。
  2. 智能体系统(Agents):LLMs 作为大脑决策,自驱动完成任务。
    1. LLMs 自己编排和规划工具调用;
    2. 适用于模型驱动决策的场景。

以上两种架构都在 Spring AI Alibaba 项目中有体现:一是 JManus 系统。二是基于 spring ai alibaba graph 构建的 DeepResearch 系统。

1. AI 智能体框架介绍

在过去一年中,AI Infra 快速发展,涌现了一系列以 LangChain 为代码的 AI 应用开发框架,到最基础的应用开发框架到智能体编排,AI 应用观测等。此章节中主要介绍下 AI 应用的智能体编排框架。

1.1 Microsoft AutoGen

Github 地址:https://github.com/microsoft/autogen

由微软开源的智能体开发框架:AutoGen 是一个用于创建可自主行动或与人类协同工作的多智能体 AI 应用程序的框架。

1.2 LangGraph

Github 地址:https://github.com/langchain-ai/langgraph

以 LangGraph 为基础,使用图结构的 AI 应用编排框架。由 LangChain 社区开发,社区活跃。

1.3 CrewAI

Github 地址:https://github.com/crewAIInc/crewAI

CrewAI 是一个精简、快速的 Python 框架,完全从零构建,完全独立于 LangChain 或其他代理框架。它为开发人员提供了高级的简洁性和精确的底层控制,非常适合创建适合任何场景的自主 AI 代理。

2. Spring AI Alibaba Graph

Github 地址:https://github.com/alibaba/spring-ai-alibaba/tree/main/spring-ai-alibaba-graph

Spring AI Alibaba Graph 是一款面向 Java 开发者的工作流、多智能体框架,用于构建由多个 AI 模型或步骤组成的复杂应用。通过图结构的定义,来描述智能体中的状态流转逻辑。

框架核心包括:StateGraph(状态图,用于定义节点和边)、Node(节点,封装具体操作或模型调用)、Edge(边,表示节点间的跳转关系)以及 OverAllState(全局状态,贯穿流程共享数据)

2.1 快速入门

Demo 地址:https://github.com/deigmata-paideias/deigmata-paideias/tree/main/ai/exmaple/spring-ai-alibaba-graph-demo

pom.xml
<dependencies><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-dashscope</artifactId></dependency><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-graph-core</artifactId><version>1.0.0.2</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId></dependency>
</dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>3.4.5</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-bom</artifactId><version>1.0.0.2</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>
application.yml
server:port: 8081spring:ai:dashscope:api-key: ${AI_DASHSCOPE_API_KEY}
Config

import com.alibaba.cloud.ai.graph.GraphRepresentation;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.OverAllStateFactory;
import com.alibaba.cloud.ai.graph.StateGraph;
import com.alibaba.cloud.ai.graph.action.EdgeAction;
import com.alibaba.cloud.ai.graph.exception.GraphStateException;
import com.alibaba.cloud.ai.graph.node.QuestionClassifierNode;
import com.alibaba.cloud.ai.graph.state.strategy.ReplaceStrategy;
import indi.yuluo.graph.customnode.RecordingNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.HashMap;
import java.util.List;
import java.util.Map;import static com.alibaba.cloud.ai.graph.StateGraph.END;
import static com.alibaba.cloud.ai.graph.StateGraph.START;
import static com.alibaba.cloud.ai.graph.action.AsyncEdgeAction.edge_async;
import static com.alibaba.cloud.ai.graph.action.AsyncNodeAction.node_async;/*** Graph Demo:首先判断评价正负,其次细分负面问题,最后输出处理方案。** @author yuluo* @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>*/@Configuration
public class GraphAutoConfiguration {private static final Logger logger = LoggerFactory.getLogger(GraphAutoConfiguration.class);/*** 定义一个工作流 StateGraph Bean.*/@Beanpublic StateGraph workflowGraph(ChatClient.Builder builder) throws GraphStateException {// LLMs BeanChatClient chatClient = builder.defaultAdvisors(new SimpleLoggerAdvisor()).build();// 定义一个 OverAllStateFactory,用于在每次执行工作流时创建初始的全局状态对象。通过注册若干 Key 及其更新策略来管理上下文数据// 注册三个状态 key 分别为// 1. input:用户输入的文本// 2. classifier_output:分类器的输出结果// 3. solution:最终输出结论// 使用 ReplaceStrategy(每次写入替换旧值)策略处理上下文状态对象中的数据,用于在节点中传递数据OverAllStateFactory stateFactory = () -> {OverAllState state = new OverAllState();state.registerKeyAndStrategy("input", new ReplaceStrategy());state.registerKeyAndStrategy("classifier_output", new ReplaceStrategy());state.registerKeyAndStrategy("solution", new ReplaceStrategy());return state;};// 创建 workflows 节点// 使用 Graph 框架预定义的 QuestionClassifierNode 来处理文本分类任务// 评价正负分类节点QuestionClassifierNode feedbackClassifier = QuestionClassifierNode.builder().chatClient(chatClient).inputTextKey("input").categories(List.of("positive feedback", "negative feedback")).classificationInstructions(List.of("Try to understand the user's feeling when he/she is giving the feedback.")).build();// 负面评价具体问题分类节点QuestionClassifierNode specificQuestionClassifier = QuestionClassifierNode.builder().chatClient(chatClient).inputTextKey("input").categories(List.of("after-sale service", "transportation", "product quality", "others")).classificationInstructions(List.of("What kind of service or help the customer is trying to get from us? Classify the question based on your understanding.")).build();// 编排 Node 节点,使用 StateGraph 的 API,将上述节点加入图中,并设置节点间的跳转关系// 首先将节点注册到图,并使用 node_async(...) 将每个 NodeAction 包装为异步节点执行(提高吞吐或防止阻塞,具体实现框架已封装)StateGraph stateGraph = new StateGraph("Consumer Service Workflow Demo", stateFactory)// 定义节点.addNode("feedback_classifier", node_async(feedbackClassifier)).addNode("specific_question_classifier", node_async(specificQuestionClassifier)).addNode("recorder", node_async(new RecordingNode()))// 定义边(流程顺序).addEdge(START, "feedback_classifier").addConditionalEdges("feedback_classifier",edge_async(new FeedbackQuestionDispatcher()),Map.of("positive", "recorder", "negative", "specific_question_classifier")).addConditionalEdges("specific_question_classifier",edge_async(new SpecificQuestionDispatcher()),Map.of("after-sale", "recorder", "transportation", "recorder", "quality", "recorder", "others","recorder"))// 图的结束节点.addEdge("recorder", END);GraphRepresentation graphRepresentation = stateGraph.getGraph(GraphRepresentation.Type.PLANTUML,"workflow graph");System.out.println("\n\n");System.out.println(graphRepresentation.content());System.out.println("\n\n");return stateGraph;}public static class FeedbackQuestionDispatcher implements EdgeAction {@Overridepublic String apply(OverAllState state) {String classifierOutput = (String) state.value("classifier_output").orElse("");logger.info("classifierOutput: {}", classifierOutput);if (classifierOutput.contains("positive")) {return "positive";}return "negative";}}public static class SpecificQuestionDispatcher implements EdgeAction {@Overridepublic String apply(OverAllState state) {String classifierOutput = (String) state.value("classifier_output").orElse("");logger.info("classifierOutput: {}", classifierOutput);Map<String, String> classifierMap = new HashMap<>();classifierMap.put("after-sale", "after-sale");classifierMap.put("quality", "quality");classifierMap.put("transportation", "transportation");for (Map.Entry<String, String> entry : classifierMap.entrySet()) {if (classifierOutput.contains(entry.getKey())) {return entry.getValue();}}return "others";}}}
自定义 RecordingNode 节点
public class RecordingNode implements NodeAction {private static final Logger logger = LoggerFactory.getLogger(RecordingNode.class);@Overridepublic Map<String, Object> apply(OverAllState state) {String feedback = (String) state.value("classifier_output").get();Map<String, Object> updatedState = new HashMap<>();if (feedback.contains("positive")) {logger.info("Received positive feedback: {}", feedback);updatedState.put("solution", "Praise, no action taken.");}else {logger.info("Received negative feedback: {}", feedback);updatedState.put("solution", feedback);}return updatedState;}}
Controller
@RestController
@RequestMapping("/graph/demo")
public class GraphController {private final CompiledGraph compiledGraph;public GraphController(@Qualifier("workflowGraph") StateGraph stateGraph) throws GraphStateException {this.compiledGraph = stateGraph.compile();}@GetMapping("/chat")public String simpleChat(@RequestParam("query") String query) {return compiledGraph.invoke(Map.of("input", query)).flatMap(input -> input.value("solution")).get().toString();}}

2.2 访问测试

### 正面
GET http://localhost:8081/graph/demo/chat?query="This product is excellent, I love it!"# Praise, no action taken.### 负面 1
GET http://localhost:8081/graph/demo/chat?query="这东西真垃圾啊,天呐,太难用了!"# ```json
# {"keywords": ["东西", "垃圾", "难用"], "category_name": "product quality"}
# ```### 负面 2
GET http://localhost:8081/graph/demo/chat?query="The product broke after one day, very disappointed."# ```json
# {"keywords": ["product", "broke", "one day", "disappointed"], "category_name": "product quality"}
# ```

3. 参考资料

  1. Google Agent 白皮书:https://www.kaggle.com/whitepaper-agents
  2. Authropic Agent:https://www.anthropic.com/engineering/building-effective-agents
  3. IBM Agents 智能体编排: https://www.ibm.com/cn-zh/think/topics/ai-agent-orchestration
  4. Spring AI Alibaba Graph:https://github.com/alibaba/spring-ai-alibaba/blob/main/spring-ai-alibaba-graph/README-zh.md

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.tpcf.cn/bicheng/84877.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Server 11 ,⭐通过脚本在全新 Ubuntu 系统中安装 Nginx 环境,安装到指定目录( 脚本安装Nginx )

目录 前言 一、准备工作 1.1 系统要求 1.2 创建目录 1.3 创建粘贴 1.4 授权脚本 1.5 执行脚本 1.6 安装完成 二、实际部署 2.1 赋予权限 2.2 粘贴文件 2.3 重启服务 三、脚本解析 步骤 1: 安装编译依赖 步骤 2: 创建安装目录 步骤 3: 下载解压源码 步骤 4: 配置…

层压板选择、信号完整性和其他权衡

关于印刷电路材料&#xff0c;我有很多话要说&#xff0c;我觉得这非常有趣&#xff0c;而且所有候选人都带有“材料”这个词。无论出现在顶部的东西都是我最终选择的。我实际上会描述决策过程&#xff0c;因为我认为这很有趣&#xff0c;但首先要强调将我带到这里的职业旅程。…

几种经典排序算法的C++实现

以下是几种经典排序算法的C实现&#xff0c;包含冒泡排序、选择排序、插入排序、快速排序和归并排序&#xff1a; #include <iostream> #include <vector> using namespace std;// 1. 冒泡排序 void bubbleSort(vector<int>& arr) {int n arr.size();f…

[学习] 多项滤波器在信号插值和抽取中的应用:原理、实现与仿真(完整仿真代码)

多项滤波器在信号插值和抽取中的应用&#xff1a;原理、实现与仿真 文章目录 多项滤波器在信号插值和抽取中的应用&#xff1a;原理、实现与仿真引言 第一部分&#xff1a;原理详解1.1 信号插值中的原理1.2 信号抽取中的原理1.3 多项滤波器的通用原理 第二部分&#xff1a;实现…

Linux中source和bash的区别

在Linux中&#xff0c;source和bash&#xff08;或sh&#xff09;都是用于执行Shell脚本的命令&#xff0c;但它们在执行方式和作用域上有显著区别&#xff1a; 1. 执行方式 bash script.sh&#xff08;或sh script.sh&#xff09; 启动一个新的子Shell进程来执行脚本。脚本中的…

解决文明6 内存相关内容报错EXCEPTION_ACCESS_VIOLATION

我装了很多Mod&#xff0c;大约五六十个&#xff0c;经常出现内存读写异常的报错。为了这个问题&#xff0c;我非常痛苦&#xff0c;已经在全球各大论坛查询了好几周&#xff0c;终于在下方的steam评论区发现了靠谱的解答讨论区。 https://steamcommunity.com/app/289070/dis…

IIS 实现 HTTPS:OpenSSL证书生成与配置完整指南

参考 IIS7使用自签名证书搭建https站点(内网外网都可用) windows利用OpenSSL生成证书,并加入IIS 亲测有效 !!! IIS 配置自签名证书 参考:IIS7使用自签名证书搭建https站点(内网外网都可用) 亲测可行性,不成功。 IIS 配置OpenSSL 证书 √ OpenSSL 下载 https://slp…

Spark DAG、Stage 划分与 Task 调度底层原理深度剖析

Spark DAG、Stage 划分与 Task 调度底层原理深度剖析 核心知识点详解 1. DAG (Directed Acyclic Graph) 的构建过程回顾 Spark 应用程序的执行始于 RDD 的创建和一系列的转换操作 (Transformations)。这些转换操作&#xff08;如 map(), filter(), reduceByKey() 等&#xff…

关于阿里云-云消息队列MQTT的连接和使用,以及SpringBoot的集成使用

一、目的 本文主要记录物联网设备接入MQTT以及对接服务端SpringBoot整个的交互流程和使用。 二、概念 2.1什么是MQTT? MQTT是基于TCP/IP协议栈构建的异步通信消息协议&#xff0c;是一种轻量级的发布、订阅信息传输协议。可以在不可靠的网络环境中进行扩展&#xff0c;适用…

车载功能框架 --- 整车安全策略

我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 简单,单纯,喜欢独处,独来独往,不易合同频过着接地气的生活,除了生存温饱问题之外,没有什么过多的欲望,表面看起来很高冷,内心热情,如果你身…

HarmonyOS5 让 React Native 应用支持 HarmonyOS 分布式能力:跨设备组件开发指南

以下是 HarmonyOS 5 与 React Native 融合实现跨设备组件的完整开发指南&#xff0c;综合关键技术与实操步骤&#xff1a; 一、分布式能力核心架构 React Native JS 层 → Native 桥接层 → HarmonyOS 分布式能力层(JavaScript) (ArkTS封装) (设备发现/数据同步/硬件…

Unity打包到微信小程序的问题

GUI Error: Invalid GUILayout state in FlowchartWindow view. Verify that all layout Begin/End calls match UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) 第一个问题可以不用管&#xff0c;这个不影响&#xff0c;这个错误&#xff0c;但是可以正常运行&a…

Hugging face 和 魔搭

都是知名的模型平台&#xff0c;二者在定位、功能、生态等方面存在区别&#xff0c;具体如下&#xff1a; 一、定位与背景 Hugging Face&#xff1a; 定位是以自然语言处理&#xff08;NLP&#xff09;为核心发展起来的开源模型平台&#xff0c;后续逐步拓展到文本、音频、图…

React 第六十一节 Router 中 createMemoryRouter的使用详解及案例注意事项

前言 createMemoryRouter 是 React Router 提供的一种特殊路由器,它将路由状态存储在内存中而不是浏览器的 URL 地址栏中。 这种路由方式特别适用于测试、非浏览器环境(如 React Native)以及需要完全控制路由历史的场景。 一、createMemoryRouter 的主要用途 测试环境:在…

透视黄金窗口:中国有机杂粮的高质量跃迁路径

一、行业概览&#xff1a;蓝海市场背后的结构性红利 伴随全民健康意识提升和中产阶层的扩大&#xff0c;中国有机杂粮市场正迎来新一轮结构性红利期。根据《健康中国3.0时代&#xff1a;粗粮食品消费新趋势与市场增长极》数据显示&#xff0c;2020 年中国有机杂粮市场规模约 3…

实现p2p的webrtc-srs版本

1. 基本知识 1.1 webrtc 一、WebRTC的本质&#xff1a;实时通信的“网络协议栈”类比 将WebRTC类比为Linux网络协议栈极具洞察力&#xff0c;二者在架构设计和功能定位上高度相似&#xff1a; 分层协议栈架构 Linux网络协议栈&#xff1a;从底层物理层到应用层&#xff08;如…

OpenCV CUDA模块图像变形------对图像进行上采样操作函数pyrUp()

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 函数用于对图像进行 上采样操作&#xff08;升采样&#xff09;&#xff0c;是 GPU 加速版本的 高斯金字塔向上采样&#xff08;Gaussian Pyrami…

勒贝格测度、勒贝格积分

又要接触测度论了。随着随机规划的不断深入&#xff0c;如果涉及到证明部分&#xff0c;测度论的知识几乎不可或缺。 测度论的相关书籍&#xff0c;基本都非常艰涩难读&#xff0c;对于非数学专业出身的人入门非常不易。从十几年前开始&#xff0c;我很难把测度论教材看到超过…

UE5 学习系列(一)创建一个游戏工程

这个系类笔记用来记录学习 UE 过程中遇到的一些问题与解决方案。整个博客的动机是在使用 AirSim 中遇到了不少性能瓶颈&#xff0c;因此想要系统性地去学一下 UE &#xff0c;这个系列博客主要是跟着 B 站大佬 欧酱&#xff5e; 和 GenJi是真想教会你 的系列视频 《500 分钟学会…

Nginx 负载均衡、高可用及动静分离

Nginx 负载均衡、高可用及动静分离深度实践与原理剖析 在互联网应用架构不断演进的今天&#xff0c;如何高效地处理大量用户请求、保障服务的稳定性与性能&#xff0c;成为开发者和运维人员面临的关键挑战。Nginx 作为一款高性能的 Web 服务器和反向代理服务器&#xff0c;凭借…