Spring AI Alibaba 1.x 系列【41】多智能体核心模式 - 交接(Handoffs)中的四大智能体源码解读
1. 概述
1.1 交接模式
当前正在工作的活跃 Agent,主动决策、将会话控制权完整转移给另一个指定 Agent,交接完成后,原 Agent 休眠 / 退出,用户后续直接和新接管的 Agent 交互。
去中心化特性:
- 无需中心调度器、顶层路由
Agent统一分发; - 每个
Agent具备自主决策移交的能力; - 活跃
Agent可以动态改写「当前谁来处理用户请求」。
典型使用场景:
- 跨领域对话拆分(通用客服 → 财务专家 / 法务专家 / 技术运维)
- 复杂任务专家接管(普通问答 → 数据分析
Agent/ 工单处理Agent) - 多角色分工协作(前置意图识别
Agent→ 专项执行Agent)
1.2 四种交接模式多智能体
Spring AI Alibaba 提供了 4 种 FlowAgent(流程编排智能体),它们继承自 [FlowAgent] 抽象类,内部通过 StateGraph 构建执行图,将多个子 Agent 按不同模式组合运行。
| FlowAgent | 执行模式 | 核心特点 |
|---|---|---|
| SequentialAgent | 串行链式 | 子 Agent 按顺序依次执行,上一个的输出作为下一个的输入 |
| ParallelAgent | 并行聚合 | 所有子 Agent 同时执行,结果按策略合并 |
| LoopAgent | 循环执行 | 单个子 Agent 按策略(次数/条件/数组)循环执行 |
| LlmRoutingAgent | LLM 路由 | LLM 根据输入自主决定调用哪些子 Agent,支持多路并行路由 |
共同点:
- 都通过
builder()模式构建 - 子
Agent通常是ReactAgent,也可以是嵌套的FlowAgent - 支持
Hook扩展(beforeAgent/beforeModel/afterModel等) - 支持
invoke()同步调用和stream()流式调用
2. FlowAgent 抽象类
FlowAgent 是所有多智能体智能体的顶层父类:
- 统一封装子智能体管理、状态图初始化、钩子挂载、配置构建能力
- 衔接多智能体协作与
StateGraph底层图执行引擎
默认已经实现的子类:

2.1 SequentialAgent
源码如下:
public class SequentialAgent extends FlowAgent {
/**
* 构造方法
* 通过建造者模式接收配置参数,委托给父类 FlowAgent 初始化
* @param builder 顺序智能体建造器
*/
protected SequentialAgent(SequentialAgentBuilder builder) {
super(builder.name, builder.description, builder.compileConfig, builder.subAgents,
builder.stateSerializer, builder.executor, builder.hooks);
}
/**
* 静态建造器入口
* 提供类型安全的链式调用方式创建 SequentialAgent 实例
*/
public static SequentialAgentBuilder builder() {
return new SequentialAgentBuilder();
}
/**
* 重写父类抽象方法:构建【顺序类型】的状态图
* 核心逻辑:调用 FlowGraphBuilder,指定 SEQUENTIAL(顺序)类型生成工作流图
* @param config 流图配置(包含子智能体、钩子、序列化器等)
* @return 构建完成的顺序执行状态图
* @throws GraphStateException 图构建异常
*/
@Override
protected StateGraph buildSpecificGraph(FlowGraphBuilder.FlowGraphConfig config) throws GraphStateException {
return FlowGraphBuilder.buildGraph(FlowAgentEnum.SEQUENTIAL.getType(), config);
}
/**
* 【顺序智能体建造器】
* 继承通用 FlowAgentBuilder,实现类型安全的对象创建
* 遵循建造者设计模式,简化复杂对象的初始化
*/
public static class SequentialAgentBuilder extends FlowAgentBuilder<SequentialAgent, SequentialAgentBuilder> {
/**
* 返回当前建造器实例(用于链式调用)
*/
@Override
protected SequentialAgentBuilder self() {
return this;
}
/**
* 参数校验
* 继承父类基础校验,可扩展顺序智能体专属校验规则
*/
@Override
protected void validate() {
super.validate();
// 如需扩展顺序执行的专属校验逻辑,可在此处添加
}
/**
* 执行构建:创建 SequentialAgent 实例
*/
@Override
public SequentialAgent doBuild() {
validate();
return new SequentialAgent(this);
}
}
}
极简使用示例:
// 1. 创建多个子智能体(每个绑定不同动态工具)
Agent orderAgent = ...; // 订单查询智能体
Agent refundAgent = ...; // 退款处理智能体
// 2. 链式创建顺序执行智能体
SequentialAgent agent = SequentialAgent.builder()
.name("客服流程智能体")
.description("按顺序执行:查询→退款")
.subAgents(List.of(orderAgent, refundAgent)) // 顺序执行
.hooks(List.of(new ToolAuditHook())) // 工具审计钩子
.build();
// 3. 启动执行
agent.run();
2.2 ParallelAgent
源码如下:
/**
* 【并行执行智能体】
* 并发执行多个子智能体,并自动合并所有子智能体的执行结果。
*
* <p>
* 实现 【分发-并行-聚合】(Fan-Out/Gather) 设计模式:
* </p>
* <ul>
* <li><strong>分发</strong>:将输入数据同时分发给所有子智能体</li>
* <li><strong>并行</strong>:所有子智能体并发执行(非顺序阻塞)</li>
* <li><strong>聚合</strong>:收集所有子智能体的结果,按策略合并</li>
* </ul>
*
* <p>
* 基于底层 ParallelNode 实现真正的并发执行,支持自定义结果合并策略。
* </p>
*/
public class ParallelAgent extends FlowAgent {
private static final Logger logger = LoggerFactory.getLogger(ParallelAgent.class);
/** 结果合并策略 */
private final MergeStrategy mergeStrategy;
/** 合并结果的输出Key */
private String mergeOutputKey;
/** 最大并发数(控制子智能体的并发执行数量) */
private final Integer maxConcurrency;
/**
* 构造方法:通过建造器初始化参数
*/
protected ParallelAgent(ParallelAgentBuilder builder) {
super(builder.name, builder.description, builder.compileConfig, builder.subAgents,
builder.stateSerializer, builder.executor, builder.hooks);
// 未指定合并策略则使用默认
this.mergeStrategy = builder.mergeStrategy != null ? builder.mergeStrategy : new DefaultMergeStrategy();
this.maxConcurrency = builder.maxConcurrency;
this.mergeOutputKey = builder.mergeOutputKey;
}
/**
* 建造器入口:链式创建 ParallelAgent 实例
*/
public static ParallelAgentBuilder builder() {
return new ParallelAgentBuilder();
}
/**
* 重写:构建【并行类型】的状态图
* 向配置中注入并行专属参数(合并策略、最大并发数)
*/
@Override
protected StateGraph buildSpecificGraph(FlowGraphBuilder.FlowGraphConfig config) throws GraphStateException {
config.customProperty("mergeStrategy", this.mergeStrategy);
config.customProperty("maxConcurrency", this.maxConcurrency);
return FlowGraphBuilder.buildGraph(FlowAgentEnum.PARALLEL.getType(), config);
}
// ========== Getter 方法 ==========
public MergeStrategy mergeStrategy() {
return mergeStrategy;
}
public String mergeOutputKey() {
return mergeOutputKey;
}
public Integer maxConcurrency() {
return maxConcurrency;
}
/**
* 重写:构建非流式配置,将最大并发数注入元数据
* 供 ParallelNode 运行时读取并发限制
*/
@Override
protected RunnableConfig buildNonStreamConfig(RunnableConfig config) {
RunnableConfig baseConfig = super.buildNonStreamConfig(config);
if (this.maxConcurrency != null) {
return RunnableConfig.builder(baseConfig)
.addMetadata(ParallelNode.formatMaxConcurrencyKey(ParallelNode.formatNodeId(this.name())), this.maxConcurrency)
.build();
}
return baseConfig;
}
/**
* 重写:构建流式配置,逻辑同上
*/
@Override
protected RunnableConfig buildStreamConfig(RunnableConfig config) {
RunnableConfig baseConfig = super.buildStreamConfig(config);
if (this.maxConcurrency != null) {
return RunnableConfig.builder(baseConfig)
.addMetadata(ParallelNode.formatMaxConcurrencyKey(ParallelNode.formatNodeId(this.name())), this.maxConcurrency)
.build();
}
return baseConfig;
}
/**
* 【结果合并策略接口】
* 定义并行子智能体结果的合并规则,支持自定义扩展
*/
public interface MergeStrategy {
/**
* 合并并行执行结果
* @param subAgentResults 子智能体结果(Key=智能体标识,Value=执行结果)
* @param overallState 全局状态上下文
* @return 合并后的最终结果
*/
Object merge(Map<String, Object> subAgentResults, OverAllState overallState);
}
/**
* 并行智能体建造器
* 继承通用 FlowAgentBuilder,提供并行专属配置(并发数、合并策略)
*/
public static class ParallelAgentBuilder extends FlowAgentBuilder<ParallelAgent, ParallelAgentBuilder> {
private MergeStrategy mergeStrategy;
private Integer maxConcurrency;
private String mergeOutputKey;
/** 设置结果合并策略 */
public ParallelAgentBuilder mergeStrategy(MergeStrategy mergeStrategy) {
this.mergeStrategy = mergeStrategy;
return this;
}
/** 设置合并结果的输出Key */
public ParallelAgentBuilder mergeOutputKey(String mergeOutputKey) {
this.mergeOutputKey = mergeOutputKey;
return this;
}
/**
* 重写:设置子智能体
* 强制校验:子智能体必须是 BaseAgent 类型
*/
@Override
public ParallelAgentBuilder subAgents(List<Agent> subAgents) {
if (subAgents == null || subAgents.isEmpty()) {
throw new IllegalArgumentException("必须指定子智能体列表");
}
if (subAgents.stream().anyMatch(agent -> !(agent instanceof BaseAgent))) {
throw new IllegalArgumentException("子智能体必须是 BaseAgent 类型");
}
return super.subAgents(subAgents);
}
/** 设置最大并发数 */
public ParallelAgentBuilder maxConcurrency(Integer maxConcurrency) {
this.maxConcurrency = maxConcurrency;
return this;
}
@Override
protected ParallelAgentBuilder self() {
return this;
}
/**
* 核心校验:并行智能体强校验规则
*/
@Override
protected void validate() {
// 1. 校验名称必填
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("必须指定智能体名称");
}
// 2. 至少2个子智能体,最多10个(性能限制)
if (subAgents == null || subAgents.size() < 2) {
throw new IllegalArgumentException("并行智能体至少需要2个子智能体,当前:"
+ (subAgents != null ? subAgents.size() : 0));
}
if (subAgents.size() > 10) {
throw new IllegalArgumentException("并行智能体最多支持10个子智能体,当前:" + subAgents.size());
}
// 3. 校验子智能体输出Key唯一(避免合并冲突)
validateUniqueOutputKeys();
// 4. 校验输入输出Key兼容性
validateInputKeyCompatibility();
// 5. 校验并发数合法性
if (maxConcurrency != null && maxConcurrency < 1) {
throw new IllegalArgumentException("最大并发数必须≥1,当前:" + maxConcurrency);
}
}
/** 校验所有子智能体的 outputKey 唯一 */
private void validateUniqueOutputKeys() {
Set<String> outputKeys = new HashSet<>();
Set<String> duplicateKeys = new HashSet<>();
for (Agent subAgent : subAgents) {
if (subAgent instanceof ReactAgent agent) {
String key = agent.getOutputKey();
if (key != null && !outputKeys.add(key)) {
duplicateKeys.add(key);
}
}
}
if (!duplicateKeys.isEmpty()) {
throw new IllegalArgumentException("子智能体输出Key重复:" + duplicateKeys + ",必须唯一");
}
}
/** 校验子智能体输入输出兼容性 */
private void validateInputKeyCompatibility() {
for (Agent subAgent : subAgents) {
if (!(subAgent instanceof ReactAgent)) continue;
String key = ((ReactAgent) subAgent).getOutputKey();
if (key == null) {
logger.warn("子智能体 {} 未配置 outputKey,可能导致数据流转异常", subAgent.name());
}
}
}
/** 构建并行智能体实例 */
@Override
public ParallelAgent doBuild() {
validate();
return new ParallelAgent(this);
}
}
// ==================== 内置默认合并策略 ====================
/** 默认合并策略:将结果封装为 Map */
public static class DefaultMergeStrategy implements MergeStrategy {
@Override
public Object merge(Map<String, Object> subAgentResults, OverAllState overallState) {
return new HashMap<>(subAgentResults);
}
}
/** 列表合并策略:将结果转为 List */
public static class ListMergeStrategy implements MergeStrategy {
@Override
public Object merge(Map<String, Object> subAgentResults, OverAllState overallState) {
return subAgentResults.values().stream().toList();
}
}
/** 字符串拼接策略:合并文本结果 */
public static class ConcatenationMergeStrategy implements MergeStrategy {
private final String separator;
public ConcatenationMergeStrategy() {
this("\n");
}
public ConcatenationMergeStrategy(String separator) {
this.separator = separator;
}
@Override
public Object merge(Map<String, Object> subAgentResults, OverAllState overallState) {
return subAgentResults.values()
.stream()
.map(Object::toString)
.reduce("", (a, b) -> a.isEmpty() ? b : a + separator + b);
}
}
}
使用示例:
LoopAgent loopAgent = LoopAgent.builder()
.name("example-loop-agent")
.description("循环智能体示例")
.loopStrategy(LoopMode.condition(messagePredicate))
.subAgent(subAgent)
.build();
2.3 LoopAgent
源码如下:
public class LoopAgent extends FlowAgent {
/** 循环策略对象 */
private final LoopStrategy loopStrategy;
/** 配置常量:循环策略的Key */
public static final String LOOP_STRATEGY = "loopStrategy";
/**
* 构造方法:通过建造器初始化参数
*/
private LoopAgent(LoopAgentBuilder builder) {
super(builder.name, builder.description, builder.compileConfig, builder.subAgents,
builder.stateSerializer, builder.executor, builder.hooks);
this.loopStrategy = builder.loopStrategy;
}
/**
* 重写父类方法:构建【循环类型】的状态图
* 将循环策略注入配置,交由 FlowGraphBuilder 构建循环工作流
*/
@Override
protected StateGraph buildSpecificGraph(FlowGraphBuilder.FlowGraphConfig config) throws GraphStateException {
config.customProperty(LOOP_STRATEGY, loopStrategy);
return FlowGraphBuilder.buildGraph(FlowAgentEnum.LOOP.getType(), config);
}
/**
* 建造器入口:链式创建 LoopAgent 实例
*/
public static LoopAgentBuilder builder() {
return new LoopAgentBuilder();
}
/**
* 【循环智能体建造器】
* 重写通用建造器,强制约束:仅支持单个子智能体、必须配置循环策略
*/
public static class LoopAgentBuilder extends FlowAgentBuilder<LoopAgent, LoopAgentBuilder> {
/** 循环策略(必填) */
private LoopStrategy loopStrategy = null;
/**
* 返回当前建造器实例,支持链式调用
*/
@Override
protected LoopAgentBuilder self() {
return this;
}
/**
* 设置【单个】子智能体(LoopAgent 唯一支持的子智能体配置方式)
* @param subAgent 循环中重复执行的子智能体
*/
public LoopAgentBuilder subAgent(Agent subAgent)
{
this.subAgents = List.of(subAgent);
return self();
}
/**
* 重写:禁用批量设置子智能体
* 强制约束:LoopAgent 只能有一个子智能体,禁止调用此方法
*/
@Override
public LoopAgentBuilder subAgents(List<Agent> subAgents) {
throw new UnsupportedOperationException("LoopAgent 必须且只能有一个子智能体,请使用 subAgent() 方法。");
}
/**
* 设置循环策略(必填)
*/
public LoopAgentBuilder loopStrategy(LoopStrategy loopStrategy) {
this.loopStrategy = loopStrategy;
return self();
}
/**
* 参数校验:强制校验循环策略不能为空
*/
@Override
protected void validate() {
super.validate();
if (this.loopStrategy == null) {
throw new IllegalArgumentException("LoopAgent 必须配置循环策略 loopStrategy。");
}
}
/**
* 构建 LoopAgent 实例
*/
@Override
public LoopAgent doBuild() {
validate();
return new LoopAgent(this);
}
}
}
2.4 LlmRoutingAgent
核心属性:
public class LlmRoutingAgent extends FlowAgent {
/** 大模型实例(用于做路由决策,必填) */
private final ChatModel chatModel;
/** 兜底智能体名称(路由决策失败/无匹配时,执行该智能体) */
private final String fallbackAgent;
/** 路由系统提示词(定义路由智能体的角色、规则) */
private final String systemPrompt;
/** 路由指令(具体的路由执行指令) */
private final String instruction;
其他源码内容:
public class LlmRoutingAgent extends FlowAgent {
/**
* 构造方法:通过建造器初始化所有配置
*/
protected LlmRoutingAgent(LlmRoutingAgentBuilder builder) {
super(builder.name, builder.description, builder.compileConfig, builder.subAgents,
builder.stateSerializer, builder.executor, builder.hooks);
this.chatModel = builder.chatModel;
this.fallbackAgent = builder.fallbackAgent;
this.systemPrompt = builder.systemPrompt;
this.instruction = builder.instruction;
}
/**
* 静态建造器入口:链式创建 LlmRoutingAgent 实例
*/
public static LlmRoutingAgentBuilder builder() {
return new LlmRoutingAgentBuilder();
}
// ========== Getter 方法 ==========
public String getFallbackAgent() {
return fallbackAgent;
}
public String getSystemPrompt() {
return systemPrompt;
}
public String getInstruction() {
return instruction;
}
/**
* 重写父类抽象方法:构建【路由类型】的状态图
* 注入大模型实例,交由 FlowGraphBuilder 构建路由工作流
*/
@Override
protected StateGraph buildSpecificGraph(FlowGraphBuilder.FlowGraphConfig config) throws GraphStateException {
// 向图配置中注入大模型(路由决策核心依赖)
config.setChatModel(this.chatModel);
// 构建路由类型的状态图
return FlowGraphBuilder.buildGraph(FlowAgentEnum.ROUTING.getType(), config);
}
/**
* 【LLM路由智能体建造器】
* 继承通用 FlowAgentBuilder,扩展大模型路由专属配置
* 强制校验:必须指定 ChatModel
*/
public static class LlmRoutingAgentBuilder extends FlowAgentBuilder<LlmRoutingAgent, LlmRoutingAgentBuilder> {
/** 大模型(必填,路由决策核心) */
private ChatModel chatModel;
/** 兜底智能体(可选) */
private String fallbackAgent;
/** 系统提示词(可选) */
private String systemPrompt;
/** 路由指令(可选) */
private String instruction;
/**
* 设置路由决策使用的大模型(必填)
* @param chatModel Spring AI 大模型实例
* @return 建造器实例
*/
public LlmRoutingAgentBuilder model(ChatModel chatModel) {
this.chatModel = chatModel;
return this;
}
/**
* 设置兜底智能体(路由无匹配时执行)
*/
public LlmRoutingAgentBuilder fallbackAgent(String fallbackAgent) {
this.fallbackAgent = fallbackAgent;
return this;
}
/**
* 设置路由系统提示词
*/
public LlmRoutingAgentBuilder systemPrompt(String systemPrompt) {
this.systemPrompt = systemPrompt;
return this;
}
/**
* 设置路由执行指令
*/
public LlmRoutingAgentBuilder instruction(String instruction) {
this.instruction = instruction;
return this;
}
/**
* 返回当前建造器实例,支持链式调用
*/
@Override
protected LlmRoutingAgentBuilder self() {
return this;
}
/**
* 核心校验:路由智能体必须配置 ChatModel
*/
@Override
protected void validate() {
super.validate();
if (chatModel == null) {
throw new IllegalArgumentException("LLM路由智能体必须指定 ChatModel 大模型实例");
}
}
/**
* 构建最终的 LlmRoutingAgent 实例
*/
@Override
public LlmRoutingAgent doBuild() {
validate();
return new LlmRoutingAgent(this);
}
}
极简使用示例:
// 1. 注入大模型
@Autowired
private ChatModel chatModel;
// 2. 创建多个带独立动态工具的子智能体
Agent customerServiceAgent = createAgentWithTool("客服智能体", "orderQuery,refund");
Agent opsAgent = createAgentWithTool("运维智能体", "logQuery,monitor");
Agent officeAgent = createAgentWithTool("办公智能体", "summary,parse");
// 3. 构建 LLM 路由智能体
LlmRoutingAgent routingAgent = LlmRoutingAgent.builder()
.name("企业统一智能体入口")
.description("根据用户问题,智能路由到对应场景智能体")
.model(chatModel) // 必选:大模型
.fallbackAgent("customerServiceAgent") // 兜底:客服智能体
.systemPrompt("你是智能路由助手,根据用户问题选择对应智能体")
.subAgents(List.of(customerServiceAgent, opsAgent, officeAgent)) // 路由候选池
.build();
// 4. 执行:自动路由 + 调用对应工具
routingAgent.run(userMessage);
3. FlowAgentBuilder
FlowAgentBuilder 是所有 FlowAgent 的通用建造器父类,提供统一的配置项 + 链式调用 API + 自动校验 + 编译逻辑,子类只需要实现具体智能体创建即可。
类结构与泛型解释:
public abstract class FlowAgentBuilder<
T extends FlowAgent, // 要构建的智能体类型(如 SequentialAgent)
B extends FlowAgentBuilder<T, B> // 建造器自身类型(支持链式调用)
>
核心配置属性:
| 属性 | 作用 |
|---|---|
| name | 智能体名称(必填) |
| description | 智能体能力/用途描述 |
| compileConfig | 图编译配置(执行策略、检查点、运行规则) |
| saver | 状态持久化组件(检查点保存/恢复) |
| subAgents | 子智能体列表(Flow 流程核心,承载多节点编排) |
| stateSerializer | 状态序列化器(用于状态存储、反序列化、上下文持久化) |
| executor | 并行执行线程池(支撑并行节点、异步任务调度) |
| hooks | 执行钩子(拦截增强:日志打印、内容过滤、消息裁剪、链路监控、权限校验) |
四大构建器对比表:
| 特性 | Sequential | Parallel | Loop | LlmRouting |
|---|---|---|---|---|
| 执行方式 | 顺序 | 并行 | 循环 | 智能路由 |
| 子智能体数量 | 1+ | 2~10 | 固定 1 个 | 1+ |
| 必选配置 | name、subAgents | name、subAgents | name、subAgent、loopStrategy | name、subAgents、chatModel |
| 结果合并 | 顺序传递 | 支持 3 种策略 | 覆盖 / 累积 | 路由到单个执行 |
| 适用场景 | 步骤流程 | 并发任务 | 重试 / 迭代 | 意图分发 |
需要我给表格补充每个特性的简要说明,让表格更易理解吗?
3.1 SequentialAgentBuilder
专门用于创建 SequentialAgent 实例的建造器类。
public static class SequentialAgentBuilder extends FlowAgentBuilder<SequentialAgent, SequentialAgentBuilder> {
/**
* 实现父类的抽象方法,返回当前建造器实例
* 作用:支持链式调用(.name().subAgents()...),保证调用后类型不丢失
*/
@Override
protected SequentialAgentBuilder self() {
return this;
}
/**
* 校验建造器参数合法性
* 直接复用父类 FlowAgentBuilder 的校验逻辑
* 可在此处扩展 SequentialAgent 专属的校验规则(当前无额外校验)
*/
@Override
protected void validate() {
super.validate();
// 如需顺序智能体特有校验,可在此添加
}
/**
* 实际创建 SequentialAgent 实例
* 1. 先执行参数校验
* 2. 将建造器自身(包含所有已配置属性)传入构造方法,创建并返回顺序智能体对象
*/
@Override
public SequentialAgent doBuild() {
validate();
return new SequentialAgent(this);
}
}
3.2 ParallelAgentBuilder
用于创建 ParallelAgent(并行执行智能体)的建造器。
/**
* 并行智能体建造器
* 用于创建 ParallelAgent(并行执行智能体)的建造器
* 继承通用 FlowAgentBuilder,提供类型安全的并行流程构建能力
*
* <p>
* 使用示例:
* </p>
*
* <pre>{@code
* ParallelAgent parallelAgent = ParallelAgent.builder()
* .name("parallel_workflow")
* .description("多任务并行执行")
* .inputKey("input")
* .outputKey("output")
* .mergeStrategy(new ParallelAgent.ListMergeStrategy())
* .maxConcurrency(5)
* .subAgents(List.of(agent1, agent2, agent3))
* .build();
* }</pre>
*/
public static class ParallelAgentBuilder extends FlowAgentBuilder<ParallelAgent, ParallelAgentBuilder> {
// ========================== 并行智能体专属配置属性 ==========================
/**
* 结果合并策略:多个子智能体执行完成后,如何合并结果
*/
private MergeStrategy mergeStrategy;
/**
* 最大并发数:控制同时执行的子智能体数量
*/
private Integer maxConcurrency;
/**
* 合并后的输出 key(用于将合并结果存入状态)
*/
private String mergeOutputKey;
/**
* 设置并行执行结果的合并策略
* @param mergeStrategy 合并策略
* @return 建造器自身,支持链式调用
*/
public ParallelAgentBuilder mergeStrategy(MergeStrategy mergeStrategy) {
this.mergeStrategy = mergeStrategy;
return this;
}
/**
* 设置合并结果的输出 key
*/
public ParallelAgentBuilder mergeOutputKey(String mergeOutputKey) {
this.mergeOutputKey = mergeOutputKey;
return this;
}
/**
* 设置子智能体列表(重写父类方法,增加强校验)
* 校验:
* 1. 子智能体不能为空
* 2. 必须是 BaseAgent 类型
*/
@Override
public ParallelAgentBuilder subAgents(List<Agent> subAgents) {
if (subAgents == null || subAgents.isEmpty()) {
throw new IllegalArgumentException("Sub-agents must be provided");
}
if (subAgents.stream().anyMatch(agent -> !(agent instanceof BaseAgent))) {
throw new IllegalArgumentException("Sub-agents must be BaseAgent");
}
return super.subAgents(subAgents);
}
/**
* 设置最大并发数
*/
public ParallelAgentBuilder maxConcurrency(Integer maxConcurrency) {
this.maxConcurrency = maxConcurrency;
return this;
}
/**
* 链式调用必须实现:返回自身
*/
@Override
protected ParallelAgentBuilder self() {
return this;
}
// ========================== 核心校验逻辑(ParallelAgent 专用) ==========================
/**
* 校验建造器配置是否合法
* 并行智能体有非常严格的校验规则
*/
@Override
protected void validate() {
// 1. 名称必须非空
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Name must be provided");
}
// 2. 必须至少 2 个子智能体才能并行
if (subAgents == null || subAgents.size() < 2) {
throw new IllegalArgumentException(
"ParallelAgent requires at least 2 sub-agents for parallel execution, but got: "
+ (subAgents != null ? subAgents.size() : 0));
}
// 3. 最多支持 10 个(性能限制)
if (subAgents.size() > 10) {
throw new IllegalArgumentException(
"ParallelAgent supports maximum 10 sub-agents for performance reasons, but got: "
+ subAgents.size());
}
// 4. 校验所有子智能体的 outputKey 必须唯一(避免合并冲突)
validateUniqueOutputKeys();
// 5. 校验输入 key 兼容性
validateInputKeyCompatibility();
// 6. 并发数必须 >=1
if (maxConcurrency != null) {
if (maxConcurrency < 1) {
throw new IllegalArgumentException("maxConcurrency must be at least 1, but got: " + maxConcurrency);
}
}
}
/**
* 校验:所有子智能体的 outputKey 必须唯一,否则合并时会覆盖
*/
private void validateUniqueOutputKeys() {
Set<String> outputKeys = new HashSet<>();
Set<String> duplicateKeys = new HashSet<>();
for (Agent subAgent : subAgents) {
if (subAgent instanceof ReactAgent subReactAgent) {
String outputKey = subReactAgent.getOutputKey();
if (outputKey != null) {
if (!outputKeys.add(outputKey)) {
duplicateKeys.add(outputKey);
}
}
}
}
if (!duplicateKeys.isEmpty()) {
throw new IllegalArgumentException(
"ParallelAgent validation failed: Duplicate output keys found among sub-agents: "
+ duplicateKeys
+ ". Each sub-agent must have a unique output key to avoid conflicts during result merging.");
}
}
/**
* 校验子智能体输入输出兼容性,避免数据流断裂
*/
private void validateInputKeyCompatibility() {
for (Agent subAgent : subAgents) {
if (!(subAgent instanceof ReactAgent)) {
continue;
}
String subAgentOutputKey = ((ReactAgent)subAgent).getOutputKey();
if (subAgentOutputKey == null) {
logger.warn("Sub-agent '{}' has no outputKey defined. This may cause data flow issues "
+ "as downstream agents won't receive data from this agent.", subAgent.name());
}
}
}
/**
* 实际创建 ParallelAgent 实例
*/
@Override
public ParallelAgent doBuild() {
validate();
return new ParallelAgent(this);
}
}
// ========================== 内置合并策略(3 种最常用) ==========================
/**
* 默认合并策略:将结果转为 Map
* key = 子智能体名称 / outputKey
* value = 执行结果
*/
public static class DefaultMergeStrategy implements MergeStrategy {
@Override
public Object merge(Map<String, Object> subAgentResults, OverAllState overallState) {
return new HashMap<>(subAgentResults);
}
}
/**
* List 合并策略:将所有结果收集到 List 中
*/
public static class ListMergeStrategy implements MergeStrategy {
@Override
public Object merge(Map<String, Object> subAgentResults, OverAllState overallState) {
return subAgentResults.values().stream().toList();
}
}
/**
* 字符串拼接合并策略:用于文本结果拼接
*/
public static class ConcatenationMergeStrategy implements MergeStrategy {
private final String separator;
public ConcatenationMergeStrategy() {
this("\n");
}
public ConcatenationMergeStrategy(String separator) {
this.separator = separator;
}
@Override
public Object merge(Map<String, Object> subAgentResults, OverAllState overallState) {
return subAgentResults.values()
.stream()
.map(Object::toString)
.reduce("", (a, b) -> a.isEmpty() ? b : a + separator + b);
}
}
3.3 LoopAgentBuilder
用于创建 LoopAgent(循环执行智能体)的建造器。
public static class LoopAgentBuilder extends FlowAgentBuilder<LoopAgent, LoopAgentBuilder> {
/**
* 循环策略(核心):决定【什么时候停止循环】【是否继续循环】
* 例如:固定次数循环、条件满足停止循环
*/
private LoopStrategy loopStrategy = null;
/**
* 实现父类抽象方法,返回当前建造器实例
* 作用:支持链式调用,保证调用后类型不丢失
*/
@Override
protected LoopAgentBuilder self() {
return this;
}
/**
* 设置【单个】循环执行的子智能体
* LoopAgent 设计:只能循环执行【一个】子智能体
* @param subAgent 要循环执行的智能体
* @return 建造器实例
*/
public LoopAgentBuilder subAgent(Agent subAgent) {
this.subAgents = List.of(subAgent);
return self();
}
/**
* 重写禁止使用批量设置子智能体方法
* LoopAgent 强制只能有【一个】子智能体,因此抛出不支持操作异常
*/
@Override
public LoopAgentBuilder subAgents(List<Agent> subAgents) {
throw new UnsupportedOperationException(
"LoopAgent must have only one subAgent, please use subAgent() method."
);
}
/**
* 设置循环策略(必须设置)
* @param loopStrategy 循环策略
* @return 建造器实例
*/
public LoopAgentBuilder loopStrategy(LoopStrategy loopStrategy) {
this.loopStrategy = loopStrategy;
return self();
}
/**
* 校验建造器参数合法性
* 1. 复用父类基础校验(name 非空、子智能体非空)
* 2. 扩展校验:必须设置 loopStrategy
*/
@Override
protected void validate() {
// 父类校验:name 非空、subAgents 非空
super.validate();
// 循环智能体专属校验:必须设置循环策略
if (this.loopStrategy == null) {
throw new IllegalArgumentException("LoopAgent must have a loopStrategy.");
}
}
/**
* 实际创建 LoopAgent 实例
* 1. 执行校验
* 2. 将建造器自身(所有配置)传入构造方法
*/
@Override
public LoopAgent doBuild() {
validate();
return new LoopAgent(this);
}
}
3.4 LlmRoutingAgentBuilder
用于创建 LlmRoutingAgent(基于大模型智能路由的智能体)的建造器。
public static class LlmRoutingAgentBuilder extends FlowAgentBuilder<LlmRoutingAgent, LlmRoutingAgentBuilder> {
// ========================== LLM 路由专属配置属性 ==========================
/**
* 大模型(必填):用于做路由决策的 ChatModel
*/
private ChatModel chatModel;
/**
* 降级/兜底智能体名称:当 LLM 无法判断时,执行该智能体
*/
private String fallbackAgent;
/**
* 系统提示词:给 LLM 的身份、角色、规则定义
*/
private String systemPrompt;
/**
* 路由指令:告诉 LLM 如何根据用户问题选择子智能体
*/
private String instruction;
/**
* 设置路由决策使用的大模型(必填)
* @param chatModel 大模型实例
* @return 建造器自身,支持链式调用
*/
public LlmRoutingAgentBuilder model(ChatModel chatModel) {
this.chatModel = chatModel;
return this;
}
/**
* 设置兜底智能体(路由失败时执行)
*/
public LlmRoutingAgentBuilder fallbackAgent(String fallbackAgent) {
this.fallbackAgent = fallbackAgent;
return this;
}
/**
* 设置系统提示词(定义路由智能体的角色)
*/
public LlmRoutingAgentBuilder systemPrompt(String systemPrompt) {
this.systemPrompt = systemPrompt;
return this;
}
/**
* 设置路由指令(告诉 LLM 如何选择子智能体)
*/
public LlmRoutingAgentBuilder instruction(String instruction) {
this.instruction = instruction;
return this;
}
/**
* 链式调用必须实现:返回自身
*/
@Override
protected LlmRoutingAgentBuilder self() {
return this;
}
/**
* 校验建造器配置是否合法
* 1. 父类基础校验:name 非空、子智能体非空
* 2. 专属校验:必须设置 ChatModel
*/
@Override
protected void validate() {
super.validate();
if (chatModel == null) {
throw new IllegalArgumentException("ChatModel must be provided for LLM routing agent");
}
}
/**
* 实际创建 LlmRoutingAgent 实例
*/
@Override
public LlmRoutingAgent doBuild() {
validate();
return new LlmRoutingAgent(this);
}
}
4. 构建流程

4.1 构建入口
所有 FlowAgent 建造器的 build() 方法,调用的都是抽象父类 FlowAgentBuilder,再调用子类实现的 doBuild() 创建具体智能体:
/**
* 【模板方法】构建具体的 FlowAgent 实例
* @return 构建完成的 FlowAgent 实例
* @throws GraphStateException 智能体创建失败时抛出异常
*/
public T build() {
// ====================== 公共逻辑:统一处理状态持久化配置 ======================
// 如果配置了状态持久化器(saver,用于智能体状态保存/恢复)
if (this.saver != null) {
// 场景1:若编译配置(CompileConfig)为空,创建新的编译配置,并注册持久化器
if (this.compileConfig == null) {
this.compileConfig = CompileConfig.builder()
.saverConfig(SaverConfig.builder()
.register(saver) // 注册状态持久化器
.build())
.build();
}
// 场景2:若编译配置已存在,基于原有配置,覆盖/注入持久化配置
else {
this.compileConfig = CompileConfig.builder(compileConfig)
.saverConfig(SaverConfig.builder()
.register(saver)
.build())
.build();
}
}
// ====================== 调用子类实现:创建具体智能体实例 ======================
return doBuild();
}
doBuild() 会先进行校验,再调用 SequentialAgent 构造函数:
/**
* 重写:抽象构建方法
* 完成校验后,创建并返回 SequentialAgent 具体实例
* @return 构建完成的顺序执行智能体
*/
@Override
public SequentialAgent doBuild() {
// 执行参数校验(确保所有配置合法)
validate();
// 通过构造方法创建 SequentialAgent,传入当前建造器的所有配置
return new SequentialAgent(this);
}
/**
* 重写:参数校验方法
* 先执行父类通用校验,再扩展顺序智能体专属校验(可扩展)
*/
@Override
protected void validate() {
// 1. 执行父类 FlowAgentBuilder 的基础校验(必填项:名称、子智能体非空等)
super.validate();
// 2. 扩展点:此处可添加 SequentialAgent 专属的参数校验规则(当前无额外校验)
}
校验智能体名称 name 非空,智能体列表 subAgents 非空
protected void validate() {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Name must be provided");
}
if (subAgents == null || subAgents.isEmpty()) {
throw new IllegalArgumentException("At least one sub-agent must be provided for flow");
}
}
4.2 构造函数
SequentialAgent 构造函数中都是调用的父类的构造进行初始化:
protected SequentialAgent(SequentialAgentBuilder builder) {
super(builder.name, builder.description, builder.compileConfig, builder.subAgents, builder.stateSerializer, builder.executor, builder.hooks);
}
protected FlowAgent(String name, String description, CompileConfig compileConfig, List<Agent> subAgents,
StateSerializer stateSerializer, Executor executor, List<Hook> hooks) {
super(name, description);
this.compileConfig = compileConfig;
this.subAgents = subAgents;
this.stateSerializer = stateSerializer;
this.executor = executor;
this.hooks = hooks;
}
protected Agent(String name, String description) {
this.name = name;
this.description = description;
}
4.3 初始化状态图
图在第一次执行时,会调用 FlowAgent #initGraph() 进行初始化,统一为所有子类(顺序 / 并行 / 循环 / 路由智能体)初始化状态图(StateGraph):
/**
* 重写父类方法:初始化状态图(StateGraph)
* 所有 FlowAgent 子类(顺序/并行/循环/路由)统一复用此模板方法
* @return 构建完成的状态图对象
* @throws GraphStateException 状态图构建失败时抛出异常
*/
@Override
protected StateGraph initGraph() throws GraphStateException {
// ====================== 1. 构建流图基础配置 ======================
// 使用 FlowGraphBuilder 构建工作流配置,封装智能体核心属性
FlowGraphBuilder.FlowGraphConfig config = FlowGraphBuilder.FlowGraphConfig.builder()
.name(this.name()) // 设置智能体名称
.rootAgent(this) // 设置当前智能体为【根智能体】(工作流入口)
.subAgents(this.subAgents()); // 设置子智能体列表
// ====================== 2. 注入可选配置 ======================
// 如果配置了状态序列化器(用于状态持久化/断点续跑),则注入配置
if (this.stateSerializer != null) {
config.stateSerializer(this.stateSerializer);
}
// 如果配置了钩子函数(日志/裁剪/权限/工具扩展),则注入配置
if (this.hooks != null && !this.hooks.isEmpty()) {
config.hooks(this.hooks);
}
// ====================== 3. 子类实现具体图构建逻辑 ======================
// 调用抽象方法 buildSpecificGraph,由子类实现【顺序/并行/循环/路由】的具体图构建
return buildSpecificGraph(config);
}
接着进入到子类中的具体构建【顺序执行】类型的状态图方法:
/**
* 重写父类抽象方法:构建【顺序执行】类型的状态图
* @param config 流图通用配置(名称、子智能体、钩子、序列化器等)
* @return 构建完成的顺序执行状态图
* @throws GraphStateException 图构建失败异常
*/
@Override
protected StateGraph buildSpecificGraph(FlowGraphBuilder.FlowGraphConfig config) throws GraphStateException {
// 调用统一的流图构建器,传入【顺序类型】和通用配置,生成StateGraph
return FlowGraphBuilder.buildGraph(FlowAgentEnum.SEQUENTIAL.getType(), config);
}
4.4 图构建器
使用策略模式 ,从【策略注册器】中,根据类型创建对应的图构建策略,再调用具体策略,执行图构建逻辑:
/**
* 流图构建器(统一调度器)
* 所有FlowAgent的状态图构建,最终都会走到这个静态方法
*/
public class FlowGraphBuilder {
/**
* 通用图构建方法:根据策略类型,分发到对应的具体构建逻辑
* @param strategyType 策略类型(对应FlowAgentEnum:SEQUENTIAL/PARALLEL/LOOP/ROUTING)
* @param config 图构建的所有配置参数
* @return 最终构建完成的StateGraph(状态图)
* @throws GraphStateException 图构建失败抛出异常
*/
public static StateGraph buildGraph(String strategyType, FlowGraphConfig config) throws GraphStateException {
// 1. 从【策略注册器】中,根据类型创建对应的图构建策略
FlowGraphBuildingStrategy strategy = FlowGraphBuildingStrategyRegistry.getInstance().createStrategy(strategyType);
// 2. 执行策略专属的配置校验
strategy.validateConfig(config);
// 3. 调用具体策略,执行图构建逻辑
return strategy.buildGraph(config);
}
}
4.4.1 FlowGraphBuildingStrategyRegistry
【流图构建策略注册中心】负责所有 FlowGraphBuildingStrategy(图构建策略)的注册、查询、创建。
核心能力:
- 动态注册新的图构建策略,无需修改框架核心代码(符合开闭原则)
- 线程安全设计,支持多线程环境下的策略注册与获取
- 单例全局唯一,统一管理所有策略
/**
* 【流图构建策略注册中心】
* 负责所有 FlowGraphBuildingStrategy(图构建策略)的注册、查询、创建
*
* 核心能力:
* 1. 动态注册新的图构建策略,无需修改框架核心代码(符合开闭原则)
* 2. 线程安全设计,支持多线程环境下的策略注册与获取
* 3. 单例全局唯一,统一管理所有策略
*
* 所有 FlowAgent(顺序/并行/循环/路由)的图构建策略,都由此类管理
*/
public class FlowGraphBuildingStrategyRegistry {
/** 单例实例:全局唯一的注册中心对象 */
private static final FlowGraphBuildingStrategyRegistry INSTANCE = new FlowGraphBuildingStrategyRegistry();
/**
* 策略工厂容器:线程安全的 ConcurrentHashMap
* Key:策略类型(如 sequential/parallel/loop/routing)
* Value:策略工厂(Supplier 函数式接口,用于创建策略实例)
*/
private final Map<String, Supplier<FlowGraphBuildingStrategy>> strategyFactories = new ConcurrentHashMap<>();
/**
* 私有构造方法:禁止外部实例化,保证单例
* 构造时自动注册框架内置的默认策略
*/
private FlowGraphBuildingStrategyRegistry() {
registerDefaultStrategies();
}
/**
* 获取单例实例:全局唯一入口
*/
public static FlowGraphBuildingStrategyRegistry getInstance() {
return INSTANCE;
}
/**
* 注册策略实例:每次获取返回同一个对象(单例策略)
* @param strategy 具体的图构建策略
*/
public void registerStrategy(FlowGraphBuildingStrategy strategy) {
if (strategy == null) {
throw new IllegalArgumentException("策略实例不能为空");
}
String type = strategy.getStrategyType();
if (type == null || type.trim().isEmpty()) {
throw new IllegalArgumentException("策略类型不能为空");
}
if (strategyFactories.containsKey(type)) {
throw new IllegalArgumentException("策略类型 '" + type + "' 已注册,不可重复注册");
}
// 存入工厂:固定返回当前策略实例
strategyFactories.put(type, () -> strategy);
}
/**
* 注册策略工厂:每次获取创建新实例(原型策略)
* 适用于每次构建都需要新策略对象的场景
* @param type 策略类型
* @param factory 策略工厂(创建新实例)
*/
public void registerStrategy(String type, Supplier<FlowGraphBuildingStrategy> factory) {
if (type == null || type.trim().isEmpty()) {
throw new IllegalArgumentException("策略类型不能为空");
}
if (factory == null) {
throw new IllegalArgumentException("策略工厂不能为空");
}
if (strategyFactories.containsKey(type)) {
throw new IllegalArgumentException("策略类型 '" + type + "' 已注册");
}
strategyFactories.put(type, factory);
}
/**
* 创建策略实例:调用工厂生成新的策略对象
* 内置策略:每次返回新实例
* 手动注册实例:每次返回同一实例
*/
public FlowGraphBuildingStrategy createStrategy(String type) {
if (type == null || type.trim().isEmpty()) {
throw new IllegalArgumentException("策略类型不能为空");
}
Supplier<FlowGraphBuildingStrategy> factory = strategyFactories.get(type);
if (factory == null) {
throw new IllegalArgumentException("未找到策略类型: " + type);
}
// 执行工厂方法,创建/获取策略实例
return factory.get();
}
/**
* 获取策略实例(别名方法,底层调用 createStrategy)
*/
public FlowGraphBuildingStrategy getStrategy(String type) {
return createStrategy(type);
}
/**
* 判断指定类型的策略是否已注册
*/
public boolean hasStrategy(String type) {
return type != null && strategyFactories.containsKey(type);
}
/**
* 获取所有已注册的策略类型
*/
public Set<String> getRegisteredTypes() {
return Set.copyOf(strategyFactories.keySet());
}
/**
* 注销指定策略(主要用于测试)
*/
public Supplier<FlowGraphBuildingStrategy> unregisterStrategy(String type) {
return strategyFactories.remove(type);
}
/**
* 清空所有策略(主要用于测试)
*/
public void clear() {
strategyFactories.clear();
}
/**
* 注册框架【内置默认策略】
* 所有官方 FlowAgent 对应的图构建策略,都在这里初始化
* 采用 工厂方法::new 模式,每次创建新实例
*/
private void registerDefaultStrategies() {
registerStrategy(FlowAgentEnum.SEQUENTIAL.getType(), SequentialGraphBuildingStrategy::new);
registerStrategy(FlowAgentEnum.ROUTING.getType(), RoutingGraphBuildingStrategy::new);
registerStrategy(FlowAgentEnum.PARALLEL.getType(), ParallelGraphBuildingStrategy::new);
registerStrategy(FlowAgentEnum.CONDITIONAL.getType(), ConditionalGraphBuildingStrategy::new);
registerStrategy(FlowAgentEnum.LOOP.getType(), LoopGraphBuildingStrategy::new);
}
}
注册中心初始化时,自动注册 5 种官方策略:
SEQUENTIAL→SequentialGraphBuildingStrategy(顺序)ROUTING→RoutingGraphBuildingStrategy(路由)PARALLEL→ParallelGraphBuildingStrategy(并行)LOOP→LoopGraphBuildingStrategy(循环)CONDITIONAL→ConditionalGraphBuildingStrategy(条件分支)
4.4.2 SequentialGraphBuildingStrategy
【顺序执行图构建策略】实现线性顺序执行流程,子智能体按添加顺序串联,前一个执行完成 → 后一个执行。
public class SequentialGraphBuildingStrategy extends AbstractFlowGraphBuildingStrategy {
/**
* 【核心】构建顺序图的核心逻辑
*/
@Override
protected void buildCoreGraph(FlowGraphBuilder.FlowGraphConfig config)
throws GraphStateException {
// 1. 专属校验:至少1个子智能体
validateSequentialConfig(config);
// 2. 定义顺序流程入口:根智能体名称
String sequentialStartNode = getRootAgent().name();
// 3. 添加【透明节点】作为流程入口(无业务逻辑,仅做流转)
this.graph.addNode(sequentialStartNode, node_async(new TransparentNode()));
// 4. 连接前置钩子(如果有)到入口节点
if (!this.beforeModelHooks.isEmpty()) {
connectBeforeModelHookEdges(this.graph, sequentialStartNode, this.beforeModelHooks);
}
// 5. 🌟 核心:线性串联所有子智能体
Agent currentAgent = getRootAgent();
for (Agent subAgent : config.getSubAgents()) {
// 添加子智能体节点
FlowGraphBuildingStrategy.addSubAgentNode(subAgent, this.graph);
// 建立边:前一个节点 → 当前子节点
this.graph.addEdge(currentAgent.name(), subAgent.name());
// 移动指针,继续串联
currentAgent = subAgent;
}
// 6. 连接后置钩子(如果有)
String finalNode;
if (!this.afterModelHooks.isEmpty()) {
finalNode = connectAfterModelHookEdges(this.graph, currentAgent.name(), this.afterModelHooks);
} else {
finalNode = currentAgent.name();
}
// 7. 最后一个节点连接到出口节点,结束流程
this.graph.addEdge(finalNode, this.exitNode);
}
/**
* 重写:空实现(顺序策略已在核心方法中处理钩子,避免重复连接)
*/
@Override
protected void connectBeforeModelHooks() throws GraphStateException {
}
/**
* 重写:空实现(顺序策略已在核心方法中处理钩子,避免重复连接)
*/
@Override
protected void connectAfterModelHooks() throws GraphStateException {
}
/**
* 返回策略类型:sequential
*/
@Override
public String getStrategyType() {
return FlowAgentEnum.SEQUENTIAL.getType();
}
/**
* 扩展校验:父类通用校验 + 顺序专属校验
*/
@Override
public void validateConfig(FlowGraphBuilder.FlowGraphConfig config) {
super.validateConfig(config);
validateSequentialConfig(config);
}
/**
* 顺序流程专属校验规则
*/
private void validateSequentialConfig(FlowGraphBuilder.FlowGraphConfig config) {
// 必须至少有一个子智能体
if (config.getSubAgents() == null || config.getSubAgents().isEmpty()) {
throw new IllegalArgumentException("顺序流程至少需要一个子智能体");
}
// 根节点必须是 FlowAgent
if (!(config.getRootAgent() instanceof FlowAgent)) {
throw new IllegalArgumentException("顺序流程的根节点必须是 FlowAgent");
}
}
}
4.5 构建完成
所有智能体都是通过对应的 GraphBuildingStrategy 策略类进行构建,SequentialGraphBuildingStrategy 中的核心流程:
- 专属校验:至少
1个子智能体 - 定义顺序流程入口:根智能体名称
- 添加【透明节点】作为流程入口(无业务逻辑,仅做流转)
- 连接前置钩子(如果有)到入口节点
- 🌟 核心:线性串联所有子智能体
- 连接后置钩子(如果有)
- 最后一个节点连接到出口节点,结束流程
/**
* 【核心】构建顺序图的核心逻辑
*/
@Override
protected void buildCoreGraph(FlowGraphBuilder.FlowGraphConfig config)
throws GraphStateException {
// 1. 专属校验:至少1个子智能体
validateSequentialConfig(config);
// 2. 定义顺序流程入口:根智能体名称
String sequentialStartNode = getRootAgent().name();
// 3. 添加【透明节点】作为流程入口(无业务逻辑,仅做流转)
this.graph.addNode(sequentialStartNode, node_async(new TransparentNode()));
// 4. 连接前置钩子(如果有)到入口节点
if (!this.beforeModelHooks.isEmpty()) {
connectBeforeModelHookEdges(this.graph, sequentialStartNode, this.beforeModelHooks);
}
// 5. 🌟 核心:线性串联所有子智能体
Agent currentAgent = getRootAgent();
for (Agent subAgent : config.getSubAgents()) {
// 添加子智能体节点
FlowGraphBuildingStrategy.addSubAgentNode(subAgent, this.graph);
// 建立边:前一个节点 → 当前子节点
this.graph.addEdge(currentAgent.name(), subAgent.name());
// 移动指针,继续串联
currentAgent = subAgent;
}
// 6. 连接后置钩子(如果有)
String finalNode;
if (!this.afterModelHooks.isEmpty()) {
finalNode = connectAfterModelHookEdges(this.graph, currentAgent.name(), this.afterModelHooks);
} else {
finalNode = currentAgent.name();
}
// 7. 最后一个节点连接到出口节点,结束流程
this.graph.addEdge(finalNode, this.exitNode);
}
最终图可视化如下:

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐

所有评论(0)