Supervisor/Executor 多 Agent 协作编排
学习目标
理解 LobeHub 如何通过 GroupOrchestrationRuntime 实现多 Agent 协作编排,包括 Supervisor 状态机决策、Executor 执行层、步骤限制和状态克隆隔离。
前置知识
本章涉及多 Agent 编排模式的通用原理,建议先阅读:
下文假设你已理解上述概念,直接聚焦 LobeHub 的具体实现。
项目实践
Supervisor/Executor 双层架构
LobeHub 的编排循环:
- step() 接收上一步的执行结果和当前状态
- Supervisor 根据结果决定下一步指令类型
- Executor 执行指令并返回结果
- 重复 2-3 直到 Supervisor 返回
finish
步骤限制与状态克隆
// 伪代码:步骤限制async step(state, result): Promise<GroupOrchestrationExecutorOutput> { const newState = structuredClone(state); // 状态克隆隔离 newState.stepCount = (newState.stepCount || 0) + 1;
// 步骤上限检查 if (newState.maxSteps && newState.stepCount > newState.maxSteps) { newState.status = "done"; return { events: [{ type: "done", reason: "Maximum steps exceeded" }], newState }; }
const instruction = await this.supervisor.decide(result, newState); // ...}状态克隆的意义:每次 step 使用 structuredClone 创建状态副本,确保 Executor 的修改不影响原始状态。如果 step 失败,可以从原始状态重试。
性能注意:structuredClone 对大状态(如包含大量消息的 AgentState)有显著开销。
Executor 类型注册
Executor 按指令类型注册:
// 伪代码:Executor 注册interface GroupOrchestrationExecutor { (instruction: SupervisorInstruction, state: AgentState): Promise<ExecutorResult>;}
const executors: Record<string, GroupOrchestrationExecutor> = { "parallel": parallelExecutor, "sequential": sequentialExecutor, "review": reviewExecutor, // 可按需扩展};与 Agent Groups 功能的集成
LobeHub 的 Agent Groups 功能(Pages、Projects、Schedule)在业务层使用 GroupOrchestrationRuntime:
- Pages:多个 Agent 在同一文档上协同编辑
- Projects:按项目组织 Agent 任务
- Schedule:定时执行 Agent 任务
编排运行时负责调度这些场景中的多 Agent 协作。
问题与规避
| 问题 | 场景 | 规避策略 |
|---|---|---|
| 状态克隆性能 | 大 AgentState 的 structuredClone 慢 | 限制 maxSteps,减少不必要的深拷贝 |
| Executor 失败 | 某个 Executor 执行异常 | 捕获异常,通过 Supervisor 决策重试或跳过 |
| 无对应 Executor | Supervisor 返回未注册的指令类型 | 抛出明确错误 “No executor found for type: X” |
| 步骤超限 | 协作循环超过 maxSteps | 直接标记 done,保留当前状态 |
设计取舍
为什么用 Supervisor 状态机而非固定流程?
固定流程(A → B → C)无法处理协作中的分支情况(如审查不通过需要返工)。Supervisor 状态机根据上一步结果动态决策,支持:
- 条件分支(审查通过 → 完成,不通过 → 返工)
- 并行调度(多个 Agent 同时执行)
- 动态终止(达到目标提前结束)
代价:Supervisor 逻辑复杂度随协作场景增长。
参考来源
- LobeHub GroupOrchestrationRuntime —
packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.ts - 编排器模式 — 通用多 Agent 编排原理