Multi-Agent 系统协作实践
目录
不是所有场景都需要多个 Agent。Multi-Agent 只在任务需要不同专业能力、可并行的独立子任务、或多方校验时才值得上。
先说什么时候需要 Multi-Agent
单一 Agent 能搞定:
- 任务边界清晰
- 需要集中决策
- 工具调用链不长
Multi-Agent 值得考虑:
- 任务需要不同专业能力
- 需要并行处理独立子任务
- 决策需要多方校验
- 系统规模大,需要职责分离常见架构
Supervisor + Workers
Supervisor Agent
├── Worker Agent A(负责某领域)
├── Worker Agent B(负责另一领域)
└── Worker Agent C(负责第三领域)// Supervisor 负责任务分解与汇总
interface Worker {
execute(subtask: Subtask): Promise<SubtaskResult>;
}
class Supervisor {
async handle(task: Task): Promise<FinalResult> {
const subtasks = await this.decompose(task);
const results: SubtaskResult[] = [];
for (const subtask of subtasks) {
const worker = this.selectWorker(subtask);
results.push(await worker.execute(subtask));
}
return this.synthesize(results);
}
}适用场景:任务可分解,每个子任务相对独立。
Sequential Pipeline
Agent A → Agent B → Agent C → Agent D// 流水线式:每一步消费前一步输出,按需重试
const pipeline: Array<[string, StageAgent]> = [
["research", new ResearchAgent()],
["analyze", new AnalyzeAgent()],
["write", new WriteAgent()],
["review", new ReviewAgent()],
];
async function runPipeline(initialInput: string): Promise<string> {
let output = initialInput;
for (const [, agent] of pipeline) {
output = await agent.process(output);
if (agent.needsRetry(output)) {
output = await agent.retry(output);
}
}
return output;
}适用场景:有序步骤,每步有明确输入输出。
Parallel + Merge
→ Agent A (并行)
Task → → Agent B (并行) → Merge Agent → Result
→ Agent C (并行)// 同一任务多角度并行处理,再由 Merge Agent 汇总
async function parallelAnalyze(task: Task): Promise<Report> {
const agents = [new ResearchAgent(), new AnalyzeAgent(), new CritiqueAgent()];
const results = await Promise.all(agents.map((agent) => agent.process(task)));
return mergeAgent.synthesize(results);
}适用场景:需要多角度分析、综合不同观点。
通信协议
Multi-Agent 需要通信。有两种方式:
共享消息队列
// 通过共享消息队列异步解耦通信
class QueueAgent {
constructor(
private readonly name: string,
private readonly inbox: AsyncQueue<AgentMessage>,
private readonly outbox: AsyncQueue<AgentMessage>,
) {}
async run(signal: AbortSignal): Promise<void> {
while (!signal.aborted) {
const msg = await this.inbox.dequeue(signal);
const result = await this.process(msg);
await this.outbox.enqueue({
from: this.name,
to: "merge",
content: result,
});
}
}
}显式消息传递
// 显式点对点消息传递
class DirectAgent {
async sendTo(target: string, content: unknown): Promise<void> {
await this.messenger.send({
to: target,
content,
metadata: { priority: "normal" },
});
}
receive(): Promise<AgentMessage> {
return this.messenger.receive(this.id);
}
}踩过的坑
Agent 之间信息丢失
// 解决信息丢失:用强类型契约标准化 Agent 输出
interface ResearchOutput {
findings: string[];
sources: string[];
confidence: number;
rawData: Record<string, unknown>;
}循环依赖
Agent A → Agent B → Agent C
↑ ↓
└─────────────────────┘
# Agent C 依赖 A 的输出
# Agent A 也间接依赖 C// 解决循环依赖:用有向无环图(DAG)编排,并在冲突时显式仲裁
class Orchestrator {
resolveConflict(a: AgentResult, b: AgentResult): AgentResult {
return a.confidence >= b.confidence ? a : b;
}
}调试困难
// 解决调试困难:每个 Agent 记录结构化输入/输出日志,消息队列支持回放
class TracedAgent {
async process(msg: AgentMessage): Promise<AgentResult> {
logger.info({ agent: this.name, event: "received", msgId: msg.id });
const result = await this.processImpl(msg);
logger.info({ agent: this.name, event: "completed", msgId: msg.id, status: result.status });
return result;
}
}框架选择
| 框架 | 适用场景 | 特点 |
|---|---|---|
| LangGraph | 复杂流程编排 | 状态管理强 |
| AutoGen | 多 Agent 对话 | 协作模式丰富 |
| CrewAI | 角色分工明确 | 上手简单 |
| 自建 | 高度定制 | 灵活但工作量大 |
结论
Multi-Agent 的价值:让专业的人做专业的事。
多个 Agent 各有所长,组合起来能处理比单一 Agent 更复杂的任务。但 Multi-Agent 也带来通信、调试与一致性成本(单 Agent 与多 Agent 的架构取舍详见 AI Agent 架构模式)。建议先用单一 Agent,确定上下文或专业边界不够用再拆分。