本文面向 AI 应用开发者,系统拆解多智能体(Multi-Agent)协同的架构模式、通信机制、状态管理与冲突解决。结合图像生成工作流平台的真实场景,讲清楚"多个 AI Agent 如何像团队一样分工协作、互相校验、共同交付"。
本文是「MCP Server 篇」与「Skills 篇」的终章——MCP 解决"怎么调工具",Skills 解决"调什么、怎么编排",本文解决"谁来做、怎么协作"。
一、为什么单 Agent 不够用了?
2024 年底,我们 flowBench 平台遇到一个典型瓶颈:
用户输入:"帮我做一套电商主图,5 张,风格统一,要突出产品卖点,文案自动配,最后导出 PSD 分层文件。"
单个 Agent 的处理过程:
Agent(独自思考):
→ 分析需求...
→ 生成第 1 张图...
→ 等等,文案还没写...
→ 写文案...
→ 回来继续生成第 2 张...
→ 糟糕,第 2 张风格和第 1 张不一致...
→ 重新生成...
→ 导出 PSD...
→ 等等,我刚才第 3 张的参数是什么来着?
→ (上下文溢出,开始幻觉)
三个致命问题:
| 问题 | 表现 | 根因 |
|---|---|---|
| 上下文爆炸 | 一个 Agent 要记住 5 张图的参数、文案、风格约束 | 单窗口装不下 |
| 能力冲突 | 同一个 Prompt 既要"创意发散"又要"严格一致" | 角色矛盾 |
| 串行瓶颈 | 所有步骤排队执行,用户等 3 分钟 | 无法并行 |
解法:不是一个更聪明的 Agent,而是一群各司其职的 Agent。
二、多 Agent 协同的四种架构模式
模式一:Supervisor(主管模式)
┌─────────────┐
│ Supervisor │
│ (调度 Agent) │
└──────┬──────┘
┌────────────┼────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Agent A │ │ Agent B │ │ Agent C │
│ (创意) │ │ (执行) │ │ (质检) │
└──────────┘ └──────────┘ └──────────┘
- Supervisor 接收用户需求,拆解任务,分配给下属 Agent,汇总结果。
- 下属 Agent 互不通信,只和 Supervisor 交互。
- 适合:任务可明确拆解、流程固定的场景。
模式二:Peer-to-Peer(对等协商模式)
┌──────────┐ ┌──────────┐
│ Agent A │◄─────►│ Agent B │
│ (设计) │ │ (文案) │
└────┬─────┘ └─────┬────┘
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│ Agent C │◄─────►│ Agent D │
│ (生成) │ │ (审核) │
└──────────┘ └──────────┘
- 所有 Agent 平等,通过消息总线互相通信。
- 没有中心调度,靠协议和共识协作。
- 适合:创意碰撞、需要多轮讨论的场景(如头脑风暴)。
模式三:Hierarchical(层级模式)
┌─────────────┐
│ Director │
│ (总监) │
└──────┬──────┘
┌────────────┴────────────┐
▼ ▼
┌──────────┐ ┌──────────┐
│ Lead A │ │ Lead B │
│ (视觉组长)│ │ (内容组长)│
└────┬─────┘ └─────┬────┘
┌───┴───┐ ┌───┴───┐
▼ ▼ ▼ ▼
Worker Worker Worker Worker
(生成) (修图) (文案) (排版)
- 多层管理,Director → Lead → Worker。
- 适合:大型复杂项目(如"做一整套品牌视觉")。
模式四:Pipeline(流水线模式)
Agent A ──► Agent B ──► Agent C ──► Agent D
(需求分析) (图像生成) (质量审核) (导出交付)
- 严格串行,上游输出 = 下游输入。
- 适合:流程固定、步骤间强依赖的场景。
我们的选择:Supervisor + Pipeline 混合。 Supervisor 做任务拆解和并行调度,Pipeline 做单条任务内的串行流转。下面以此为主线展开。
三、核心设计:Agent 身份定义
每个 Agent 不是"一段 Prompt",而是一个完整的角色定义:
// src/agent-definition.ts
export interface AgentDefinition {
// ① 身份
id: string;
name: string;
role: string; // 一句话角色定义
systemPrompt: string; // 完整 System Prompt
// ② 能力边界
skills: string[]; // 可调用的 Skill ID 列表
mcpServers: string[]; // 可访问的 MCP Server 列表
canDelegateTo: string[]; // 可以把子任务委托给谁
// ③ 约束
maxIterations: number; // 最大推理轮次(防死循环)
tokenBudget: number; // Token 预算上限
permissions: string[]; // 权限(如 "gpu:use", "file:write")
// ④ 通信
outputFormat: "json" | "markdown" | "structured";
escalationTarget: string; // 搞不定时上报给谁
}
实战:电商主图场景的 Agent 团队
// src/agents/ecommerce-team.ts
export const supervisorAgent: AgentDefinition = {
id: "supervisor",
name: "项目调度",
role: "电商视觉项目调度员,负责需求拆解、任务分配、进度跟踪、结果汇总",
systemPrompt: `你是一个电商视觉项目的调度主管。
你的职责:
1. 接收用户需求,拆解为可执行的子任务
2. 将子任务分配给合适的 Agent
3. 跟踪进度,处理异常(如某 Agent 失败则重试或换人)
4. 汇总所有 Agent 的输出,组装最终交付物
你不亲自做设计、不亲自写文案、不亲自生成图片。你只调度。`,
skills: ["task_decompose", "progress_track", "result_assemble"],
mcpServers: [],
canDelegateTo: ["creative_director", "copywriter", "image_generator", "quality_reviewer", "export_agent"],
maxIterations: 20,
tokenBudget: 8000,
permissions: ["orchestrate"],
outputFormat: "json",
escalationTarget: "human",
};
export const creativeDirectorAgent: AgentDefinition = {
id: "creative_director",
name: "创意总监",
role: "视觉创意方向制定者,负责风格定义、构图规划、色彩方案",
systemPrompt: `你是一个资深电商视觉创意总监。
你的职责:
1. 根据产品卖点和目标受众,制定视觉创意方向
2. 输出:风格关键词、构图方案、色彩方案、每张图的差异化策略
3. 确保 5 张图"风格统一但各有侧重"
你不做具体生成,你输出"创意 Brief"给图像生成 Agent。
你的输出必须是结构化 JSON,包含每张图的 prompt、negative_prompt、参数建议。`,
skills: ["style_analysis", "composition_planning"],
mcpServers: [],
canDelegateTo: [],
maxIterations: 5,
tokenBudget: 4000,
permissions: ["read:product_info"],
outputFormat: "json",
escalationTarget: "supervisor",
};
export const imageGeneratorAgent: AgentDefinition = {
id: "image_generator",
name: "图像生成师",
role: "AI 图像生成执行者,负责调用大模型生成图片",
systemPrompt: `你是一个 AI 图像生成专家。
你的职责:
1. 接收创意 Brief(含 prompt、参数)
2. 调用图像生成工具(通过 MCP Server)
3. 如果生成结果不满意,自主微调参数重试(最多 3 次)
4. 输出:图片 URL + 最终参数 + seed
你不懂创意决策,你只负责"把 Brief 变成图片"。
参数调整策略:
- 构图不对 → 调 prompt 权重
- 细节不够 → 加 steps(25→40)
- 风格偏移 → 调 CFG(7.5→9)`,
skills: ["generate_image", "img2img_refine"],
mcpServers: ["comfyui-server", "flux-server"],
canDelegateTo: [],
maxIterations: 10,
tokenBudget: 3000,
permissions: ["gpu:use", "file:write"],
outputFormat: "json",
escalationTarget: "supervisor",
};
export const qualityReviewerAgent: AgentDefinition = {
id: "quality_reviewer",
name: "质量审核员",
role: "图像质量与合规审核者,负责评分、挑错、合规检查",
systemPrompt: `你是一个严格的电商图像质量审核员。
你的职责:
1. 对每张生成图进行多维度评分(构图/色彩/细节/卖点表达/合规)
2. 检查:是否有文字错误、是否有违规内容、是否符合平台规范
3. 评分 < 7 分的图,给出具体修改建议,打回给图像生成师
4. 所有图通过后,输出审核报告
你绝不修改图片,你只评判。你的标准是"能不能直接上架"。`,
skills: ["analyze_image", "compliance_check"],
mcpServers: ["vision-model-server"],
canDelegateTo: [],
maxIterations: 5,
tokenBudget: 3000,
permissions: ["read:all"],
outputFormat: "json",
escalationTarget: "supervisor",
};
export const copywriterAgent: AgentDefinition = {
id: "copywriter",
name: "文案策划",
role: "电商文案撰写者,负责标题、卖点文案、促销话术",
systemPrompt: `你是一个电商文案策划专家。
你的职责:
1. 根据产品信息和目标受众,撰写主图文案
2. 每张图配:主标题(≤8字)+ 副标题(≤15字)+ 卖点标签(≤3个)
3. 文案风格与视觉风格一致(如赛博朋克风 → 文案也要有科技感)
4. 输出结构化 JSON,供排版 Agent 使用
你不懂设计,你只输出文字内容。`,
skills: ["generate_copy", "tone_adjust"],
mcpServers: [],
canDelegateTo: [],
maxIterations: 5,
tokenBudget: 3000,
permissions: ["read:product_info"],
outputFormat: "json",
escalationTarget: "supervisor",
};
四、通信机制:Agent 之间怎么"说话"
4.1 消息协议
// src/message-protocol.ts
export interface AgentMessage {
id: string; // 消息唯一 ID
from: string; // 发送方 Agent ID
to: string; // 接收方 Agent ID(或 "broadcast")
type: MessageType;
payload: any; // 消息体
replyTo?: string; // 回复哪条消息
timestamp: number;
priority: "low" | "normal" | "high" | "critical";
}
export type MessageType =
| "task_assign" // Supervisor → Worker:分配任务
| "task_result" // Worker → Supervisor:返回结果
| "task_failed" // Worker → Supervisor:报告失败
| "review_request" // Worker → Reviewer:请求审核
| "review_feedback" // Reviewer → Worker:审核意见(通过/打回)
| "clarification" // 任意 → Supervisor:需要澄清
| "status_update" // Worker → Supervisor:进度更新
| "escalation"; // 任意 → Supervisor/Human:上报
4.2 消息总线实现
// src/message-bus.ts
type MessageHandler = (msg: AgentMessage) => Promise<void>;
export class MessageBus {
private handlers = new Map<string, MessageHandler[]>();
private history: AgentMessage[] = [];
private maxHistory = 1000;
// 订阅
subscribe(agentId: string, handler: MessageHandler) {
if (!this.handlers.has(agentId)) {
this.handlers.set(agentId, []);
}
this.handlers.get(agentId)!.push(handler);
}
// 发布
async publish(msg: AgentMessage) {
this.history.push(msg);
if (this.history.length > this.maxHistory) {
this.history.shift();
}
const targets = msg.to === "broadcast"
? [...this.handlers.keys()]
: [msg.to];
for (const target of targets) {
const handlers = this.handlers.get(target) || [];
for (const handler of handlers) {
await handler(msg);
}
}
}
// 查询历史(用于 Agent 回溯上下文)
getHistory(filter?: { from?: string; to?: string; type?: MessageType }): AgentMessage[] {
return this.history.filter(msg => {
if (filter?.from && msg.from !== filter.from) return false;
if (filter?.to && msg.to !== filter.to) return false;
if (filter?.type && msg.type !== filter.type) return false;
return true;
});
}
}
4.3 共享状态(黑板模式)
Agent 之间除了消息传递,还需要共享工作状态:
// src/shared-state.ts
export interface ProjectState {
// 全局信息(所有 Agent 可读)
project: {
id: string;
userRequirement: string;
productInfo: Record<string, any>;
targetAudience: string;
platform: "taobao" | "jd" | "douyin";
};
// 创意方案(创意总监写,其他 Agent 读)
creativeBrief: {
style: string;
colorScheme: string[];
compositions: Array<{
imageIndex: number;
prompt: string;
negativePrompt: string;
params: Record<string, any>;
focus: string; // 这张图侧重什么
}>;
} | null;
// 生成结果(图像生成师写,审核员读)
generatedImages: Array<{
imageIndex: number;
url: string;
seed: number;
finalParams: Record<string, any>;
status: "pending_review" | "approved" | "rejected";
reviewScore?: number;
reviewFeedback?: string;
}>;
// 文案(文案策划写,排版 Agent 读)
copies: Array<{
imageIndex: number;
title: string;
subtitle: string;
tags: string[];
}>;
// 最终交付
deliverables: {
psdUrl?: string;
pngUrls?: string[];
status: "in_progress" | "completed" | "failed";
};
}
export class SharedBlackboard {
private state: ProjectState;
private locks = new Map<string, string>(); // 字段级锁:field → agentId
constructor(initialState: ProjectState) {
this.state = initialState;
}
// 读(任何 Agent 可读)
read<K extends keyof ProjectState>(field: K): ProjectState[K] {
return this.state[field];
}
// 写(需要加锁,防止并发冲突)
async write<K extends keyof ProjectState>(
field: K,
value: ProjectState[K],
agentId: string
): Promise<boolean> {
// 简易锁:同一字段同时只有一个 Agent 可写
if (this.locks.has(field) && this.locks.get(field) !== agentId) {
return false; // 被锁了,稍后重试
}
this.locks.set(field, agentId);
this.state[field] = value;
this.locks.delete(field);
return true;
}
}
五、Supervisor 调度引擎:核心中的核心
// src/supervisor-engine.ts
import OpenAI from "openai";
import { AgentDefinition } from "./agent-definition";
import { MessageBus, AgentMessage } from "./message-bus";
import { SharedBlackboard } from "./shared-state";
import { SkillRegistry } from "./skill-registry";
export class SupervisorEngine {
private llm = new OpenAI();
private agents = new Map<string, AgentDefinition>();
private bus: MessageBus;
private blackboard: SharedBlackboard;
private skillRegistry: SkillRegistry;
constructor(
agents: AgentDefinition[],
bus: MessageBus,
blackboard: SharedBlackboard,
skillRegistry: SkillRegistry
) {
agents.forEach(a => this.agents.set(a.id, a));
this.bus = bus;
this.blackboard = blackboard;
this.skillRegistry = skillRegistry;
}
// ===== 主入口:接收用户需求,驱动整个团队 =====
async execute(userRequirement: string): Promise<ProjectState> {
// Step 1: 需求拆解
const tasks = await this.decompose(userRequirement);
// Step 2: 并行分配(无依赖的任务同时下发)
const parallelGroups = this.buildParallelGroups(tasks);
for (const group of parallelGroups) {
await Promise.all(
group.map(task => this.dispatchToAgent(task))
);
}
// Step 3: 汇总 + 质检循环
await this.qualityLoop();
// Step 4: 组装交付物
await this.assembleDeliverables();
return this.blackboard.read("deliverables");
}
// ===== 需求拆解(LLM 推理) =====
private async decompose(requirement: string): Promise<Task[]> {
const response = await this.llm.chat.completions.create({
model: "gpt-4o",
messages: [{
role: "system",
content: `你是项目调度主管。将用户需求拆解为子任务。
每个子任务包含:id, type, assignTo, dependsOn, input。
可用 Agent:${[...this.agents.values()].map(a => `- ${a.id}: ${a.role}`).join("\n")}
输出 JSON 数组。`
}, {
role: "user",
content: requirement
}],
response_format: { type: "json_object" },
});
return JSON.parse(response.choices[0].message.content!).tasks;
}
// ===== 构建并行组(拓扑排序) =====
private buildParallelGroups(tasks: Task[]): Task[][] {
const groups: Task[][] = [];
const completed = new Set<string>();
while (completed.size < tasks.length) {
const ready = tasks.filter(t =>
!completed.has(t.id) &&
t.dependsOn.every(dep => completed.has(dep))
);
if (ready.length === 0) throw new Error("Circular dependency detected");
groups.push(ready);
ready.forEach(t => completed.add(t.id));
}
return groups;
}
// ===== 分配任务给具体 Agent =====
private async dispatchToAgent(task: Task): Promise<void> {
const agent = this.agents.get(task.assignTo);
if (!agent) throw new Error(`Unknown agent: ${task.assignTo}`);
// 构建 Agent 专属上下文
const context = this.buildAgentContext(agent, task);
// Agent 执行循环
let iterations = 0;
while (iterations < agent.maxIterations) {
iterations++;
const response = await this.llm.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: agent.systemPrompt },
...context.messages,
],
tools: this.getAgentTools(agent),
tool_choice: "auto",
});
const msg = response.choices[0].message;
// 无 tool_call → Agent 认为任务完成
if (!msg.tool_calls?.length) {
// 解析输出,写入黑板
await this.handleAgentOutput(agent, task, msg.content!);
return;
}
// 执行 tool_calls
for (const call of msg.tool_calls) {
const result = await this.skillRegistry.dispatch(
call.function.name,
JSON.parse(call.function.arguments),
{ userId: "system", sessionId: task.id, history: [], resources: {}, executedSkills: [] }
);
context.messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(result),
});
}
}
// 超过最大轮次 → 上报
await this.bus.publish({
id: crypto.randomUUID(),
from: agent.id,
to: "supervisor",
type: "escalation",
payload: { taskId: task.id, reason: "max_iterations_exceeded" },
timestamp: Date.now(),
priority: "high",
});
}
// ===== 质检循环(审核员打回 → 生成师修改 → 再审核) =====
private async qualityLoop(): Promise<void> {
const maxRounds = 3;
for (let round = 0; round < maxRounds; round++) {
// 审核员评审所有待审图片
await this.dispatchToAgent({
id: `review_round_${round}`,
type: "review",
assignTo: "quality_reviewer",
dependsOn: [],
input: { images: this.blackboard.read("generatedImages") },
});
const images = this.blackboard.read("generatedImages");
const rejected = images.filter(img => img.status === "rejected");
if (rejected.length === 0) break; // 全部通过
// 打回的图重新生成
for (const img of rejected) {
await this.dispatchToAgent({
id: `regen_${img.imageIndex}_r${round}`,
type: "regenerate",
assignTo: "image_generator",
dependsOn: [],
input: {
imageIndex: img.imageIndex,
feedback: img.reviewFeedback,
previousParams: img.finalParams,
},
});
}
}
}
}
六、完整执行流程:电商主图实战
用户:"帮我做 5 张电商主图,产品是无线降噪耳机,目标人群 25-35 岁白领,
风格科技感,突出降噪卖点和续航,要适配淘宝 800×800。"
═══════════════════════════════════════════════════
[Supervisor] 需求拆解:
Task 1 → creative_director: 制定 5 张图的创意 Brief
Task 2 → copywriter: 撰写 5 组文案(依赖 Task 1 的风格方向)
Task 3 → image_generator: 生成 5 张图(依赖 Task 1)
Task 4 → quality_reviewer: 审核 5 张图(依赖 Task 3)
Task 5 → export_agent: 导出 PSD + PNG(依赖 Task 4 通过)
═══════════════════════════════════════════════════
[并行组 1] Task 1(创意总监)
输出 Creative Brief:
{
style: "dark tech, gradient blue-purple, clean minimal",
compositions: [
{ index: 1, focus: "产品正面特写 + 降噪波纹可视化", prompt: "..." },
{ index: 2, focus: "佩戴场景 + 城市背景虚化", prompt: "..." },
{ index: 3, focus: "爆炸图展示内部芯片", prompt: "..." },
{ index: 4, focus: "续航数据可视化(72h)", prompt: "..." },
{ index: 5, focus: "多场景拼接(通勤/办公/健身)", prompt: "..." },
]
}
[并行组 2] Task 2 + Task 3(文案 + 生成,并行)
[Copywriter] 输出 5 组文案
[Image Generator] 调用 MCP Server → ComfyUI → 生成 5 张图
- 图 3 第一次生成不满意(芯片细节不够)
- 自主调整:steps 25→40, CFG 7.5→9
- 第二次生成通过
═══════════════════════════════════════════════════
[并行组 3] Task 4(质量审核)
[Quality Reviewer] 逐张评分:
图 1: 9.2 ✓
图 2: 8.7 ✓
图 3: 8.9 ✓
图 4: 6.1 ✗ → 打回:"续航数字太小,不够醒目"
图 5: 8.3 ✓
[Supervisor] 收到打回 → 重新分配给 Image Generator
[Image Generator] 根据反馈调整 prompt + 重新生成
[Quality Reviewer] 二审:图 4: 8.5 ✓
═══════════════════════════════════════════════════
[并行组 4] Task 5(导出)
[Export Agent] 组装 PSD 分层文件 + 5 张 PNG
[Supervisor] 汇总 → 返回用户
总耗时:47 秒(单 Agent 串行预估 3 分 20 秒)
七、冲突解决:Agent 意见不一致怎么办?
真实场景中,Agent 之间会产生分歧:
| 冲突类型 | 示例 | 解决策略 |
|---|---|---|
| 创意 vs 合规 | 创意总监要"爆炸效果",审核员说"平台禁止夸大宣传" | 审核员有一票否决权,创意总监必须修改 |
| 质量 vs 效率 | 审核员打回 3 次,生成师说"已经是最好了" | 超过 3 轮 → 上报 Supervisor → 降级通过或换模型 |
| 文案 vs 视觉 | 文案太长,图上放不下 | 排版 Agent 反馈 → Supervisor 协调 → 文案精简 |
| 资源竞争 | 两个任务同时要 GPU | 消息总线排队 + 优先级调度 |
冲突解决代码
// src/conflict-resolver.ts
export class ConflictResolver {
// 优先级规则(硬编码,不让 LLM 决定)
private priorityRules = [
{ rule: "compliance > creativity", weight: 100 }, // 合规永远优先
{ rule: "user_explicit > agent_inferred", weight: 90 }, // 用户明确说的优先
{ rule: "quality > speed", weight: 70 }, // 质量优先于速度
{ rule: "consistency > novelty", weight: 60 }, // 一致性优先于新奇
];
async resolve(conflict: Conflict): Promise<Resolution> {
// 1. 先查硬规则
const hardRule = this.matchHardRule(conflict);
if (hardRule) return { winner: hardRule.winner, reason: hardRule.rule };
// 2. 硬规则无法覆盖 → LLM 仲裁
const arbitration = await this.llmArbitrate(conflict);
return arbitration;
}
private async llmArbitrate(conflict: Conflict): Promise<Resolution> {
const response = await this.llm.chat.completions.create({
model: "gpt-4o",
messages: [{
role: "system",
content: `你是仲裁者。两个 Agent 产生分歧,你需要做出裁决。
原则:
1. 用户需求 > 一切
2. 合规 > 创意
3. 如果无法判断,选择更保守的方案
输出:{ winner, loser, reason, compromise? }`
}, {
role: "user",
content: JSON.stringify(conflict)
}],
response_format: { type: "json_object" },
});
return JSON.parse(response.choices[0].message.content!);
}
}
关键设计决策:合规类冲突不让 LLM 裁决,硬编码一票否决。 LLM 可能"理解"创意意图而放行违规内容,这在电商场景是致命的。
八、可观测性:多 Agent 系统的调试噩梦与解法
单 Agent 调试:看一段对话。
多 Agent 调试:看一群 Agent 的群聊记录 + 状态变更 + 工具调用 + 冲突日志。
8.1 全链路 Trace
// src/tracer.ts
export class AgentTracer {
private traces: TraceEvent[] = [];
// 每个关键节点都打点
trace(event: {
traceId: string; // 整个用户请求的唯一 ID
spanId: string; // 当前步骤 ID
parentSpanId?: string; // 父步骤(形成树)
agentId: string;
action: string; // "llm_call" | "tool_call" | "message_send" | "state_write" | "conflict"
input?: any;
output?: any;
durationMs?: number;
tokensUsed?: number;
error?: string;
}) {
this.traces.push({ ...event, timestamp: Date.now() });
}
// 输出可视化(接入 Jaeger / LangSmith / 自建面板)
export() {
return this.traces.sort((a, b) => a.timestamp - b.timestamp);
}
// 快速定位:某个 Agent 的所有 LLM 调用
getAgentLLMCalls(agentId: string) {
return this.traces.filter(t => t.agentId === agentId && t.action === "llm_call");
}
// 快速定位:所有冲突事件
getConflicts() {
return this.traces.filter(t => t.action === "conflict");
}
}
8.2 关键度量
| 指标 | 含义 | 告警阈值 |
|---|---|---|
| 端到端延迟 | 用户发需求 → 收到交付物 | > 120s |
| Agent 轮次 | 单个 Agent 的 LLM 调用次数 | > maxIterations × 0.8 |
| 打回率 | 审核员打回次数 / 总生成次数 | > 40%(说明创意 Brief 质量差) |
| 冲突次数 | 每次请求的冲突事件数 | > 3 |
| Token 总消耗 | 所有 Agent 的 token 之和 | > 50000(成本失控) |
| 幻觉率 | Agent 输出与黑板状态矛盾的次数 | > 0(零容忍) |
九、工程踩坑:血泪教训
| # | 坑 | 现象 | 解法 |
|---|---|---|---|
| 1 | Agent 互相"客气" | 审核员说"挺好的",不敢打回 | System Prompt 明确"你是严格审核员,不是同事,不需要礼貌" |
| 2 | Supervisor 微管理 | 每步都干预,Agent 没有自主性 | Supervisor 只管分配和汇总,不审查过程 |
| 3 | 上下文串台 | Agent B 看到了 Agent A 的对话历史 | 每个 Agent 独立 messages 数组,只通过黑板共享结果,不共享过程 |
| 4 | 死循环 | 生成→打回→生成→打回→∞ | 硬编码 maxRounds=3,超过则降级通过或上报人类 |
| 5 | Token 爆炸 | 5 个 Agent × 10 轮 × 4000 token = 200K | 每轮只传摘要,不传完整历史;黑板只存结构化数据 |
| 6 | 并发写冲突 | 两个 Agent 同时写 generatedImages | 黑板字段级锁 + 乐观锁版本号 |
| 7 | 模型不一致 | 创意用 GPT-4o,生成用 GPT-3.5,风格割裂 | 创意/审核用强模型,执行用快模型,但 System Prompt 中注入统一的风格约束 |
十、多 Agent 与训练师职业要素的映射
| 多 Agent 工程环节 | 对应训练师职业定义 | 具体体现 |
|---|---|---|
| Agent System Prompt 设计 | 人机交互设计 | 定义 Agent 的角色、边界、交互策略 |
| Skill 参数 Schema(steps/CFG/sampler) | 算法参数设置 | 图像生成 Agent 的参数调优策略 |
| MCP Server 调用(ComfyUI/Flux) | 智能训练软件使用 | 通过标准协议调用 AI 工具链 |
| 黑板状态管理 + 数据库持久化 | 数据库管理 | 项目状态、生成记录、审核日志的存储与查询 |
| 质检循环 + 冲突仲裁 | 智能训练软件使用 | 用反馈数据迭代优化 Agent 行为 |
| 团队内技术分享 + 社区文章 | 培训指导 | 知识传播与经验沉淀 |
十一、总结:多 Agent 不是"多个 Prompt"
很多人对多 Agent 的理解停留在"写几段不同的 System Prompt,让它们轮流说话"。
真正的多 Agent 工程是分布式系统设计:
单 Agent = 一个函数
多 Agent = 一个微服务架构
你需要考虑:
- 服务发现(Agent 能力注册与发现)
- 通信协议(消息格式、路由、确认)
- 状态管理(共享黑板、一致性、锁)
- 容错(重试、降级、熔断、上报)
- 可观测性(Trace、Metrics、Logging)
- 安全(权限、配额、审计)
大模型给了每个 Agent "智力",但让它们像团队一样协作,靠的是工程。
从单兵到军团,不是堆人数,是建制度。