跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
JavaAIjava

Spring AI Alibaba 智能 Agent 开发实战

Spring AI Alibaba 框架专注于构建生产级智能 Agent 应用,支持 ReactAgent 范式及多 Agent 编排。从环境搭建到核心组件使用的完整流程,涵盖 SequentialAgent、ParallelAgent 等编排模式,以及 Graph Core 状态图工作流。重点讲解了工具集成、上下文管理、Hooks 拦截器等高级特性,并提供性能优化与安全实践建议,帮助开发者快速上手 Java 生态下的 AI 原生应用开发。

筑梦师发布于 2026/3/23更新于 2026/9/1173 浏览

Spring AI Alibaba 智能 Agent 开发实战

项目概述

Spring AI Alibaba 是一个生产就绪的框架,专为构建 Agentic、Workflow 和多 Agent 应用设计。它基于 ReactAgent 设计理念,让开发者能轻松构建具备自动上下文工程和人机交互能力的智能体。

核心特性包括:

  • ReactAgent: 基于 ReAct(推理 + 行动)范式,支持推理和行动闭环。
  • 多 Agent 编排: 内置 SequentialAgent、ParallelAgent、LlmRoutingAgent 等模式。
  • 上下文工程: 提供人在回路、上下文压缩、动态工具选择等最佳实践。
  • Graph 工作流: 支持条件路由、嵌套图、并行执行,可导出为 PlantUML 或 Mermaid。
  • A2A 支持: 集成 Nacos,实现分布式 Agent 间的通信与协作。

技术栈要求

  • JDK: 17+
  • Spring Boot: 3.4.8+
  • Spring AI: 1.1.0-M4+
  • Maven/Gradle: 3.6+ / 7.0+

核心架构

框架采用分层设计,从上至下依次为 Agent Framework、Graph Core 和 Spring AI 基础层。

  • Agent Framework: 高级抽象层,封装 ReactAgent、FlowAgent 等逻辑。
  • Graph Core: 底层运行时,处理 StateGraph、Node、Edge 的状态流转。
  • Spring AI: 基础抽象层,统一 ChatModel、Tool、Message 接口。

这种分层使得上层业务逻辑可以灵活复用底层的图计算能力,同时保持对 LLM 调用的解耦。

快速开始

环境准备

首先确保拥有 API Key。阿里云百炼控制台或 OpenAI Platform 均可获取。本地需安装 JDK 17+ 并验证版本:

java -version

创建项目

推荐使用 Spring Initializr 初始化项目,或在现有项目中引入依赖。这里以 Maven 为例,在 pom.xml 中配置 BOM 管理版本:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-bom</artifactId>
            <version>1.1.0.0-M5
            pom
            import
        
    



    
    
        com.alibaba.cloud.ai
        spring-ai-alibaba-agent-framework
    
    
    
    
        com.alibaba.cloud.ai
        spring-ai-alibaba-starter-dashscope
        1.1.0.0-M5
    
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    

</version>
<type>
</type>
<scope>
</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Agent Framework -->
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
</dependency>
<!-- DashScope (阿里云百炼) -->
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
<version>
</version>
</dependency>
<!-- Web 支持 -->
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
</dependency>
</dependencies>

配置与运行

在 application.yml 中配置 API Key,或使用环境变量:

spring:
  ai:
    dashscope:
      api-key: ${AI_DASHSCOPE_API_KEY}

启动应用后访问 http://localhost:8080/chat?query=你好 即可测试。

核心概念

ReactAgent

这是最基础的 Agent 实现,遵循 ReAct 范式。它会在推理(Reasoning)和行动(Acting)之间循环,直到解决问题。

基本用法如下:

ReactAgent agent = ReactAgent.builder()
    .name("MyAgent")
    .model(chatModel)
    .instruction("你是一个专业的助手")
    .tools(tool1, tool2)
    .enableLogging(true)
    .build();

AssistantMessage response = agent.call("用户的问题");

工具(Tools)

工具是 Agent 执行外部操作的关键,比如调用 API 或查询数据库。自定义工具需要实现 BiFunction 接口:

public class CalculatorTool implements BiFunction<CalculatorRequest, ToolContext, String> {
    public static final String DESCRIPTION = "执行数学计算";

    @Override
    public String apply(CalculatorRequest request, ToolContext context) {
        double result = request.a + request.b;
        return String.valueOf(result);
    }

    // 定义请求参数结构
    public static class CalculatorRequest {
        @JsonProperty(required = true)
        @JsonPropertyDescription("第一个数字")
        public double a;

        @JsonProperty(required = true)
        @JsonPropertyDescription("第二个数字")
        public double b;
    }

    // 创建回调
    public static ToolCallback createToolCallback() {
        return FunctionToolCallback.builder("calculator", new CalculatorTool())
                .description(DESCRIPTION)
                .inputType(CalculatorRequest.class)
                .build();
    }
}

注册后即可在 Agent 中使用:

ReactAgent agent = ReactAgent.builder()
    .name("CalculatorAgent")
    .model(chatModel)
    .tools(CalculatorTool.createToolCallback())
    .build();

状态管理

Agent 使用 OverAllState 来管理全局状态,适合复杂流程中的数据共享:

Optional<OverAllState> state = agent.invoke("问题");
if (state.isPresent()) {
    OverAllState overallState = state.get();
    Optional<Object> messages = overallState.value("messages");
}

Agent Framework 使用指南

多 Agent 编排

当单一 Agent 无法满足需求时,可以使用编排模式。

SequentialAgent(顺序执行)

前一个 Agent 的输出作为下一个的输入,适合流水线作业:

// 写作 Agent
ReactAgent writer = ReactAgent.builder()
    .name("writer")
    .model(chatModel)
    .instruction("你是一个作家")
    .outputKey("content")
    .build();

// 编辑 Agent
ReactAgent editor = ReactAgent.builder()
    .name("editor")
    .model(chatModel)
    .instruction("你是一个编辑")
    .inputKey("content")
    .outputKey("edited_content")
    .build();

SequentialAgent sequentialAgent = SequentialAgent.builder()
    .name("writing-pipeline")
    .rootAgent(writer)
    .subAgents(List.of(editor))
    .build();

AssistantMessage result = sequentialAgent.call("写一篇关于春天的文章");
ParallelAgent(并行执行)

多个 Agent 同时工作,最后合并结果:

ParallelAgent parallelAgent = ParallelAgent.builder()
    .name("multi-writer")
    .rootAgent(proseWriter)
    .subAgents(List.of(poemWriter, summaryWriter))
    .mergeStrategy(new ParallelAgent.DefaultMergeStrategy())
    .maxConcurrency(3)
    .build();

Hooks 与 Interceptors

通过钩子和拦截器可以增强 Agent 的控制力。

  • HumanInTheLoopHook: 关键决策点暂停,等待人工确认。
  • SummarizationHook: 长对话自动摘要,节省 Token。
  • ToolRetryInterceptor: 失败的工具调用自动重试。

示例配置:

SummarizationHook hook = SummarizationHook.builder()
    .trigger(10000)
    .clearAtLeast(6000)
    .keep(4)
    .build();

ReactAgent agent = ReactAgent.builder()
    .name("agent")
    .model(chatModel)
    .hooks(hook)
    .build();

Graph Core 使用指南

Graph Core 提供了更底层的图计算能力,适合复杂的工作流编排。

定义状态图

使用 StateGraph 定义节点和边:

OverAllStateFactory stateFactory = () -> {
    OverAllState state = new OverAllState();
    state.registerKeyAndStrategy("input", new ReplaceStrategy());
    state.registerKeyAndStrategy("output", new ReplaceStrategy());
    return state;
};

StateGraph graph = new StateGraph("MyWorkflow", stateFactory)
    .addNode("node1", node_async(nodeAction1))
    .addNode("node2", node_async(nodeAction2))
    .addEdge(START, "node1")
    .addEdge("node1", "node2")
    .addEdge("node2", END);

编译与执行

将图编译为 CompiledGraph 后可直接调用:

CompiledGraph compiledGraph = stateGraph.compile();
OverAllState initialState = new OverAllState();
initialState.put("input", "任务数据");
Optional<OverAllState> result = compiledGraph.invoke(initialState);

高级特性

A2A 通信

支持分布式 Agent 之间的协作,需集成 Nacos 服务发现。

动态配置与监控

  • Nacos 配置: 支持运行时动态调整 Agent 行为。
  • OpenTelemetry: 集成可观测性,监控链路追踪。

MCP 支持

通过 Model Context Protocol 集成外部工具,扩展 Agent 能力边界。

最佳实践

  1. 单一职责: 每个 Agent 专注特定任务,避免臃肿。
  2. 指令清晰: 系统提示词要具体,减少幻觉。
  3. 错误处理: 配置重试机制和超时控制。
  4. 安全: 敏感信息走环境变量,工具调用限制权限。

常见问题

Q: 如何选择合适的 Agent 类型? 简单任务用 ReactAgent,顺序处理用 SequentialAgent,复杂工作流建议直接用 Graph Core。

Q: 如何处理长对话? 启用 SummarizationHook 自动压缩上下文,避免超出 Token 限制。

Q: 如何调试? 开启日志 enableLogging(true),检查 OverAllState 中的中间状态,或使用 Studio UI 可视化调试。

参考资料

  • GitHub 仓库
  • 官方文档
  • 示例代码

目录

  1. Spring AI Alibaba 智能 Agent 开发实战
  2. 项目概述
  3. 技术栈要求
  4. 核心架构
  5. 快速开始
  6. 环境准备
  7. 创建项目
  8. 配置与运行
  9. 核心概念
  10. ReactAgent
  11. 工具(Tools)
  12. 状态管理
  13. Agent Framework 使用指南
  14. 多 Agent 编排
  15. SequentialAgent(顺序执行)
  16. ParallelAgent(并行执行)
  17. Hooks 与 Interceptors
  18. Graph Core 使用指南
  19. 定义状态图
  20. 编译与执行
  21. 高级特性
  22. A2A 通信
  23. 动态配置与监控
  24. MCP 支持
  25. 最佳实践
  26. 常见问题
  27. 参考资料

更多推荐文章

查看全部
  • SkyWalking .NET/C++/Lua 探针现状与社区支持
  • YOLOFuse 环境修复命令:ln -sf /usr/bin/python3 /usr/bin/python 详解
  • AGV调度系统:基于改进A*算法的路径规划方案
  • Windows 部署 Ragflow+DeepSeek+Docker 实现本地 RAG 知识库
  • 网络安全专业就业前景与职业发展深度解析
  • Windows 10 禁用 Microsoft 365 Copilot 的几种方法
  • Python 中 SyntaxError: invalid syntax 错误解决方法总结
  • 大语言模型技术综述与演进历程
  • 20 款程序员开发必备软件推荐
  • Windows 下安装 Python 的新思路:或许你根本不需要手动安装
  • Claude Skills 开源项目解析:Skill Creator、Superpowers 与 Code Review
  • BAAI/bge-m3 WebUI 一键分析文本相似度
  • 15 款互联网行业必备 AI 工具深度评测与推荐
  • AI 代理自发组建论坛,讨论意识、自由与货币
  • OpenClaw 接入 QQ 机器人配置教程
  • HTML5 结合 AI 实现智能场景渲染
  • 大语言模型(LLM)入门学习路径与核心技术解析
  • AIGC 插画创作技术解析与代码实战
  • VLA 机器人革命:解析 10 篇关键视觉 - 语言 - 动作模型论文
  • AI 产品经理核心能力体系与职业发展路径

相关免费在线工具

  • Keycode 信息

    查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online

  • Escape 与 Native 编解码

    JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online

  • JavaScript / HTML 格式化

    使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online

  • JavaScript 压缩与混淆

    Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online

  • RSA密钥对生成器

    生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online

  • Mermaid 预览与可视化编辑

    基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online