
大家好,我是煜道。
今天我们一起来学习 Spring AI Alibaba: Agent 框架与多类型 Agent 详解。
引言
在上一篇文章中,我们深入探讨了 Graph 核心运行时的设计原理,包括状态图构建、状态管理、检查点持久化等核心机制。本文将聚焦于 Agent 框架层,详细介绍各类 Agent 的实现原理和使用场景,帮助我们掌握如何利用框架构建智能化的 AI 应用。

01 Agent 核心架构
1.1 Agent 抽象体系
Spring AI Alibaba 的 Agent 框架是构建在 Graph 核心之上的高级抽象,它将 AI 驱动的任务执行封装为可复用的组件。

1.2 Agent 与 StateGraph 的关系
Agent 本质上是基于 StateGraph 的一种封装,框架预先定义好了图的结构,开发者只需要关注业务逻辑的配置。


02 ReactAgent 详解
2.1 ReAct 模式原理
ReactAgent 是最常用的 Agent 类型,它实现了 ReAct(Reasoning + Acting) 模式。这种模式的核心思想是让 AI 模型在推理和行动之间交替进行,直到完成任务。

2.2 构建 ReactAgent
ReactAgent agent = ReactAgent.builder() .name("assistant") .description("A helpful assistant that can answer questions and use tools") .instruction(""" You are a helpful assistant. When you need to get current information, use the available tools. """) .chatModel(chatModel) .tools(tool1, tool2) // 注册工具 .hooks(new HumanInTheLoopHook()) // 添加钩子 .maxIterations(10) // 最大迭代次数 .verbose(true) // 输出详细日志 .build();// 调用 AgentString response = agent.invoke("What is the weather in Beijing?");2.3 核心配置项
2.4 Agent 内部节点
ReactAgent 内部由两个核心节点组成:

AgentLlmNode负责调用大语言模型生成响应。它将当前状态中的消息历史发送给模型,并解析模型的回复。
AgentToolNode 负责执行工具调用。它解析模型返回的工具调用请求,执行相应的工具,并将结果返回给模型。

03 多类型 Agent
3.1 SequentialAgent(顺序执行)
SequentialAgent 按顺序执行一系列 Agent,每个 Agent 的输出作为下一个 Agent 的输入。
// 构建顺序执行 AgentSequentialAgent agent = SequentialAgent.builder() .name("workflow") .description("Sequential workflow") .agents( agent1, // 第一步:信息收集 agent2, // 第二步:处理分析 agent3 // 第三步:生成报告 ) .build();
适用场景:
多步骤的流水线任务。 需要严格顺序依赖的工作流程。 数据经过多个阶段处理的场景。
3.2 ParallelAgent(并行执行)
ParallelAgent 并行执行多个 Agent,适用于相互独立的任务。
// 构建并行执行 AgentParallelAgent agent = ParallelAgent.builder() .name("parallel") .description("Parallel execution") .agents( agent1, // 并行任务1 agent2 // 并行任务2 ) .mergeStrategy(MergeStrategy.concatenate()) // 结果合并策略 .build();
适用场景:
并发获取多个信息源。 独立任务的批量处理。 需要聚合多个视角的分析。
3.3 RoutingAgent(条件路由)
RoutingAgent 根据输入内容决定路由到哪个 Agent 处理。
// 构建路由 AgentRoutingAgent agent = RoutingAgent.builder() .name("router") .description("Intent router") .routingFunction(input -> { String query = (String) input.get("query");// 根据查询内容路由if (query.contains("weather")) {return"weather_agent"; } elseif (query.contains("news")) {return"news_agent"; }return"general_agent"; }) .agents( Map.of("weather_agent", weatherAgent,"news_agent", newsAgent,"general_agent", generalAgent )) .build();
适用场景:
多意图识别和分发。 客服机器人的意图路由。 场景分类后的差异化处理。
3.4 LoopAgent(循环执行)
LoopAgent 循环执行直到满足退出条件。
// 构建循环 AgentLoopAgent agent = LoopAgent.builder() .name("loop") .description("Loop execution") .maxIterations(5) .loopCondition(state -> {// 循环条件:result 不为空且 iterations < 5return state.get("result") == null; }) .loopBody(agent1) // 循环体 .build();
适用场景:
轮询等待某个状态。 迭代优化类任务。 需要多次尝试才能完成的任务。
3.5 SupervisorAgent(监督者模式)
SupervisorAgent 由一个监督者 Agent 协调多个子 Agent,监督者负责分配任务和汇总结果。
// 构建监督者 AgentSupervisorAgent agent = SupervisorAgent.builder() .name("supervisor") .description("Supervisor coordinating sub-agents") .supervisorAgent(supervisorLlm) // 监督者模型 .agents( researchAgent, analysisAgent, reportAgent ) .promptTemplate(""" You are a supervisor coordinating a team. Available agents: research, analysis, report. Task: {task} """) .build();
适用场景:
复杂任务分解。 多 Agent 协作场景。 需要动态分配任务的场景。
⚠️ 特别注意:SupervisorAgent 的子 Agent 列表中不能包含另一个 SupervisorAgent,否则会报错:
Error: Setting Supervisor as parent of Supervisor would create a cycle。如果需要多层级监督,请使用 SequentialAgent 或 ParallelAgent 组合多个 SupervisorAgent。

04 Agent 通信机制
4.1 A2A 协议概述
A2A(Agent-to-Agent)是 Google 提出的 Agent 通信协议标准,Spring AI Alibaba 实现了该协议并与 Nacos 深度集成。

4.2 A2aRemoteAgent
A2aRemoteAgent 用于与实现 A2A 协议的远程 Agent 通信:
// 构建远程 AgentA2aRemoteAgent agent = A2aRemoteAgent.builder() .name("remote-assistant") .description("Remote agent via A2A") .endpoint("http://remote-agent:8080/a2a") .agentCard(AgentCard.fromJson(json)) .build();// 调用远程 AgentString result = agent.invoke("Hello, please help me...");4.3 Nacos 服务注册发现
框架通过 Nacos 实现 Agent 的服务注册与发现:


05 工具系统
5.1 工具注册
工具是 Agent 能力的重要扩展:
// 注册工具到 AgentReactAgent agent = ReactAgent.builder() .name("assistant") .chatModel(chatModel) .tools(// Spring AI Tool weatherTool, // 使用 @Tool 注解的工具 calculatorTool, // 计算器工具// 自定义 ToolCallbacknew CustomToolCallback() ) .build();5.2 工具调用限制
可以通过 Hook 实现工具调用限制:
agent = ReactAgent.builder() .name("assistant") .chatModel(chatModel) .tools(tool1, tool2) .hooks(List.of(new ToolCallLimitHook(5) // 限制单次执行最多5次工具调用 )) .build();
06 最佳实践
6.1 Agent 类型选择
6.2 指令设计原则
明确性原则:指令应该清晰明确,避免歧义。
// ❌ 模糊的指令.instruction("Help me.")// ✅ 明确的指令.instruction(""" You are a weather assistant. When users ask about weather, use the weather_tool to get data. Respond in Chinese with temperature and conditions. """)角色定义原则:为 Agent 定义明确的角色。
.instruction(""" You are a professional data analyst. Your expertise includes: - Statistical analysis - Data visualization - Trend prediction Always explain your reasoning step by step. """)6.3 工具设计原则
单一职责:每个工具只完成一个功能。
清晰命名:工具名称应该直观表达其功能。
// ❌ 模糊的工具名@Tool(name = "do", description = "do something")public String doSomething(String input){ ... }// ✅ 清晰的工具名@Tool(name = "get_weather", description = "Get current weather for a location")public String getWeather(@ToolParam(description = "City name") String city) { ... }
07 总结
本文详细介绍了 Spring AI Alibaba 的 Agent 框架,包括 ReactAgent 的实现原理、多种 Agent 类型的适用场景、A2A 协议与远程 Agent 通信等内容。通过合理选择和组合不同类型的 Agent,开发者可以构建复杂的 AI 应用。
在下一篇文章中,我们将探讨 Hook 系统与拦截器机制,了解如何通过扩展点实现对 Agent 行为的精细控制。敬请期待。

夜雨聆风