Spring AI Alibaba:智能Agent开发实战指南
Spring AI Alibaba 学习使用文档
目录
1. 项目概述
1.1 什么是 Spring AI Alibaba
Spring AI Alibaba 是一个生产就绪的框架,用于构建 Agentic、Workflow 和多 Agent 应用。该框架基于 ReactAgent 设计理念,使开发者能够构建具有自动上下文工程和**人在回路(Human In The Loop)**交互能力的智能 Agent。
1.2 核心特性
- ReactAgent: 基于 ReAct(Reasoning + Acting)范式的智能 Agent,支持推理和行动能力
- 多 Agent 编排: 内置
SequentialAgent、ParallelAgent、LlmRoutingAgent、LoopAgent等模式 - 上下文工程: 内置最佳实践策略,包括人在回路、上下文压缩、上下文编辑、模型和工具调用限制、工具重试、规划、动态工具选择等
- 基于 Graph 的工作流: 支持条件路由、嵌套图、并行执行和状态管理,可导出为 PlantUML 和 Mermaid 格式
- A2A 支持: Agent-to-Agent 通信支持,集成 Nacos,实现分布式 Agent 协调和协作
- 丰富的模型、工具和 MCP 支持: 支持多种 LLM 提供商(DashScope、OpenAI 等)、工具调用和模型上下文协议(MCP)
1.3 项目结构
Spring AI Alibaba 采用多模块 Maven 项目结构:
spring-ai-alibaba/ ├── spring-ai-alibaba-bom/ # BOM 模块,统一管理依赖版本 ├── spring-ai-alibaba-graph-core/ # Graph 核心运行时 ├── spring-ai-alibaba-agent-framework/ # Agent 框架 ├── spring-ai-alibaba-studio/ # Studio 应用(可视化界面) ├── spring-boot-starters/ # Spring Boot Starters │ ├── spring-ai-alibaba-starter-a2a-nacos/ │ ├── spring-ai-alibaba-starter-config-nacos/ │ └── spring-ai-alibaba-starter-graph-observation/ └── examples/ # 示例代码 ├── chatbot/ # ChatBot 示例 ├── deepresearch/ # DeepResearch 示例 └── documentation/ # 文档示例 1.4 技术栈要求
- JDK: 17 或更高版本
- Spring Boot: 3.4.8 或更高版本
- Spring AI: 1.1.0-M4 或更高版本
- Maven: 3.6+ 或 Gradle 7.0+
2. 核心架构
2.1 架构图
Spring AI Alibaba 采用分层架构设计:
┌─────────────────────────────────────────────────┐ │ Agent Framework (高级抽象层) │ │ ReactAgent, SequentialAgent, ParallelAgent │ └─────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────┐ │ Graph Core (工作流运行时) │ │ StateGraph, Node, Edge, OverAllState │ └─────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────┐ │ Spring AI (基础抽象层) │ │ ChatModel, Tool, Message, MCP │ └─────────────────────────────────────────────────┘ 2.2 核心组件
2.2.1 Agent Framework
Agent Framework 是高级抽象层,提供:
- ReactAgent: 单 Agent 实现,支持 ReAct 循环
- FlowAgent: 多 Agent 编排基类
SequentialAgent: 顺序执行多个 AgentParallelAgent: 并行执行多个 AgentLlmRoutingAgent: 基于 LLM 的路由 AgentLoopAgent: 循环执行 Agent
2.2.2 Graph Core
Graph Core 是底层工作流运行时,提供:
- StateGraph: 状态图定义,用于定义节点和边
- Node: 节点,封装特定操作或模型调用
- Edge: 边,表示节点之间的转换
- OverAllState: 全局状态,在整个流程中携带共享数据
- CompiledGraph: 可执行图,处理实际执行、状态转换和结果流式传输
3. 快速开始
3.1 环境准备
- 获取 API Key
- DashScope (阿里云百炼): 访问 阿里云百炼控制台
- OpenAI: 访问 OpenAI Platform
安装 JDK 17+
java -version 3.2 创建项目
方式一:使用示例项目
# 克隆仓库git clone https://github.com/alibaba/spring-ai-alibaba.git cd spring-ai-alibaba/examples/chatbot 方式二:创建新项目
- 创建 Spring Boot 项目(使用 Spring Initializr 或 IDE)
- 添加依赖到
pom.xml:
<dependencyManagement><dependencies><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-bom</artifactId><version>1.1.0.0-M5</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><!-- Agent Framework --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-agent-framework</artifactId></dependency><!-- 选择模型提供商 --><!-- DashScope (阿里云百炼) --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-dashscope</artifactId><version>1.1.0.0-M5</version></dependency><!-- 或 OpenAI --><!-- <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai-spring-boot-starter</artifactId> </dependency> --><!-- Spring Boot Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>3.3 配置 API Key
在 application.yml 或环境变量中配置:
spring:ai:dashscope:api-key: ${AI_DASHSCOPE_API_KEY}或使用环境变量:
exportAI_DASHSCOPE_API_KEY=your-api-key 3.4 创建第一个 Agent
@ConfigurationpublicclassAgentConfig{@BeanpublicReactAgentchatBotAgent(ChatModel chatModel){returnReactAgent.builder().name("ChatBot").model(chatModel).instruction("你是一个友好的AI助手,能够回答用户的问题。").enableLogging(true).build();}}3.5 使用 Agent
@RestControllerpublicclassChatController{@AutowiredprivateReactAgent chatBotAgent;@GetMapping("/chat")publicStringchat(@RequestParamString query){AssistantMessage response = chatBotAgent.call(query);return response.getContent();}}3.6 运行应用
mvn spring-boot:run 访问 http://localhost:8080/chat?query=你好 进行测试。
4. 核心概念
4.1 ReactAgent
ReactAgent 是 Spring AI Alibaba 的核心 Agent 实现,基于 ReAct(Reasoning + Acting)范式:
- Reasoning(推理): Agent 分析问题并制定计划
- Acting(行动): Agent 执行工具调用获取信息
- 循环迭代: 推理和行动交替进行,直到解决问题
基本用法
ReactAgent agent =ReactAgent.builder().name("MyAgent").model(chatModel).instruction("你是一个专业的助手").tools(tool1, tool2, tool3)// 可选:添加工具.enableLogging(true)// 可选:启用日志.build();// 调用 AgentAssistantMessage response = agent.call("用户的问题");4.2 工具(Tools)
工具允许 Agent 执行外部操作,如调用 API、执行代码、查询数据库等。
创建自定义工具
publicclassCalculatorToolimplementsBiFunction<CalculatorRequest,ToolContext,String>{publicstaticfinalString DESCRIPTION ="执行数学计算";@OverridepublicStringapply(CalculatorRequest request,ToolContext context){// 实现计算逻辑double result = request.a + request.b;returnString.valueOf(result);}publicstaticclassCalculatorRequest{@JsonProperty(required =true)@JsonPropertyDescription("第一个数字")publicdouble a;@JsonProperty(required =true)@JsonPropertyDescription("第二个数字")publicdouble b;}// 创建 ToolCallbackpublicstaticToolCallbackcreateToolCallback(){returnFunctionToolCallback.builder("calculator",newCalculatorTool()).description(DESCRIPTION).inputType(CalculatorRequest.class).build();}}使用工具
ReactAgent agent =ReactAgent.builder().name("CalculatorAgent").model(chatModel).tools(CalculatorTool.createToolCallback()).build();4.3 消息(Messages)
Spring AI Alibaba 使用 Spring AI 的消息抽象:
- UserMessage: 用户消息
- AssistantMessage: 助手消息
- SystemMessage: 系统消息
- ToolResponseMessage: 工具响应消息
// 使用字符串AssistantMessage response = agent.call("你好");// 使用消息对象UserMessage userMessage =newUserMessage("你好");AssistantMessage response = agent.call(userMessage);4.4 状态管理(State Management)
Agent 使用 OverAllState 管理状态:
// 获取执行后的状态Optional<OverAllState> state = agent.invoke("问题");if(state.isPresent()){OverAllState overallState = state.get();// 访问状态中的数据Optional<Object> messages = overallState.value("messages");}4.5 内存(Memory)
Agent 可以配置内存保存器来持久化对话历史:
ReactAgent agent =ReactAgent.builder().name("AgentWithMemory").model(chatModel).saver(newMemorySaver())// 内存保存器.build();5. Agent Framework 使用指南
5.1 ReactAgent 详解
5.1.1 基本配置
ReactAgent agent =ReactAgent.builder().name("agent-name")// Agent 名称.description("Agent 描述")// Agent 描述.model(chatModel)// 使用的模型.instruction("系统指令")// 系统提示词.systemPrompt("系统提示词")// 或使用 systemPrompt.tools(tool1, tool2)// 工具列表.enableLogging(true)// 启用日志.build();5.1.2 高级配置
ReactAgent agent =ReactAgent.builder().name("AdvancedAgent").model(chatModel).instruction("你是一个专业的助手")// Hooks(钩子).hooks( humanInTheLoopHook,// 人在回路 summarizationHook // 摘要钩子)// Interceptors(拦截器).interceptors( contextEditingInterceptor,// 上下文编辑 toolRetryInterceptor,// 工具重试 toolCallLimitInterceptor // 工具调用限制)// 内存.saver(newMemorySaver())// 输出配置.outputKey("result")// 输出键名.outputKeyStrategy(newReplaceStrategy())// 输出策略.build();5.2 多 Agent 编排
5.2.1 SequentialAgent(顺序 Agent)
顺序执行多个 Agent,前一个 Agent 的输出作为下一个 Agent 的输入:
// 创建子 AgentReactAgent agent1 =ReactAgent.builder().name("writer").model(chatModel).instruction("你是一个作家,负责创作内容").outputKey("content").build();ReactAgent agent2 =ReactAgent.builder().name("editor").model(chatModel).instruction("你是一个编辑,负责修改和优化内容").inputKey("content")// 使用前一个 Agent 的输出.outputKey("edited_content").build();// 创建顺序 AgentSequentialAgent sequentialAgent =SequentialAgent.builder().name("writing-pipeline").description("写作和编辑流水线").rootAgent(agent1)// 根 Agent.subAgents(List.of(agent2))// 子 Agent 列表.build();// 使用AssistantMessage result = sequentialAgent.call("写一篇关于春天的文章");5.2.2 ParallelAgent(并行 Agent)
并行执行多个 Agent,然后合并结果:
// 创建多个专业 AgentReactAgent proseWriter =ReactAgent.builder().name("prose_writer").model(chatModel).instruction("你是一个散文作家").outputKey("prose_result").build();ReactAgent poemWriter =ReactAgent.builder().name("poem_writer").model(chatModel).instruction("你是一个诗人").outputKey("poem_result").build();ReactAgent summaryWriter =ReactAgent.builder().name("summary_writer").model(chatModel).instruction("你是一个总结专家").outputKey("summary_result").build();// 创建并行 AgentParallelAgent parallelAgent =ParallelAgent.builder().name("multi-writer").description("并行执行多个创作任务").rootAgent(proseWriter)// 根 Agent(可选).subAgents(List.of(poemWriter, summaryWriter)).mergeStrategy(newParallelAgent.DefaultMergeStrategy())// 合并策略.maxConcurrency(3)// 最大并发数.build();// 使用AssistantMessage result = parallelAgent.call("以'春天'为主题创作");5.2.3 LlmRoutingAgent(LLM 路由 Agent)
使用 LLM 根据输入动态选择执行哪个 Agent:
// 创建路由 AgentLlmRoutingAgent routingAgent =LlmRoutingAgent.builder().name("router").model(chatModel).instruction("根据用户问题选择合适的 Agent").routeAgents(Map.of("technical", technicalAgent,"creative", creativeAgent,"analytical", analyticalAgent )).build();// 使用AssistantMessage result = routingAgent.call("用户问题");5.2.4 LoopAgent(循环 Agent)
循环执行 Agent 直到满足条件:
LoopAgent loopAgent =LoopAgent.builder().name("loop-agent").model(chatModel).instruction("持续处理任务直到完成").agent(workerAgent).maxIterations(10)// 最大迭代次数.build();5.3 Hooks(钩子)
Hooks 允许在 Agent 执行过程中插入自定义逻辑:
5.3.1 HumanInTheLoopHook(人在回路)
允许在关键决策点暂停,等待人工输入:
HumanInTheLoopHook hook =HumanInTheLoopHook.builder().enabled(true).build();ReactAgent agent =ReactAgent.builder().name("agent").model(chatModel).hooks(hook).build();5.3.2 SummarizationHook(摘要钩子)
自动对长对话进行摘要,减少上下文长度:
SummarizationHook hook =SummarizationHook.builder().trigger(10000)// 触发阈值(字符数).clearAtLeast(6000)// 至少清除的字符数.keep(4)// 保留的消息数.build();5.4 Interceptors(拦截器)
Interceptors 用于拦截和修改 Agent 的行为:
5.4.1 ContextEditingInterceptor(上下文编辑)
允许编辑和修改上下文:
ContextEditingInterceptor interceptor =ContextEditingInterceptor.builder().enabled(true).build();5.4.2 ToolRetryInterceptor(工具重试)
自动重试失败的工具调用:
ToolRetryInterceptor interceptor =ToolRetryInterceptor.builder().maxRetries(3).retryDelay(Duration.ofSeconds(1)).build();5.4.3 ToolCallLimitInterceptor(工具调用限制)
限制工具调用的次数:
ToolCallLimitInterceptor interceptor =ToolCallLimitInterceptor.builder().maxToolCalls(10).build();6. Graph Core 使用指南
6.1 基本概念
Graph Core 是底层工作流运行时,提供更灵活的工作流编排能力。
6.1.1 StateGraph(状态图)
StateGraph 用于定义工作流:
// 创建状态工厂OverAllStateFactory stateFactory =()->{OverAllState state =newOverAllState(); state.registerKeyAndStrategy("input",newReplaceStrategy()); state.registerKeyAndStrategy("output",newReplaceStrategy());return state;};// 创建状态图StateGraph graph =newStateGraph("MyWorkflow", stateFactory).addNode("node1",node_async(nodeAction1)).addNode("node2",node_async(nodeAction2)).addEdge(START,"node1").addEdge("node1","node2").addEdge("node2", END);6.1.2 Node(节点)
节点封装了工作流中的一个步骤:
// 创建节点动作NodeAction nodeAction =(state)->{// 读取输入String input =(String) state.value("input").orElse("");// 处理逻辑String output =process(input);// 写入输出 state.put("output", output);return state;};// 添加到图 graph.addNode("process_node",node_async(nodeAction));6.1.3 Edge(边)
边定义节点之间的转换:
// 简单边 graph.addEdge("node1","node2");// 条件边 graph.addConditionalEdges("node1",edge_async((state)->{// 根据状态决定下一个节点String condition =(String) state.value("condition").orElse("default");return condition;}),Map.of("option1","node2","option2","node3","default","node4"));6.2 完整示例
@ConfigurationpublicclassWorkflowConfig{@BeanpublicStateGraphworkflowGraph(ChatModel chatModel)throwsGraphStateException{// 创建 ChatClientChatClient chatClient =ChatClient.builder(chatModel).defaultAdvisors(newSimpleLoggerAdvisor()).build();// 创建状态工厂OverAllStateFactory stateFactory =()->{OverAllState state =newOverAllState(); state.registerKeyAndStrategy("input",newReplaceStrategy()); state.registerKeyAndStrategy("classification",newReplaceStrategy()); state.registerKeyAndStrategy("result",newReplaceStrategy());return state;};// 创建分类节点QuestionClassifierNode classifier =QuestionClassifierNode.builder().chatClient(chatClient).inputTextKey("input").categories(List.of("positive","negative")).build();// 创建处理节点NodeAction processor =(state)->{String classification =(String) state.value("classification").orElse("");String result ="处理结果: "+ classification; state.put("result", result);return state;};// 创建路由逻辑EdgeAction router =(state)->{String classification =(String) state.value("classification").orElse("unknown");return classification.contains("positive")?"positive":"negative";};// 构建图StateGraph graph =newStateGraph("CustomerService", stateFactory).addNode("classifier",node_async(classifier)).addNode("processor",node_async(processor)).addEdge(START,"classifier").addConditionalEdges("classifier",edge_async(router),Map.of("positive","processor","negative","processor")).addEdge("processor", END);return graph;}}6.3 使用 CompiledGraph
@RestControllerpublicclassWorkflowController{privatefinalCompiledGraph compiledGraph;publicWorkflowController(StateGraph stateGraph)throwsGraphStateException{this.compiledGraph = stateGraph.compile();}@GetMapping("/workflow")publicStringexecuteWorkflow(@RequestParamString input){OverAllState initialState =newOverAllState(); initialState.put("input", input);Optional<OverAllState> result = compiledGraph.invoke(initialState);return result.map(state ->(String) state.value("result").orElse("")).orElse("执行失败");}}7. 高级特性
7.1 A2A(Agent-to-Agent)通信
A2A 支持分布式 Agent 之间的通信和协作。
7.1.1 配置 A2A Server
<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-a2a-nacos</artifactId><version>1.1.0.0-M5</version></dependency>spring:cloud:nacos:discovery:server-addr: localhost:8848ai:alibaba:a2a:enabled:trueagent-name: my-agent 7.1.2 使用 A2A Client
@AutowiredprivateA2AClient a2aClient;publicvoidcallRemoteAgent(){A2AMessage request =newA2AMessage("remote-agent","问题");A2AMessage response = a2aClient.call(request);}7.2 动态配置(Nacos)
支持通过 Nacos 动态配置 Agent:
<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-config-nacos</artifactId><version>1.1.0.0-M5</version></dependency>@BeanpublicReactAgentnacosAgent(NacosOptions nacosOptions){returnNacosReactAgentBuilder.builder().nacosOptions(nacosOptions).build();}7.3 可观测性(Observation)
集成 OpenTelemetry 进行可观测性监控:
<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-graph-observation</artifactId><version>1.1.0.0-M5</version></dependency>StateGraph graph =newStateGraph("Workflow", stateFactory).compile(CompileConfig.builder().withLifecycleListener(newGraphObservationLifecycleListener(observationRegistry)).build());7.4 MCP(Model Context Protocol)支持
支持 MCP 工具集成:
// 配置 MCP 工具McpToolCallbackProvider mcpProvider =newMcpToolCallbackProvider();List<ToolCallback> mcpTools = mcpProvider.getToolCallbacks();ReactAgent agent =ReactAgent.builder().name("MCPAgent").model(chatModel).tools(mcpTools).build();7.5 流式响应
支持流式返回 Agent 响应:
@GetMapping(value ="/stream", produces =MediaType.TEXT_EVENT_STREAM_VALUE)publicFlux<String>streamChat(@RequestParamString query){return agent.stream(query).map(AssistantMessage::getContent);}8. 最佳实践
8.1 Agent 设计原则
- 单一职责: 每个 Agent 应该专注于一个特定任务
- 清晰的指令: 提供明确、详细的系统指令
- 合适的工具: 为 Agent 配置必要的工具,但不要过度
- 错误处理: 实现适当的错误处理和重试机制
8.2 性能优化
- 并行执行: 对于独立任务,使用
ParallelAgent - 上下文管理: 使用
SummarizationHook管理长对话 - 工具选择: 限制工具数量,使用动态工具选择
- 缓存: 对重复查询使用缓存
8.3 安全性
- API Key 管理: 使用环境变量或密钥管理服务
- 工具权限: 限制工具的执行权限
- 输入验证: 验证和清理用户输入
- 沙箱执行: 对代码执行使用沙箱环境
8.4 调试和监控
- 启用日志: 使用
enableLogging(true)查看详细日志 - 状态检查: 检查
OverAllState了解执行状态 - 可观测性: 集成 OpenTelemetry 进行监控
- 可视化: 使用 PlantUML 或 Mermaid 可视化工作流
9. 常见问题
9.1 如何选择合适的 Agent 类型?
- 简单任务: 使用
ReactAgent - 顺序处理: 使用
SequentialAgent - 并行处理: 使用
ParallelAgent - 动态路由: 使用
LlmRoutingAgent - 复杂工作流: 直接使用
Graph Core
9.2 如何处理长对话?
使用 SummarizationHook 自动摘要:
SummarizationHook hook =SummarizationHook.builder().trigger(10000).clearAtLeast(6000).keep(4).build();9.3 如何限制工具调用次数?
使用 ToolCallLimitInterceptor:
ToolCallLimitInterceptor interceptor =ToolCallLimitInterceptor.builder().maxToolCalls(10).build();9.4 如何实现人在回路?
使用 HumanInTheLoopHook:
HumanInTheLoopHook hook =HumanInTheLoopHook.builder().enabled(true).build();9.5 如何调试 Agent 执行?
- 启用日志:
enableLogging(true) - 检查状态:
agent.invoke(query)返回OverAllState - 使用 Studio UI: 访问
/chatui/index.html进行可视化调试
10. 参考资料
10.1 官方文档
10.2 示例代码
10.3 社区资源
10.4 相关项目
- Spring AI Alibaba Admin: 本地可视化工具包
- Spring AI Extensions: Spring AI 扩展实现
- JManus: Java 实现的 Manus
- DataAgent: 自然语言转 SQL 项目
- DeepResearch: 深度研究实现
10.5 白皮书
- AI-Native Application Architecture White Paper: AI 原生应用架构白皮书
附录
A. 依赖版本说明
当前文档基于以下版本:
- Spring AI Alibaba: 1.1.0.0-M5
- Spring AI: 1.1.0-M4
- Spring Boot: 3.4.8
- JDK: 17+
B. 快速参考
B.1 ReactAgent 构建器
ReactAgent.builder().name(String)// 必需.model(ChatModel)// 必需.instruction(String)// 可选.systemPrompt(String)// 可选.tools(ToolCallback...)// 可选.hooks(Hook...)// 可选.interceptors(Interceptor...)// 可选.saver(MemorySaver)// 可选.enableLogging(boolean)// 可选.build()B.2 常用工具创建
// 函数工具FunctionToolCallback.builder("toolName", function).description("工具描述").inputType(InputType.class).build()// Python 工具PythonTool.createPythonToolCallback("执行 Python 代码")B.3 状态管理
// 注册键和策略 state.registerKeyAndStrategy("key",newReplaceStrategy()); state.registerKeyAndStrategy("key",newAppendStrategy());// 读取值Optional<Object> value = state.value("key");// 写入值 state.put("key", value);