在AI 技术飞速发展之下的今天,信任搞技术的朋友们今年听到最多的词就是“大模型”,“AI Agent”,“MCP”等等,想必大家也都有所了解,那么作为一名Java开发者,尤其是对习惯了Spring生态的朋友们来说,spring-ai-alibaba-agent是最容易入门和上手AI Agent的Agent框架。
如果你是一名Java开发者,信任这篇文章肯定对你有所协助,可作为了解Agent的入门级文章,让我们一起了解Spring-ai-alibaba-agent
项目介绍
什么是 Spring AI Alibaba?
Spring AI Alibaba 是一个代码优先(Code-First)的 AI Agent 开发框架,专为 Java 开发者设计,用于快速构建智能体(Agent)、工作流(Workflow)和多智能体应用(Multi-Agent Applications)。
该框架深度集成了 Spring Boot 生态,让熟悉 Spring 的开发者能够以极低的学习成本进入 AI 应用开发领域。

能用它做什么?
Spring AI Alibaba 可以协助我们构建以下类型的应用:
- 智能对话助手 – 具备推理和行动能力的对话机器人
- 工作流自动化 – 复杂的多步骤任务编排和执行
- 多智能体协作系统 – 多个 AI Agent 协同完成复杂任务
- 企业级 AI 应用 – 集成业务逻辑的生产级 AI 解决方案
- 分布式智能体网络 – 支持 Agent-to-Agent(A2A)通信的分布式系统
为什么选择 Spring AI Alibaba?
|
特性 |
说明 |
优势 |
|
Spring 原生 |
完全基于 Spring Boot 生态 |
Spring 开发者零学习成本 |
|
代码优先 |
通过 Java 代码定义 Agent 和工作流 |
类型安全、易于调试、版本控制友善 |
|
功能完整 |
ReactAgent、多智能体编排、工具调用等 |
一站式解决方案 |
|
中文支持 |
完善的中文文档和社区 |
对国内开发者友善 |
核心特性
1. ReactAgent – 推理与行动智能体
ReactAgent 是框架的核心概念,基于 ReAct(Reasoning + Acting) 范式:
- 自动上下文工程:框架自动管理提示词(Prompt)和对话历史
- 工具调用能力:Agent 可以调用外部工具(Function Calling)和MCP
- 迭代推理:支持多轮推理和行动循环
- 流式响应:支持实时流式输出
ReactAgent agent = ReactAgent.builder()
.name("assistant_agent")
.model(chatModel)
.description("查询全国各地旅游景点")
.instruction("你是一个一名旅行博主,对全国各地的旅游城市以及景点很了解。请根据用户的提问进行回答。" +
"你擅长使用MCP Tool工具。通过Tool工具查询天气信息情况,根据不同的天气情况,给出具体的需要准备的出行装备")
.tools(List.of(weatherTool)) // 配置工具
.outputKey("tourism_attractions_Agent")
.build();
// 调用 Agent
AssistantMessage response = agent.call("6月份我想去青海旅游,请给我一份旅游计划,note: 请查看6月份西宁的天气情况");
2. Multi-Agent Orchestration – 多智能体编排
框架提供多种内置的编排模式:
|
编排模式 |
说明 |
适用场景 |
|
SequentialAgent |
顺序执行多个 Agent |
工作流、流水线处理 |
|
ParallelAgent |
并行执行多个 Agent |
同时处理多个独立任务 |
|
LlmRoutingAgent |
基于 LLM 决策路由 |
动态选择执行路径 |
|
LoopAgent |
循环执行 Agent |
迭代优化、重复处理 |
// 创建顺序执行的 Agent 工作流
SequentialAgent workflow = SequentialAgent.builder()
.name("travel_workflow")
.description("创建一个旅游计划")
.subAgents(List.of(tourismAttractionsAgent, reviewTourismAgent))
.build();
Optional<OverAllState> result = workflow.invoke("青海哪个季节适合旅游");
3. Context Engineering – 上下文工程
框架内置了上下文管理的最佳实践:
- 自动历史管理:对话历史自动维护和传递
- 状态持久化:支持工作流状态的保存和恢复
- 上下文窗口管理:智能管理 Token 使用
- Prompt 模板:灵活的提示词模板系统
4. Human In The Loop – 人类参与
支持在 Agent 执行过程中加入人类审批和反馈:
ReactAgent sensitiveAgent = ReactAgent.builder()
.name("data_processor")
.model(chatModel)
.instruction("Process user data carefully")
.tools(List.of(deleteDataTool)) // 敏感操作需要人工确认
.build();
// 工作流中断等待人工确认
CompiledGraph graph = stateGraph.compile(
CompileConfig.builder()
.interruptBefore(List.of("delete_data_node")) // 在此节点前中断
.build()
);
5. Graph-based Workflow – 图工作流
基于有向图的工作流引擎,提供底层编排能力:
- 状态图(StateGraph):定义节点和边的有向图
- 条件路由:根据状态动态选择执行路径
- 并行执行:支持节点并行执行
- 子图嵌套:支持复杂的层级工作流
- 可视化导出:导出为 PlantUML 和 Mermaid 格式
StateGraph graph = new StateGraph("my_workflow", stateFactory)
.addNode("classify", classifyNode)
.addNode("process_a", processANode)
.addNode("process_b", processBNode)
.addEdge(START, "classify")
.addConditionalEdges("classify", dispatcher,
Map.of("type_a", "process_a", "type_b", "process_b"))
.addEdge("process_a", END)
.addEdge("process_b", END);
6. A2A Support – Agent 间通信
支持分布式 Agent 协作:
- Nacos 集成:基于 Nacos 的服务发现和注册
- 负载均衡:自动负载均衡和故障转移
- 远程调用:Agent 可以远程调用其他 Agent
- 动态配置:支持运行时配置更新
7. Rich Model & Tool Support – 丰富的模型和工具支持
- 多模型支持:DashScope(通义千问)、OpenAI、Azure OpenAI 等
- 工具调用(Function Calling):支持标准的 Function Calling 协议
- MCP 支持:集成 Model Context Protocol
- 自定义工具:轻松扩展自定义工具
快速开始
环境准备
必需条件
- JDK 17 或更高版本
java -version # 应输出: java version "17" 或更高
- Maven 3.6 或更高版本
mvn -version
- 大模型 API Key
阿里云通义千问:
https://dashscope.console.aliyun.com/
OpenAI:https://platform.openai.com/
构建项目(当前为快照版本,1.1.0.0-SNAPSHOT)
Note:spring-ai-alibaba最新release版本为:1.0.0.4。我们为了使用最新的Agent特性,使用最新的SNAPSHOT版本:
# 克隆项目,
git clone https://github.com/alibaba/spring-ai-alibaba.git
cd spring-ai-alibaba
# 构建并安装到本地 Maven 仓库
mvn clean install -DskipTests
第一个 Agent 应用
1. 创建 Spring Boot 项目
使用 Spring Initialize 创建项目,或直接创建 pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.6</version>
</parent>
<groupId>com.example</groupId>
<artifactId>my-first-agent</artifactId>
<version>1.0.0</version>
<properties>
<java.version>17</java.version>
<spring-ai-alibaba.version>1.1.0.0-SNAPSHOT</spring-ai-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.5.6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AI Alibaba Agent Framework -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-agent-framework</artifactId>
<version>${spring-ai-alibaba.version}</version>
</dependency>
<!-- DashScope Model(通义千问) -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
<version>${spring-ai-alibaba.version}</version>
</dependency>
</dependencies>
<!-- 配置 Spring Milestones 仓库 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
2. 配置文件
创建
src/main/resources/application.yml:
server:
port: 8080
spring:
application:
name: my-first-agent
ai:
dashscope:
chat:
api-key: ${AI_DASHSCOPE_API_KEY}
核心概念详解
ReactAgent 详解
ReactAgent 是框架的核心抽象,它实现了 ReAct(Reasoning + Acting)模式。
关键配置项
ReactAgent agent = ReactAgent.builder()
// 必需配置
.name("agent_name") // Agent 名称(必需)
.model(chatModel) // 大模型实例(必需)
// 基础配置
.description("Agent description") // Agent 描述
.instruction("System instruction") // 系统指令(相当于 system prompt)
// 输入输出配置
.inputSchema(inputSchema) // 输入格式定义(JSON Schema)
.outputKey("result") // 输出结果的 key
.outputSchema(outputSchema) // 输出格式定义
// 工具配置
.tools(List.of(tool1, tool2)) // 工具列表
.resolver(toolCallbackResolver) // 工具解析器
// 高级配置
.hooks(List.of(hook1, hook2)) // 生命周期钩子
.compileConfig(compileConfig) // 编译配置
.shouldContinueFunc(continueFunction) // 继续条件函数
.build();
调用方式
ReactAgent 支持多种调用方式:
// 1. 简单文本调用
AssistantMessage response1 = agent.call("北京和巴黎多远?");
// 2. UserMessage 调用
UserMessage userMsg = new UserMessage("北京和巴黎多远?");
AssistantMessage response2 = agent.call(userMsg);
// 3. 消息列表调用(支持多轮对话)
List<Message> messages = List.of(
new UserMessage("法国的首都是巴黎吗"),
new AssistantMessage("巴黎有什么旅游景点"),
new UserMessage("给我生成一份去巴黎的旅游计划")
);
AssistantMessage response3 = agent.call(messages);
// 4. 状态调用(工作流模式)
Optional<OverAllState> result = agent.invoke("给我生成一份去巴黎的旅游计划");
// 5. 流式调用
Flux<OverAllState> stream = agent.stream("给我生成一份去巴黎的旅游计划");
stream.subscribe(state -> {
// 处理每个状态更新
System.out.println(state);
});
工具(Tools)使用
定义工具
工具使用标准的 Java 方法,通过注解标注:
@Configuration
public class Weather {
public static final Map<String, String> CITY_MAP = Map.of(
"北京", "多云转晴 10-4℃",
"上海", "多云转小雨 24-20℃",
"广州", "小雨转暴雨 20-15℃",
"深圳", "小雨转阴 22-19℃",
"西宁", "晴转多云 25-17℃");
@Bean
public ToolCallback weatherTool() {
// 定义工具,并将其注册为spring bean
return FunctionToolCallback.builder("weather_tool", new Weather.WeatherFunction())
.inputType(Weather.WeatherFunction.Request.class)
.description("你是一名专业的天气预报员,能够根据城市名称,查询对应的天气情况")
.build();
}
public static class WeatherFunction implements BiFunction<Weather.WeatherFunction.Request, ToolContext, String> {
@Override
public String apply(Weather.WeatherFunction.Request request, ToolContext context) {
return CITY_MAP.get(request.cityName());
}
public record Request(
String cityName
) {
}
}
}
将工具注册到 Agent
@Bean
public ReactAgent weatherAgent(DashScopeChatModel chatModel, @Qualifier("weatherTool") ToolCallback weatherTool) throws GraphStateException {
return ReactAgent.builder()
.name("Weather Agent")
.model(chatModel)
.tools(List.of(weatherTool))
.description("查询天气预报信息")
.instruction("你是一名天气预报员,能够根据城市名称,查询对应的天气情况。" +
"你也擅长使用MCP Tool工具。通过Tool工具查询天气情况")
.outputKey("Weather_Agent")
.build();
}
// 使用
AssistantMessage result = weatherAgent.call("通过工具查询北京的天气怎么样?");
Agent 作为工具(Agent as Tool)
一个 Agent 可以作为工具被另一个 Agent 调用:
// 创建专门的 Agent
@Bean
public ReactAgent flightAgent(DashScopeChatModel chatModel, @Qualifier("flightTool") ToolCallback flightTool) throws GraphStateException {
return ReactAgent.builder()
.name("Flight Agent")
.model(chatModel)
.tools(List.of(flightTool))
.description("查询航班信息")
.instruction("你是一名专业的航班信息查询APP,知道全国以及全球每天航班信息,能根据用户的出行需求,提供适合的航班信息。" +
"你也擅长使用MCP Tool工具。通过Tool工具查询航班信息")
.outputKey("Flight_Agent")
.build();
}
@Bean
public ReactAgent weatherAgent(DashScopeChatModel chatModel, @Qualifier("weatherTool") ToolCallback weatherTool) throws GraphStateException {
return ReactAgent.builder()
.name("Weather Agent")
.model(chatModel)
.tools(List.of(weatherTool))
.description("查询天气预报信息")
.instruction("你是一名天气预报员,能够根据城市名称,查询对应的天气情况。" +
"你也擅长使用MCP Tool工具。通过Tool工具查询天气情况")
.outputKey("Weather_Agent")
.build();
}
// 创建协调 Agent,使用其他 Agent 作为工具
@Bean
public ReactAgent generateTravelPlanAgent(DashScopeChatModel chatModel, @Qualifier("flightAgent") ReactAgent flightAgent,
@Qualifier("weatherAgent") ReactAgent weatherAgent) throws GraphStateException {
return ReactAgent.builder()
.name("generate_travel_plan_Agent")
.model(chatModel)
.description("Routes requests to appropriate agents")
.tools(List.of(
AgentTool.getFunctionToolCallback(flightAgent),
AgentTool.getFunctionToolCallback(weatherAgent)
)).build();
}
// 调用
AssistantMessage result = generateTravelPlanAgent.call(
"青海哪个季节适合旅游"
);
多智能体编排
SequentialAgent – 顺序执行
按顺序执行多个 Agent,前一个的输出作为后一个的输入:
@Bean
public SequentialAgent travelSequentialAgent(@Qualifier("tourismAttractionsAgent") ReactAgent tourismAttractionsAgent,
@Qualifier("reviewTourismAgent") ReactAgent reviewTourismAgent) {
// Create a sequential workflow builder with name and description
try {
return SequentialAgent.builder()
.name("travel_workflow") // Set the workflow name
.description("create a travel plan") // Set the workflow description
.subAgents(List.of(tourismAttractionsAgent, reviewTourismAgent)).build();
} catch (GraphStateException e) {
throw new RuntimeException(e);
}
}
Optional<OverAllState> message = travelSequentialAgent.invoke("给我规划一份6月份去青海的旅行计划");
ParallelAgent – 并行执行
同时执行多个 Agent,适合独立任务:
@Bean
public ParallelAgent travelParallelAgent(@Qualifier("flightAgent") ReactAgent flightAgent,
@Qualifier("weatherAgent") ReactAgent weatherAgent) {
// Create a sequential workflow builder with name and description
try {
return ParallelAgent.builder()
.name("travel_workflow") // Set the workflow name
.description("create a travel plan") // Set the workflow description
.subAgents(Arrays.asList(flightAgent, weatherAgent)).build();
} catch (GraphStateException e) {
throw new RuntimeException(e);
}
}
Optional<OverAllState> message = travelParallelAgent.invoke("想去青海旅行,哪个季节最合适?");
LlmRoutingAgent – 智能路由
基于 LLM 决策选择执行哪个 Agent:
@Bean
public LlmRoutingAgent llmRoutingAgent(DashScopeChatModel chatModel, @Qualifier("flightAgent") ReactAgent flightAgent,
@Qualifier("weatherAgent") ReactAgent weatherAgent) throws GraphStateException {
return LlmRoutingAgent.builder()
.name("smart_router")
.model(chatModel)
.description("Routes requests to appropriate agents")
.subAgents(List.of(
flightAgent,
weatherAgent
)).build();
}
Optional<OverAllState> message = llmRoutingAgent.invoke("6月份想去青海旅行,应该做哪些准备?");
生态项目
Spring AI Alibaba在面对AI时代的技术革命 ,在积极拓展和丰富自己的生态系统:
|
项目 |
说明 |
GitHub |
|
Spring AI Extensions |
扩展实现,包括 DashScopeChatModel、MCP 等 |
spring-ai-alibaba/spring-ai-extensions |
|
Spring AI Alibaba Admin |
可视化开发工具,支持项目管理、运行时可视化、追踪和评估 |
spring-ai-alibaba/spring-ai-alibaba-admin |
|
Examples |
官方示例代码库 |
spring-ai-alibaba/examples |
|
JManus |
基于 Spring AI Alibaba 的 Manus Java 实现 |
spring-ai-alibaba/jmanus |
|
DataAgent |
自然语言转 SQL 项目 |
spring-ai-alibaba/dataagent |
|
DeepResearch |
深度研究助手 |
spring-ai-alibaba/deepresearch |
总结
Spring AI Alibaba 是一个依旧在不断迭代、完善中的,专为 Java 开发者设计的 AI Agent 开发框架,让你能够像普通 Spring 代码一样构建智能应用,这是对我们Java开发者最大的友善。
核心价值
简单易用:如果你熟悉 Spring Boot,就能快速上手。框架采用代码优先的方式,通过 Java 代码定义 Agent 和工作流,类型安全、易于调试。
功能强劲:
- ReactAgent:核心智能体,能够推理和行动,自动调用工具完成任务
- 多智能体编排:支持顺序、并行、智能路由等多种编排模式
- Graph 工作流:底层图引擎,提供灵活的条件路由和复杂流程控制
- 工具调用:轻松集成外部工具,让 AI 具备实际操作能力
- 分布式协作:支持 Agent 之间的远程调用和协作
适用场景
- 智能客服系统:自动分类和处理客户反馈
- 内容创作流水线:从研究到发布的完整自动化流程
- 数据分析助手:配备专业工具的数据分析 Agent
- 企业级 AI 应用:需要与业务系统深度整合的场景
快速上手三步走
- 环境准备:JDK 17+、Maven 3.6+、大模型 API Key
- 创建 Agent:使用 ReactAgent.builder() 构建你的第一个智能体
- 调用使用:通过 agent.call() 或 agent.invoke() 执行任务
进阶能力
- Human-in-the-Loop:在关键步骤加入人工审批
- 流式响应:实时输出,提升用户体验
- A2A 通信:分布式 Agent 网络,支持跨服务协作
学习提议
对于初学者,提议按照以下路径学习:
- 先完成”快速开始”部分,创建第一个简单 Agent
- 理解 ReactAgent 的核心概念和配置项
- 学习工具(Tools)的使用方法
- 尝试多智能体编排,理解不同编排模式的应用场景
- 通过实战案例加深理解,然后探索 Graph 工作流等高级特性
Spring AI Alibaba 让 AI Agent 开发变得像 Spring 应用开发一样简单,是 Java 开发者进入 AI 应用领域的理想选择。
收藏了,感谢分享
给力