A13: 多 Agent 协调模式
当单个 Claude Code 会话不够用时,你需要将工作分配给多个 Agent。但协调是困难的——Agent 可能会冲突、重复工作或产出不一致的结果。本附录深入探讨使多 Agent 系统可靠的协调模式,以及实用的成本模型和扩展指南。
基本协调模式
每个多 Agent 系统都由三种原始模式构建。更复杂的工作流是这些原始模式的组合。
模式 1:扇出(Fan-Out)——并行独立子任务
最简单的多 Agent 模式:将工作分成独立的部分,并行运行,然后收集结果。
┌─── Agent A ──► Result A ───┐
│ │
Orchestrator ──────┼─── Agent B ──► Result B ───┼──► Merge
│ │
└─── Agent C ──► Result C ───┘何时使用:任务可以分解为没有共享状态的独立单元。
用 Claude Code 实现:
#!/bin/bash
# Fan-out: review 3 modules in parallel using git worktrees
REPO_DIR=$(pwd)
MODULES=("auth" "payments" "notifications")
for module in "${MODULES[@]}"; do
# Create isolated worktree for each agent
git worktree add "/tmp/review-$module" HEAD
# Launch agent in background
(
cd "/tmp/review-$module"
claude -p "Review the src/$module/ directory for security issues. \
Output findings as JSON to /tmp/review-$module-results.json" \
--model claude-sonnet-4-6-20250514
) &
done
# Wait for all agents to complete
wait
# Merge results
claude -p "Merge these security review results into a unified report:
$(cat /tmp/review-*-results.json)" \
--model claude-opus-4-7-20250219关键设计决策:
- 每个 Agent 有自己的 worktree,文件读取不会冲突
- 结果写入独立的输出文件,不存在写入竞争
- 最后的合并步骤组合结果(通常使用更强的模型)
故障处理:如果一个 Agent 失败,其他 Agent 继续运行。合并步骤应优雅处理缺失的结果:
# Check which agents succeeded
for module in "${MODULES[@]}"; do
if [ ! -f "/tmp/review-$module-results.json" ]; then
echo "WARNING: Review of $module failed" >> /tmp/review-failures.txt
fi
done模式 2:流水线(Pipeline)——顺序专业化处理
每个 Agent 执行一个阶段,将结果传递给下一个。每个 Agent 专注于其所在阶段。
Input ──► Agent A ──► Agent B ──► Agent C ──► Output
(Plan) (Implement) (Review)何时使用:任务有不同的阶段,每个阶段需要不同的技能或模型。
实现:
#!/bin/bash
# Pipeline: Plan → Implement → Review
TASK="Add rate limiting to the upload API endpoint"
# Stage 1: Planning (Opus for deep reasoning)
PLAN=$(claude -p "Create a detailed implementation plan for: $TASK
Include: files to modify, approach, edge cases, test strategy.
Output as structured markdown." \
--model claude-opus-4-7-20250219 --output-format text)
# Stage 2: Implementation (Sonnet for efficient coding)
claude -p "Implement this plan:
$PLAN
Follow the plan exactly. Write code and tests." \
--model claude-sonnet-4-6-20250514
# Stage 3: Review (Opus for quality assurance)
DIFF=$(git diff)
claude -p "Review this implementation for correctness and security:
$DIFF
The original plan was:
$PLAN
Flag any deviations from the plan or issues found." \
--model claude-opus-4-7-20250219 --output-format text流水线中的模型路由:为每个阶段使用合适的模型。规划和审查受益于 Opus 更强的推理能力。实现阶段由 Sonnet 的速度和能力平衡来很好地支撑。
模式 3:辩论(Debate)——多个 Agent 互相批评
两个或更多 Agent 提出解决方案,然后互相批评对方的提案。一个裁判选择最佳方案或综合出共识。
┌─── Agent A: Proposal A ───┐
│ │
Task ─────────┤ ├──► Judge ──► Final
│ │
└─── Agent B: Proposal B ───┘何时使用:架构决策、设计选择,或任何存在多个有效方案且你想要最佳方案的任务。
实现:
#!/bin/bash
QUESTION="How should we restructure the authentication module? \
Currently it's 2000 lines in a single file."
# Two agents propose independently
PROPOSAL_A=$(claude -p "Propose an approach: $QUESTION
Focus on maintainability and testing." \
--model claude-sonnet-4-6-20250514 --output-format text)
PROPOSAL_B=$(claude -p "Propose an approach: $QUESTION
Focus on performance and minimal API surface change." \
--model claude-sonnet-4-6-20250514 --output-format text)
# Each agent critiques the other's proposal
CRITIQUE_A=$(claude -p "Critique this proposal. Find weaknesses:
$PROPOSAL_B" --model claude-sonnet-4-6-20250514 --output-format text)
CRITIQUE_B=$(claude -p "Critique this proposal. Find weaknesses:
$PROPOSAL_A" --model claude-sonnet-4-6-20250514 --output-format text)
# Judge synthesizes (use Opus for best judgment)
claude -p "Two approaches were proposed for: $QUESTION
Proposal A: $PROPOSAL_A
Critique of A: $CRITIQUE_B
Proposal B: $PROPOSAL_B
Critique of B: $CRITIQUE_A
Synthesize the best approach, incorporating strengths from both proposals
and addressing the critiques." \
--model claude-opus-4-7-20250219为什么辩论有效:单个 Agent 有盲点。通过强制显式批评,你揭示了单个 Agent 会遗漏的弱点。裁判角色受益于看到所有视角。
Agent 分歧的共识算法
当多个 Agent 产出必须一致的结果时(例如,对重叠文件的代码修改),你需要一个共识机制。
多数投票
最简单的方法:对同一任务运行 N 个 Agent,取多数答案。
# Run 3 agents on the same code review
RESULTS=()
for i in 1 2 3; do
RESULTS+=("$(claude -p "Is this code safe to deploy? Answer YES or NO with reasoning." \
--model claude-sonnet-4-6-20250514 --output-format text)")
done
# Count votes
YES_COUNT=$(printf '%s\n' "${RESULTS[@]}" | grep -c "^YES")
if [ "$YES_COUNT" -ge 2 ]; then
echo "CONSENSUS: Safe to deploy ($YES_COUNT/3 agents agree)"
else
echo "CONSENSUS: NOT safe to deploy ($YES_COUNT/3 agents agree)"
fi何时使用:二元决策(部署/不部署、批准/拒绝)。对开放式任务不太适用。
层级解决
由高级 Agent(Opus)解决初级 Agent(Sonnet/Haiku)之间的分歧:
Agent A (Sonnet): "Refactor using Strategy pattern"
Agent B (Sonnet): "Refactor using simple if/else chain"
│
▼
Resolver (Opus): Reviews both approaches with full context,
selects or synthesizes the best option这反映了人类团队的工作方式:同事提议,高级决策。
迭代收敛
Agent 分享彼此的输出并不断改进直到达成一致:
Round 1: Agent A proposes X, Agent B proposes Y
Round 2: Agent A sees Y, revises to X', Agent B sees X, revises to Y'
Round 3: X' and Y' are close enough → merge警告:如果 Agent 来回振荡,这可能会无限循环。设置最大轮数(通常为 3),并回退到层级解决。
重叠更改的冲突解决
最困难的多 Agent 问题:两个 Agent 编辑同一个文件。
预防:分割文件空间
最好的冲突解决是冲突预防。为每个 Agent 分配特定文件或目录的独占所有权:
# Agent A owns src/auth/
# Agent B owns src/payments/
# Neither touches the other's directory
claude -p "Refactor src/auth/. DO NOT modify any files outside src/auth/."检测:基于 Git 的冲突检查
并行 Agent 完成后,在合并之前检查冲突:
# Each agent works on its own branch
git checkout -b agent-a-changes
# ... Agent A runs ...
git checkout -b agent-b-changes
# ... Agent B runs ...
# Try to merge both into a combined branch
git checkout -b combined
git merge agent-a-changes
if ! git merge agent-b-changes; then
echo "CONFLICT DETECTED -- invoking resolution agent"
# Pass conflict markers to a resolution agent
claude -p "Resolve these git merge conflicts. Prefer the more correct change.
$(git diff --name-only --diff-filter=U)" \
--model claude-opus-4-7-20250219
fi解决:语义合并
当检测到冲突时,解决 Agent 读取两个版本并产出正确的合并:
# Get both versions of conflicted files
for file in $(git diff --name-only --diff-filter=U); do
git show agent-a-changes:"$file" > "/tmp/version-a-$file"
git show agent-b-changes:"$file" > "/tmp/version-b-$file"
claude -p "Two agents modified $file independently.
Version A (from agent-a): $(cat /tmp/version-a-$file)
Version B (from agent-b): $(cat /tmp/version-b-$file)
Original: $(git show main:$file)
Produce a correct merged version that preserves both agents' changes." \
--model claude-opus-4-7-20250219
done扩展模式:需要多少个 Agent?
收益递减曲线
Quality / Throughput
│
100% │ ·····················
│ ·····
│ ····
│ ····
│ ···
│ ··
│ ·
│ ·
│·
└──────────────────────────────────── Agents
1 2 3 5 8 10 15 20在实践中:
- 1 到 3 个 Agent:接近线性改善。每增加一个 Agent 都带来显著价值。
- 3 到 5 个 Agent:良好的回报。协调开销可管理。
- 5 到 10 个 Agent:收益递减。协调成为瓶颈,而非能力。
- 10+ 个 Agent:很少值得。合并/冲突解决的成本占主导。
按任务类型推荐的扩展
| 任务 | 最优 Agent 数量 | 理由 |
|---|---|---|
| 代码审查 | 2-3 | 每个审查者发现不同的问题;超过 3 个产出冗余结果 |
| 模块重构 | 每模块 1 个 | 天然的分区边界;不需要协调 |
| 测试生成 | 3-5 | 测试是独立的;容易合并 |
| 架构设计 | 2(辩论) | 两个视角加一个裁判;更多只增加噪音 |
| Bug 分类 | 5-10(Haiku) | 高并发、低复杂度、容易并行化 |
| 安全审计 | 2-3(Opus) | 不同的分析角度;每个 Agent 成本较高 |
多 Agent 系统的成本建模
多 Agent 工作流比单 Agent 工作流消耗更多的 Token。在采用多 Agent 方法之前,请使用此框架估算成本。
成本公式
Total cost = (N_agents x cost_per_agent) + cost_merge + cost_conflict_resolution
Where:
cost_per_agent = input_tokens x input_price + output_tokens x output_price
cost_merge = typically 1 agent-turn with combined context
cost_conflict_resolution = 0 if no conflicts, else 1-3 agent-turns per conflict成本估算示例
任务:用 3 个并行 Sonnet Agent + 1 个 Opus 合并来审查一个 50 文件的 PR。
Per Sonnet agent:
Input: ~30,000 tokens (code + prompt) = $0.09
Output: ~5,000 tokens (review findings) = $0.075
Subtotal per agent: = $0.165
3 Sonnet agents: = $0.495
Opus merge:
Input: ~20,000 tokens (3 reports + prompt) = $0.30
Output: ~3,000 tokens (merged report) = $0.225
Subtotal: = $0.525
Total: ≈ $1.02与单个 Opus Agent 对比:
Input: ~80,000 tokens (all files + prompt) = $1.20
Output: ~8,000 tokens (full review) = $0.60
Total: ≈ $1.80多 Agent 方案更便宜也更快(并行执行)。这是多 Agent 的最佳场景:具有独立子任务的可并行化任务。
多 Agent 不具成本效益的情况
- 无法分区的任务(所有步骤之间有顺序依赖)
- 小型任务,其中协调开销超过任务本身
- 上下文共享至关重要的任务(每个 Agent 都需要全貌)
案例研究
ECC(Ensemble Claude Code)
ECC 模式对同一任务运行多个 Claude Code 实例,并选择最佳结果:
Same task ──► Instance 1 ──► Result 1 ──┐
──► Instance 2 ──► Result 2 ──┼──► Evaluator ──► Best Result
──► Instance 3 ──► Result 3 ──┘关键洞察:由于采样温度的影响,同一模型的不同运行会产生不同的结果。运行 3 个实例并选择最佳结果通常比运行 1 个更强模型的实例更便宜。
最适合:具有明确成功标准(测试通过/失败)的任务,你可以自动评估结果。
GStack(Git-Stacked Agents)
GStack 使用 git 分支作为协调机制。每个 Agent 在自己的分支上工作:
main ──► branch/agent-1 ──► PR #1 ──┐
──► branch/agent-2 ──► PR #2 ──┼──► Sequential merge
──► branch/agent-3 ──► PR #3 ──┘关键洞察:Git 本身就是一个冲突解决系统。让 Agent 提交到独立的分支,使用 git merge 检测冲突。人工审查者按优先级顺序合并 PR。
最适合:每个 Agent 处理一个模块或功能区域的大型重构任务。
GSD(Get Stuff Done)
GSD 将规划 Agent 与执行 Agent 结合:
Planning Agent (Opus) ──► Task 1 ──► Worker Agent A (Sonnet)
──► Task 2 ──► Worker Agent B (Sonnet)
──► Task 3 ──► Worker Agent C (Sonnet)
│
Review Agent (Opus) ◄┘关键洞察:将规划与执行分离。规划 Agent 使用更强的模型来正确分解任务。工作 Agent 使用更便宜的模型来执行计划。审查 Agent 验证结果。
最适合:需要前期架构思考但实现相对简单的复杂功能。
实用实现技巧
技巧 1:使用 Worktree,而不是在同一个 Checkout 中使用分支
# GOOD: Each agent gets its own worktree (isolated filesystem)
git worktree add /tmp/agent-1 HEAD
git worktree add /tmp/agent-2 HEAD
# BAD: Agents share the same working directory
# (race conditions on file reads and writes)技巧 2:结构化输出以便机器解析
# GOOD: JSON output that can be merged programmatically
claude -p "Review the code. Output as JSON: {findings: [{file, line, severity, message}]}" \
--output-format json
# BAD: Free-form text that requires another agent to parse
claude -p "Review the code and tell me what you think"技巧 3:为每个 Agent 设置超时
# Prevent a single slow agent from blocking the entire workflow
timeout 300 claude -p "Review src/auth/" --model claude-sonnet-4-6-20250514
if [ $? -eq 124 ]; then
echo "Agent timed out -- skipping this module"
fi技巧 4:记录一切
# Each agent logs to a separate file for debugging
claude -p "$TASK" --model claude-sonnet-4-6-20250514 \
2>&1 | tee "/tmp/agent-$MODULE-$(date +%s).log"决策框架:单 Agent vs 多 Agent
Can the task be done in one session within budget?
├── YES ──► Single agent (simpler, cheaper coordination)
└── NO ──► Can the task be partitioned into independent subtasks?
├── YES ──► Fan-out pattern
└── NO ──► Does the task have distinct sequential phases?
├── YES ──► Pipeline pattern
└── NO ──► Is there genuine uncertainty about approach?
├── YES ──► Debate pattern
└── NO ──► Single agent with /compact大多数任务用一个提示良好的单 Agent 比多 Agent 系统效果更好。只有在你有明确的分区策略且任务足够大以证明协调开销合理时,才使用多 Agent。
核心要点
- 扇出、流水线和辩论是三种原始模式。所有复杂的多 Agent 工作流都是它们的组合。
- 通过分割文件空间来预防冲突。检测和解决成本高昂;预防是廉价的。
- 对于大多数任务,收益递减从约 5 个 Agent 开始。更多 Agent 意味着更多协调开销。
- 先做成本建模。多 Agent 并不总是比单个更强的 Agent 更便宜。
- 使用 git worktree 实现并行 Agent 之间的文件系统隔离。共享工作目录会导致竞态条件。
- 将输出结构化为 JSON,以便获得可编程合并的机器可解析结果。
参见:A04 Agent 架构模式 了解多 Agent 协调所依赖的单 Agent 模式,以及 A11 模型选择指南 了解如何为每个 Agent 角色选择合适的模型。