🤝 OpenClaw Agent协作模式
一个Agent是超人,一群Agent是复仇者联盟。协作模式决定了这群超人是各打各的,还是有组织有纪律。
协作模式
1. 主从模式(Master-Worker)
一个主Agent指挥多个工作Agent。主Agent负责任务分配、结果汇总。
// 主从协作
class MasterAgent {
constructor(workers) {
this.workers = workers;
}
async execute(task) {
// 1. 分解任务
const subtasks = this.decompose(task);
// 2. 分配给Worker
const promises = subtasks.map((subtask, i) =>
this.workers[i % this.workers.length].execute(subtask)
);
// 3. 汇总结果
const results = await Promise.all(promises);
return this.merge(results);
}
}
2. 对等模式(Peer-to-Peer)
所有Agent地位相等,通过协商达成共识。
// 对等协作 - 投票决策
async function peerDecision(agents, question) {
const votes = await Promise.all(
agents.map(agent => agent.vote(question))
);
// 多数票决策
const tally = {};
votes.forEach(vote => {
tally[vote] = (tally[vote] || 0) + 1;
});
return Object.entries(tally)
.sort((a, b) => b[1] - a[1])[0][0];
}
3. 层级模式(Hierarchical)
树状结构,上级管理下级。适合大型系统。
Manager Agent
/ \\
Team Lead A Team Lead B
/ | | \\
Worker Worker Worker Worker
// 层级协作
class HierarchicalAgent {
constructor(config) {
this.role = config.role; // manager | lead | worker
this.children = config.children || [];
}
async delegate(task) {
if (this.role === 'worker' || this.children.length === 0) {
return this.execute(task);
}
const assigned = this.assignToChild(task);
return this.children[assigned].delegate(task);
}
}
4. 黑板模式(Blackboard)
共享黑板,所有Agent在上面读写信息协作。
// 黑板协作
class Blackboard {
constructor() {
this.data = {};
this.subscribers = [];
}
write(key, value, author) {
this.data[key] = { value, author, timestamp: Date.now() };
this.notify(key);
}
read(key) {
return this.data[key]?.value;
}
subscribe(agent) {
this.subscribers.push(agent);
}
notify(key) {
this.subscribers.forEach(agent =>
agent.onUpdate(key, this.data[key])
);
}
}
通信协议
A2A协议
Agent-to-Agent通信标准,详见A2A协议。
// A2A消息格式
const message = {
from: 'agent-001',
to: 'agent-002',
type: 'task_request',
payload: { task: 'analyze_data', params: {...} },
metadata: { priority: 'high', reply_by: Date.now() + 60000 }
};
冲突解决
投票机制
// 冲突时投票
function resolveConflict(agents, issue) {
const votes = agents.map(a => a.vote(issue));
const majority = Math.floor(agents.length / 2) + 1;
const counts = {};
votes.forEach(v => counts[v] = (counts[v] || 0) + 1);
for (const [option, count] of Object.entries(counts)) {
if (count >= majority) return option;
}
// 无多数票,由仲裁Agent决定
return agents[0].arbitrate(issue);
}
最佳实践
- 明确角色 - 每个Agent知道自己的职责
- 定义协议 - 通信格式标准化
- 设置协调者 - 复杂场景需要仲裁机制
- 限制并发 - 避免资源争抢
- 超时处理 - 协作要有时间限制,别等太久
相关链接
最后更新:2026-04-29 | 作者:妙趣AI