springAI Alibaba Agent Framework 实战:快速使用

目录

什么是agent?

两种主流工作模式:

1.WorkFlow(工作流)

2.agentic(智能体自驱)

[spring ai alibaba agent framework](#spring ai alibaba agent framework)

[Chain Workflow 工作流实战](#Chain Workflow 工作流实战)

链式工作流 (PracticalChainWorkflow)

[利用spring ai实现整个流程:](#利用spring ai实现整个流程:)

缺点:

[引入Spring AI Alibaba Agent Framework](#引入Spring AI Alibaba Agent Framework)

ReactAgent集成

[Sequential Agent (多智能体流水线)](#Sequential Agent (多智能体流水线))

状态图工作流 (StateGraph)

定义

代码

1.ReactAgent

[2.状态合并策略 KeyStrategy](#2.状态合并策略 KeyStrategy)

[3.建图:节点 + 边](#3.建图:节点 + 边)

[Graph 的核心价值](#Graph 的核心价值)


什么是agent?

agent=感知+大脑+规划+计划+反馈

两种主流工作模式:

1.WorkFlow(工作流)

核心逻辑:SOP标准作业程序

框架:Spring AI Alibaba

底层机制:确定性的有向无环图与状态机

特点:像画流程图一样,把每一步都规定死。

适用:银行审批、售后工单等企业级业务。(企业下的垂直型)

2.agentic(智能体自驱)

核 心 逻 辑 : 目标驱动 (Goal-Driven)。

框 架 **:**AgentScope-Java

底层机制:以ReAct框架为核心,基于总目标和工具库的自主决策

特点:只给目标,不给步骤。AI 自主思考:"我得先查A,再做B"。

spring ai alibaba agent framework

Chain Workflow 工作流实战

模拟软件项目的完整流程:需求分析 → 架构设计 → 实施计划 → 代码开发

链式工作流 (PracticalChainWorkflow)

利用spring ai实现整个流程:

java 复制代码
public class PracticalChainWorkflow {
      
    private final ChatClient chatClient;
      
    // 实战场景的中文提示词  
    private static final String REQUIREMENT_ANALYSIS_PROMPT = """  
        你是一个资深的需求分析师,请分析以下业务需求:  
          
        需求描述: {input}  
          
        请从以下角度进行分析:  
        1. 核心业务目标  
        2. 主要功能模块  
        3. 技术难点识别  
        4. 风险评估  
          
        如果需求无法实现直接回复"FAIL"。  
        """;  
      
    private static final String ARCHITECTURE_DESIGN_PROMPT = """  
        你是一个系统架构师,基于以下需求分析,设计系统架构:  
          
        需求分析: {input}  
          
        请设计:  
        1. 系统整体架构  
        2. 技术栈选择  
        3. 数据库设计要点  
        4. 接口设计规范  
        5. 部署架构建议  
          
        请提供完整的架构设计方案。  
        """;  
      
    private static final String IMPLEMENTATION_PLAN_PROMPT = """  
        你是一个项目经理,基于以下架构设计,制定实施计划:  
          
        架构设计: {input}  
          
        请制定:  
        1. 开发阶段划分  
        2. 人员配置建议  
        3. 时间节点规划  
        4. 质量保证措施  
        5. 风险应对策略  
          
        请提供详细的项目实施计划。  
        """;  
      
    private static final String DELIVERY_CHECKLIST_PROMPT = """  
        你是一个交付经理,基于以下实施计划,制定交付清单:  
          
        实施计划: {input}  
          
        请制定:  
        1. 开发完成标准  
        2. 测试验收标准  
        3. 部署上线清单  
        4. 运维监控要求  
        5. 用户培训计划  
          
        请以清晰的表格形式输出交付清单。  
        """;  
      
    public PracticalChainWorkflow(ChatClient chatClient) {  
        this.chatClient = chatClient;  
    }  
      
    public void process(String businessRequirement) {
        List<String> processSteps = new ArrayList<>();
        String currentOutput = businessRequirement;  
          
        System.out.println("=== 开始项目全流程处理 ===");  
          
        // 步骤1: 需求分析  
        System.out.println("步骤1: 业务需求分析");
        // 请求大模型
        String currentOutput1 = chatClient.prompt()
            .user(u -> u.text(REQUIREMENT_ANALYSIS_PROMPT).param("input", currentOutput))
            .call()  
            .content();

        System.out.println("【步骤1模型原始输出】:\n" + currentOutput1);

        // ==== Gate 逻辑 ====
        if (currentOutput1 == null || currentOutput1.trim().equalsIgnoreCase("FAIL")) {
            System.out.println("【流程终止】:需求无法实现,流程提前退出。");
            return; // 提前返回,不进行后续步骤
        }
        System.out.println("需求分析完成:"+currentOutput1);
        // 步骤2: 架构设计  
        System.out.println("步骤2: 系统架构设计");
        String currentOutput2 = chatClient.prompt()
            .user(u -> u.text(ARCHITECTURE_DESIGN_PROMPT).param("input", currentOutput1))
            .call()  
            .content();
        System.out.println("架构设计完成:"+currentOutput2);
          
        // 步骤3: 实施计划  
        System.out.println("步骤3: 项目实施规划");
        String currentOutput3 = chatClient.prompt()
            .user(u -> u.text(IMPLEMENTATION_PLAN_PROMPT).param("input", currentOutput2))
            .call()  
            .content();
        System.out.println("实施计划完成:"+currentOutput3);
          
        // 步骤4: 交付清单  
        System.out.println("步骤4: 交付清单制定");
        String currentOutput4 = chatClient.prompt()
            .user(u -> u.text(DELIVERY_CHECKLIST_PROMPT).param("input", currentOutput3))
            .call()  
            .content();
        System.out.println("交付清单完成:"+currentOutput4);
          
        System.out.println("=== 项目全流程处理完成 ===");  

    }  
      
    public record ProjectDeliverable(String finalDeliverable, List<String> processSteps) {}  
}

注:PracticalChainWorkflow. 是 Spring AI Alibaba 框架下的一个 链式工作流(Chain Workflow)类。它模拟了一个软件项目从"业务需求"到"最终交付清单"的完整处理流程,通过 串联调用大模型 4 次,每次的输出作为下一次的输入,形成一条顺序依赖的推理链(Sequential Chain)。

缺点:

  1. 流程越多,代码将越多,不可维护
  2. 缺乏自主决策:流程决策权锁死在Java的if/else中,大模型知识被动调用的工具。
  3. 手动搬运:上下文必须由程序员显示传递

引入Spring AI Alibaba Agent Framework

ReactAgent集成

代码思维从"面向过程"升级为"面向专家角色 (Persona)"。

java 复制代码
          ReactAgent implementationAgent = ReactAgent.builder()
                .name("implementation_agent")
                .model(chatModel)
                .instruction("""  
        你是一个项目经理,基于以下架构设计,制定实施计划:  
        架构设计: {architecture_design}  
        请制定:  
        1. 开发阶段划分  
        2. 人员配置建议  
        3. 时间节点规划  
        4. 质量保证措施  
        5. 风险应对策略  
        请提供详细的项目实施计划。  
        """)
                .outputKey("implementation_plan")
                .build();

        // 4. Java高级开发角色(替换原交付经理)
        ReactAgent developerAgent = ReactAgent.builder()
                .name("developer_agent")
                .model(chatModel)
                .tools(
                        WriteFileTool.createWriteFileToolCallback(WriteFileTool.DESCRIPTION),
                        ReadFileTool.createReadFileToolCallback(ReadFileTool.DESCRIPTION),
                        ListFilesTool.createListFilesToolCallback(ListFilesTool.DESCRIPTION)

                )
                .instruction("""  
        你是一个Java高级开发工程师,基于前序的架构设计和实施计划,负责核心代码的编写:  
        架构设计: {architecture_design}
        实施计划: {implementation_plan}  
        
        请完成以下开发任务:  
        1. 核心业务的数据库实体类 (Entity / DO) 设计
        2. 核心业务逻辑接口 (Service) 与实现类 (ServiceImpl) 编写
        3. RESTful API 控制器 (Controller) 编写
        4. 关键的数据访问层接口 (Mapper / Repository)
        5. 把文件保存在桌面
        
        要求:
        - 遵循 Spring Boot 规范
        - 代码需包含完整的类注释和方法注释
        - 充分考虑异常处理与代码健壮性
        - 直接输出高质量、可参考的 Java 源代码@
        """)
                .outputKey("java_code")
                .build();

注:一个reactAgent就是一个专家角色,re =resoning 思考 、at=action 行动,name设置为该reactAgent的名字,outputKey(产出写入状态变量的键),多个带角色提示词的 ReactAgent 通过 outputKey + {占位符} 在共享状态 OverAllState 上链式传递数据,tool即注册工具,模型可以在推理过程中自主调用工具。

Sequential Agent (多智能体流水线)

java 复制代码
// 顺序执行多agent
        SequentialAgent workflow = SequentialAgent.builder()
                .name("project_workflow")
                .description("项目全流程:需求分析→架构设计→实施计划→交付清单")
                .subAgents(List.of(
                        requirementAgent,
                        architectureAgent,
                        implementationAgent,
                        developerAgent
                ))
                // agent执行前后进行增强
                .hooks(
                        // 在第一个Agent执行后检查是否FAIL,若FAIL则终止
                        new AgentHook() {
                            @Override
                            public String getName() {
                                return null;
                            }


                            @Override
                            public CompletableFuture<Map<String, Object>> afterAgent(OverAllState state, RunnableConfig config) {
                                state.value("requirement_agent")
                                        .map(Object::toString)
                                        .ifPresent(content -> {
                                            if (content.contains("FAIL")) {
                                                throw new RuntimeException("需求无法实现,流程终止");
                                            }
                                        });
                                return CompletableFuture.completedFuture(Map.of());
                            }
                        }
                )
                .build();

注:SequentialAgent 把多个子 Agent 按顺序串成一个流程。

Hook 增强:注册了一个 AgentHook,在 Agent 执行后(afterAgent)做校验------从状态中取需求分析结果,如果内容包含 "FAIL"(对应需求分析师指令中"需求无法实现直接回复 FAIL"),就抛异常熔断整个流程,避免无效地继续跑后面三个 Agent。这是一个"失败快速退出"的质量门禁设计。

缺点:当业务极其复杂时,缺乏动态编排的灵活性。框架提供的都是"预设好的固定拓扑,但真实业务往往会很复杂,不会安预先的格式组装。所以需要动态编排能力。

状态图工作流 (StateGraph)

定义

为了实现完全自定义的动态编排 ,我们直接使用 Spring AI Alibaba 的物理引擎底座------Graph Runtime。把流程图中的"圆圈"变成 Node,"黑线"变成 Edge。

Graph 是 Agent Framework 的底层运行时(实际上Agent Framework底层也会最终解析为Graph),Graph 是一个更底层的工作流和多智能体编排框架,使开发者能够实现复杂的应用程序编排。

  • 状态(State):在 Node 与 Edge 之间传递数据,是整个 Agent 上下文传递数据的载体,具体实现上是一个 Map<String, Object>。
  • 节点(Node):Node 是执行具体逻辑的单元,接受当前 State 作为输入,执行某些操作(如调用 LLM 或自定义逻辑),并返回传递到下一个Node的 State 数据。
  • 边(Edge):定义一个Node到下一个Node的连接。可为固定连接(普通边),也可依据状态条件动态决定下一步执行路径(条件边)

代码

1.ReactAgent

java 复制代码
ReactAgent requirementAgent = ReactAgent.builder()
        .name("requirement")            // 节点唯一名(后续 addEdge 用它引用)
        .model(chatModel)               // 底层大模型(DashScope 通义千问)
        .instruction("""...{input}...""") // 提示词模板,{xxx} 是状态占位符
        .outputKey("requirement_analysis") // 执行结果写回状态的 key
        .build();

注:一个专家角色 = 一个节点

2.状态合并策略 KeyStrategy

StateGraph 允许多节点写同一个 key,冲突时怎么合并由策略决定:

java 复制代码
/*
        AppendStrategy: 状态值为字符串类型时,将新状态值追加到旧状态值的末尾
        ReplaceStrategy: 状态值为字符串类型时,将新状态值替换旧状态值
        */
        KeyStrategyFactory keyStrategyFactory = () -> {
            Map<String, KeyStrategy> map = new HashMap<>();
            map.put("message", new AppendStrategy());
            map.put("requirement_analysis", new ReplaceStrategy());
            map.put("architecture_design", new ReplaceStrategy());
            map.put("implementation_plan", new ReplaceStrategy());
            map.put("delivery_checklist", new ReplaceStrategy());
            return map;
        };

注:KeyStrategyFactory 是个工厂 lambda,StateGraph 据此初始化全局状态容器

3.建图:节点 + 边

java 复制代码
return new StateGraph("project_workflow", keyStrategyFactory)
             // 1) 注册节点:asNode(true, false)  表示该节点产出进入状态
                .addNode(requirementAgent.name(), requirementAgent.asNode(true, false))
                .addNode(architectureAgent.name(),  architectureAgent.asNode(true,false))
                .addNode(implementationAgent.name(),  implementationAgent.asNode(true,false))
                .addNode(deliveryAgent.name(),  deliveryAgent.asNode(true,false))
              // 2) 入口边
                .addEdge(StateGraph.START,"requirement")
              // 3) 条件边(Gate:FAIL 则终止)
                /*
                 requirement 节点执行完
                       ↓
                 执行 edge_async 判断逻辑 → 得到字符串 "to_architecture"
                       ↓
                 拿 "to_architecture" 去映射表查 value → 得到 "architecture"
                       ↓
                 在图的节点列表中找名为 "architecture" 的节点 → 调度执行它
                 */
                .addConditionalEdges("requirement",
                        AsyncEdgeActionWithConfig.edge_async((state, runnableConfig) ->
                                state.value("requirement_analysis", String.class)
                                        .map(s -> s.contains("FAIL") ? "END" : "to_architecture")
                                        .orElse("to_architecture")),
                        Map.of("to_architecture", "architecture", "END", END)
                //该值是路由映射表,Map.of(key,value, , ) key:路由名 value;目标节点名
                      )
               //    // 4) 顺序边
                .addEdge("architecture", "implementation")
                .addEdge("implementation", "delivery")
                .addEdge("delivery", END);

Graph 的核心价值

  1. 任意拓扑的动态编排 :无论是 if/else 分支,还是打回重做的 while 有向循环,图引擎都能通过 Edge 轻松承载。你画得出图,它就写得出代码!(甚至通过UI编排后动态解析流程)
  2. 状态自动托管 (State Management) :通过 KeyStrategyFactory 精确控制状态是"追加"还是"替换"。引擎像传送带一样自动带着上下文流转。
  3. 可视化与代码完美同构:你在业务架构会上画出的白板图,直接 1:1 无损翻译成底层代码。代码即流程图。
相关推荐
Flynn Liang5 小时前
Spring AI ChatClient 详解:system/user/assistant 角色、call 与 stream 到底怎么选
java·人工智能·spring·springai·流式输出·chatclient·java接入大模型
Flynn Liang10 小时前
保姆级|Spring AI 2.0 第一个 Demo:Spring Boot 4 接入大模型(含国内可用方案 + 完整 pom)
人工智能·spring·ollama·springai·deepseek·springai入门·java接入大模型
ZealSinger12 天前
SpringAI的MCP改STREAMABLE怎么配
协议·springai·mcp·streamable
鱼宵12 天前
Spring AI RAG 问答助手:回答带引用,AI 不再睁眼说瞎话
java·人工智能·spring·springai
云和数据.ChenGuang14 天前
用 Claude Code 重构遗留系统:从评估到落地的完整指南
java·人工智能·spring boot·后端·重构·springai
鱼宵17 天前
Spring AI 可观测与透明化:traceId 串起全链路,思考过程实时直播给用户
java·人工智能·spring·链路追踪·springai
Joy T18 天前
Spring AI 接入已有 Java 项目的三种架构设计
java·人工智能·springai·ai入门·chatclient·ai service·ai能力接入
鱼宵18 天前
Spring AI 流式输出:Flux + SSE 打字机,回答不再干等三秒
java·人工智能·spring·sse·springai·流式输出
鱼宵18 天前
Spring AI 生产化改造:记忆落 Redis、向量落 ES,重启再也不丢
人工智能·redis·spring·elasticsearch·springai