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.pswp.cn/bicheng/84877.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/84877.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/84877.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋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;憑借…