多 Agent 协作:团队合作的 AI
为什么需要多 Agent?
单个 Agent 的局限:
- •能力边界有限
- •复杂任务难以处理
- •结果可能有偏差
多 Agent 优势:
- •专业分工,各司其职
- •互相验证,减少错误
- •并行处理,提高效率
多 Agent 协作模式
1. 主从模式 (Orchestrator)
一个主 Agent 协调多个子 Agent:
┌─────────────┐
│ 协调者 Agent │
└──────┬──────┘
┌───────┼───────┐
▼ ▼ ▼
Agent A Agent B Agent C
(搜索) (分析) (写作)
const orchestrator = {
agents: {
researcher: researchAgent,
analyst: analysisAgent,
writer: writingAgent
},
async execute(task) {
// 1. 研究员收集资料
const data = await this.agents.researcher.run(task);
// 2. 分析师分析数据
const insights = await this.agents.analyst.run(data);
// 3. 写手生成报告
const report = await this.agents.writer.run(insights);
return report;
}
};
2. 对等协作模式 (Peer-to-Peer)
Agent 之间平等协作:
Agent A ←──────→ Agent B
↑ ↑
└───────────────┘
↓
Agent C
3. 辩论模式 (Debate)
多个 Agent 表达不同观点,达成共识:
问题 ──→ Agent 正方: "应该..."
└→ Agent 反方: "但是..."
↓
仲裁 Agent: 综合判断
↓
最终结论
4. 流水线模式 (Pipeline)
前一个 Agent 的输出是后一个的输入:
输入 → [提取] → [分析] → [优化] → [验证] → 输出
实战示例:代码审查系统
const codeReviewSystem = {
agents: {
// 安全审查员
securityReviewer: {
role: "安全专家",
focus: "检查安全漏洞、SQL注入、XSS等"
},
// 性能审查员
performanceReviewer: {
role: "性能专家",
focus: "分析时间复杂度、内存使用、优化建议"
},
// 代码风格审查员
styleReviewer: {
role: "代码规范专家",
focus: "检查命名规范、代码结构、可读性"
},
// 综合评审员
finalReviewer: {
role: "技术负责人",
focus: "汇总所有意见,给出最终评审结论"
}
},
async review(code) {
// 并行执行专项审查
const [security, performance, style] = await Promise.all([
this.agents.securityReviewer.review(code),
this.agents.performanceReviewer.review(code),
this.agents.styleReviewer.review(code)
]);
// 综合评审
return this.agents.finalReviewer.summarize({
security,
performance,
style
});
}
};
Agent 间通信
消息格式
interface AgentMessage {
from: string; // 发送者 Agent ID
to: string; // 接收者 Agent ID
type: "request" | "response" | "broadcast";
content: any; // 消息内容
metadata: {
timestamp: Date;
conversationId: string;
priority: "high" | "normal" | "low";
};
}
共享记忆
const sharedMemory = {
// 所有 Agent 可访问的共享状态
state: {},
// 读取
get(key) {
return this.state[key];
},
// 写入(带锁)
async set(key, value, agentId) {
await this.acquireLock(key);
this.state[key] = { value, updatedBy: agentId, timestamp: Date.now() };
this.releaseLock(key);
}
};
冲突解决策略
当多个 Agent 意见不一致时:
1. 投票制
Agent A: 方案1
Agent B: 方案2
Agent C: 方案1
→ 采用方案1(2:1)
2. 专家权重
安全问题 → 安全 Agent 权重高
性能问题 → 性能 Agent 权重高
3. 仲裁 Agent
综合各方意见 + 额外推理 → 最终决策
多 Agent 框架
| 框架 | 特点 | 适用场景 | |-----|------|---------| | AutoGen | 微软开源,对话式 | 通用任务 | | CrewAI | 角色扮演,任务驱动 | 业务流程 | | LangGraph | 状态机,可视化 | 复杂工作流 | | MetaGPT | 模拟软件公司 | 软件开发 |
设计原则
1. 单一职责
每个 Agent 只负责一个明确的领域。
2. 松耦合
Agent 之间通过消息通信,不直接依赖。
3. 可观测
记录每个 Agent 的输入输出,便于调试。
4. 容错设计
单个 Agent 失败不影响整体系统。
练习
设计一个"新闻编辑室"多 Agent 系统:
角色:
- •记者:收集新闻素材
- •编辑:审核和修改稿件
- •事实核查员:验证信息准确性
- •主编:决定发布
思考:
- •各 Agent 的职责边界?
- •如何处理意见分歧?
- •工作流如何设计?
小结
- •多 Agent = 分工 + 协作 + 通信
- •选择合适的协作模式
- •设计清晰的通信协议
- •处理好冲突和错误
恭喜完成全部课程!你已掌握从基础到高级的提示工程技术。