# How to Build Multi Agent Workflows (Full Guide)
**作者**: Avid
**日期**: 2026-06-01T09:58:23.000Z
**来源**: [https://x.com/Av1dlive/status/2061386872321130782](https://x.com/Av1dlive/status/2061386872321130782)
---

## I used Single Agents to do everything for 12 months.
Then I switched to Multi Agent Workflows for 2 days.
## Here is what I found
## Overview
Multi-agent systems in 2026 have a single defining question: how do you coordinate agents that cannot share context without poisoning each other? The answer determines whether your system scales or collapses.
This course builds your mental model from primitives up, then connects every concept directly to what Claude Code's Dynamic Workflows gives you today.
By the end you will know: when to use each orchestration topology, how to design inter-agent communication that does not corrupt, which failure modes kill production systems, and how to wire all of this using Claude's native orchestration stack.
## Module 1 : What a Multi-Agent System Actually Is
## The Unit and the Runtime
An agent is the unit: one LLM instance with its own system prompt, tool set, memory window, and sometimes its own model. A multi-agent system is the runtime: the machinery that coordinates two or more agents, routes tasks between them, handles handoffs, and enforces a governance layer.
The distinction matters because most failures in multi-agent systems are runtime failures, not agent failures. Individual agents often reason correctly. The system fails at coordination, context propagation, and permission boundaries.
## Why Single Agents Break
A single agent handling a large task runs into three hard limits:
- Context saturation: Every intermediate result consumes the context window. At scale, the agent is reasoning over a pile of its own history rather than the actual problem.
- Sequential bottleneck: The agent executes one step at a time. A 200-file migration that could parallelize runs serially for hours.
- Fragile recovery: If the agent crashes or drifts mid-task, the entire job restarts. There are no checkpoints.
Multi-agent systems solve all three by distributing work across isolated agents, storing intermediate state outside any agent's context, and adding phase-level recovery points.
## Module 2 : Claude's Three Orchestration Primitives
Before picking a topology, understand the three coordination primitives Claude Code gives you. Picking the wrong one for the job is the most common architectural mistake.
The decision rule:
- Use subagents when you need one or two isolated investigations that report back to a single session.
- Use agent teams when teammates need to communicate directly with each other and with you, without going through a central orchestrator.
- Use dynamic workflows when the orchestration itself should be repeatable, the plan must survive context limits, or the job takes hours to days.
## Module 3 :The Six Orchestration Topologies
Every multi-agent system you build uses one of six topologies or a combination of them. Match the topology to the problem, not to the framework.
## 1. Sequential Pipeline
Agents arranged in a chain. Agent A produces output, passes it to Agent B, which passes to Agent C.
```
text[Agent A: Parse] -> [Agent B: Analyze] -> [Agent C: Format]
```
Use when: Work is strictly dependent. Each step must complete before the next begins. Easy to debug because data has one path.
Claude implementation: Prompt chain inside a single dynamic workflow script. Each phase runs one subagent, waits for completion, passes the result as input to the next phase.
Failure mode: Latency compounds. If Agent B is slow, the entire pipeline waits. Do not use for work with independent parallel paths.
## 2. Coordinator-Worker (Hub and Spoke)
One coordinator agent receives the top-level task, decomposes it into subtasks, and routes each to a specialist worker. Workers return results to the coordinator, which synthesizes.
```
text[Coordinator]
/ | \
[Security] [Perf] [Auth] [Coverage]
\ | /
[Coordinator: Synthesize]
```
Use when: Work decomposes into distinct specialist domains. The routing logic is stable and knowable at plan time.
Claude implementation: This is the default shape of a Claude dynamic workflow. The workflow script is the coordinator; subagents are the workers. Claude writes the decomposition logic into the script, not into a conversation.
Failure mode: Single point of failure at the coordinator. If the coordinator's context fills up or drifts, the entire system degrades. Fix by keeping the coordinator's job narrow: decompose and route only, no domain reasoning.
## 3. Parallel Fan-Out with Merge
Multiple agents work simultaneously on independent subtasks. A merge step collects and reconciles their outputs.
```
text[Orchestrator]
| | | |
[A][B][C][D] <- simultaneous
| | | |
[Merge + Reconcile]
```
Use when: Subtasks have no dependencies between them. Classic use cases: auditing 200 files, querying multiple data sources, running five bug class investigations simultaneously.
Claude implementation: Claude's dynamic workflows run up to 16 concurrent agents by default. Structure your workflow phases so the fan-out tasks are genuinely independent. Results land in script variables, not in the orchestrator's context.
Performance gain: Parallel execution cuts processing time 60-80% for tasks with no step dependencies.
Failure mode: Merge logic is the hard part. If agents return inconsistent schemas or conflicting findings, a naive merge produces garbage. Design the output contract before writing the fan-out.
## 4. Generator-Verifier
One agent generates output. A second agent evaluates it against explicit criteria. The result feeds back to the generator. The loop runs until output passes or a max iteration count is hit.
```
text[Generator] -> [Verifier] -> passes? -> done
^ |
|-- feedback --| fails? -> iterate
```
Use when: Output quality is critical and evaluation criteria can be written down explicitly. Test writing, security findings, migration plans.
Claude implementation: Two-phase dynamic workflow. Phase 1 runs generator agents in parallel. Phase 2 runs independent verifier agents on each generator output. Only outputs that survive verification get merged. This is the adversarial verification built into all Claude dynamic workflows by default.
Failure mode: If the verifier's criteria are vague, it becomes a rubber stamp. Write the verification criteria as explicit, checkable rules in the workflow prompt.
## 5. Shared-State
Agents coordinate through a persistent store they all read and write directly. No central orchestrator routes messages; the shared store is the coordination mechanism.
```
text[Agent A] ---|
[Agent B] ---|--> [Shared Store: Markdown / JSON / DB]
[Agent C] ---|
```
Use when: Agents build on each other's findings progressively. Context that one agent discovers is immediately useful to others working the same problem.
Claude implementation: In practice, this is the filesystem in a git worktree or a structured docs folder. My production Claude Code setup uses this: every decision, every plan, every completed item drops into a structured docs folder as a Markdown file. Agents downstream pick them up automatically.
Failure mode: Context poisoning (covered in Module 5). An agent writes a bad finding to the shared store. Every downstream agent reads it as ground truth. The error propagates across the entire system.
## 6. Debate (Adversarial Multi-Agent)
Two or more agents attack the same problem from opposing positions. A judge agent (or the orchestrator) reconciles the debate output.
```
text[Agent: Find Issues] -> claim
[Agent: Refute Issues] -> counter-claim
[Judge: Reconcile] -> verified finding
```
Use when: You want findings that survive adversarial pressure before they reach you. Security audits, migration risk assessments, any work where a false positive or false negative has real cost.
Claude implementation: Claude dynamic workflows include this pattern natively. "Agents address the problem from independent angles. Other agents then try to refute what they found. The run iterates until answers converge". You get it without writing the debate logic explicitly; it runs as part of the workflow's verification phase.
## Module 4 : Communication Architecture
How agents pass information is where most systems break. The design decision is not which message format to use. It is whether agents communicate directly or through a substrate.
## Direct vs. Substrate Communication
The practical rule from production systems:
> Agents should not talk to each other directly. They should write to a shared memory layer and read from it. Canonical knowledge sits in one place. Each agent operates in isolation with a defined role, defined tools, and defined outputs.
Claude's dynamic workflows implement substrate-mediated communication by default. Intermediate results live in script variables, not in any agent's context window. This is why the orchestration script being JavaScript matters architecturally: script variables are the substrate.
## Output Contracts
Every agent in a production system needs an explicit output contract: a schema that defines exactly what it must return. Without it, the merge step and downstream agents have to guess what they received.
```
/ Example output contract for a security audit agent
{
"finding_id": "string",
"file_path": "string",
"line_number": "number",
"severity": "critical | high | medium | low",
"description": "string",
"confirmed": "boolean",
"suggested_fix": "string"
}
```
Enforce this in your workflow prompt:
```
Return results in this exact JSON schema. If a field cannot be populated, return null for that field. Do not add fields not in the schema.
```
## Context Window Budgeting
Every agent has a finite context window. In a multi-agent system, you are managing a fleet of context windows simultaneously. The design decisions that matter:
- Keep the orchestrator narrow. The orchestrator should decompose and route. Domain reasoning belongs to specialist agents. Narrow orchestrators do not fill their context with domain knowledge they are not using.
- Cap what agents receive. Pass only what the agent needs for its specific task. Do not pipe full file trees to agents that need three files.
- Use a hot path limit for short-term memory. In agentic loops, keep only the last 3-5 exchanges in active context. Drop older context to a shared store.
## Module 5 : Failure Modes
These are the five failures that kill production multi-agent systems. Each is predictable and preventable.
## 1. Context Poisoning
An agent writes a bad output (hallucinated finding, wrong schema, corrupted state) to the shared store. Downstream agents read it as truth and build on it. The error compounds across the pipeline.
Signs in production: Findings that seem plausible but cannot be traced back to actual file content. Agents that confidently contradict each other on the same file.
Prevention:
- Schema validation at every write point. No agent writes raw text to the shared store; everything goes through a typed schema.
- Verifier agents check outputs before they hit the shared store, not after.
- Human review gates before results from one phase seed the next phase.
## 2. Cascading Failure
One agent fails. The orchestrator does not isolate the failure and routes the bad result downstream. Agents built on the failed output also fail. Multi-agent systems without proper orchestration have documented failure rates of 41-86.7%.
Prevention:
- Circuit breakers: if an agent returns an error or a null output, halt that branch, do not forward.
- Confidence scoring at pipeline checkpoints: outputs below a threshold do not pass through.
- Independent findings from multiple agents: one failure cannot corrupt the whole run if other agents independently reached the same or different conclusions.
## 3. Scope Creep
The orchestrator's decomposition is too broad. Agents interpret their mandate expansively. An agent tasked with "audit the codebase" starts editing files it was not supposed to touch.
Prevention:
- Every agent gets an explicit, bounded scope in its task prompt: paths, file types, allowed actions.
- Edit policy: read-only unless explicitly granted write access for specific paths.
- Anthropic's own design guidance: minimal footprint, request only necessary permissions, prefer reversible actions.
## 4. Silent Substitution
An agent cannot complete a step (API call fails, file is unreadable) and quietly inserts placeholder data behind a try/catch. It reports success. The pipeline treats the placeholder as a real result.
Prevention:
In CLAUDE.md or your workflow's agent system prompt:
```
Error Handling
- NEVER substitute mock or placeholder data for a real result
- If a step fails, report the error and halt this agent's execution
- A fallback is acceptable ONLY if explicitly logged as a fallback with the reason
```
## 5. Coordination Deadlock
Two agents wait on each other. Agent A cannot proceed until Agent B finishes. Agent B cannot start until Agent A writes to the shared store. The workflow stalls.
Prevention:
- Explicit dependency graphs in the workflow script. Claude's orchestration scripts encode dependencies in code, not in implicit conversation order.
- Timeouts on every agent invocation. If an agent has not returned in X seconds, the orchestrator marks it failed and routes around it.
- Design phases to be truly independent before fanning out. Dependency mapping is Module 8's pre-flight checklist.
## Module 6 :The Governance Layer
Every multi-agent system needs three structural layers to work reliably:
The governance layer is what separates a demo from a production system.
## What the Governance Layer Does
1. Permission scoping: Each agent has a declared permission set. A security audit agent gets read-only access. A migration agent gets write access to specific paths only. No agent gets broader permissions than its task requires.
2. Human-in-the-loop gates: Define which actions require human approval before execution. Irreversible operations (file deletions, production API calls, schema migrations) always go through a HITL gate.
3. Audit trails: Every agent decision, every action, every tool call gets logged with the agent ID and the reasoning that led to it. When something breaks, you need to replay exactly what happened.
4. Blast radius limits: Define the maximum scope of damage any single agent can cause if it misbehaves. Filesystem writes scoped to a worktree, not the repo root. API calls limited to staging environments without explicit production access.
## Implementing Governance in Claude Dynamic Workflows
The governance layer translates into three concrete artifacts:
```
CLAUDE.md rules (apply to all agents in the session):
t## Agent Permissions
- Read access: entire repository
- Write access: only paths listed in the task prompt
- Shell commands: only commands on the approved list
- Network: no external calls unless the task prompt specifies an endpoint
## Error Handling
- Silent failures are not permitted
- Every error must be reported before halting
## Irreversible Action Policy
- Database writes require explicit approval in the task prompt
- File deletions require explicit approval in the task prompt
- No production API calls without "production: true" in the task prompt
```
## Module 7 : The Five Claude-Native Patterns in Production
These are the five patterns Anthropic documented from what works reliably in production Claude systems. Each maps directly to a dynamic workflow structure.
## Pattern 1 : Prompt Chaining
1. Break a complex task into a chain of simpler prompts. Output from one becomes input to the next. Each step is small enough that the agent can complete it reliably.
2. When to use: The task has clear sequential stages. Document processing (extract then analyze then summarize), data transformation pipelines, code generation followed by testing followed by review.
Claude workflow shape:
```
Phase 1: Parse and extract -> Phase 2: Analyze -> Phase 3: Generate report
```
Each phase is a separate agent invocation. The output of Phase 1 becomes the input to Phase 2 via script variables.
## Pattern 2 : Routing
1. A classifier agent reads the input and routes it to the appropriate specialist. The classifier does not process the task; it only routes.
2. When to use: Tasks arrive in a heterogeneous stream. A coding task goes to the code agent, a security question goes to the security agent, a docs question goes to the docs agent.
Claude workflow shape:
```
text[Classifier Agent: reads task, returns agent_type]
|
-> dynamic dispatch to [Security | Code | Performance | Documentation]
```
Implement the dispatch in the workflow script's routing logic.
## Pattern 3 : Parallelization
Fan out independent subtasks to multiple agents simultaneously. Merge results at the end.
When to use: Subtasks have no dependencies on each other. Auditing multiple files, searching multiple data sources, running multiple analysis categories simultaneously.
Claude workflow shape:
```
/ Workflow script structure
const files = getFilesInScope();
const results = await Promise.all(
files.map(file => runAgent({ task: 'audit', scope: file }))
);
const merged = mergeAndDeduplicate(results);
```
Dynamic workflows run up to 16 concurrent agents. Token usage drops 60-90% versus sequential chaining because intermediate results stay in script variables.
## Pattern 4 : Orchestrator-Subagents
1. An orchestrator receives a high-level goal, breaks it into subtasks, dispatches to specialized subagents, and synthesizes their outputs.
2. When to use: Work requires multiple specialist domains. A codebase audit that needs a security specialist, a performance specialist, and a coverage specialist running simultaneously.
Claude workflow shape:
```
[Orchestrator: decompose goal into subtasks]
|
[Security Agent] [Perf Agent] [Coverage Agent]
| | |
[Orchestrator: synthesize findings]
```
The orchestrator's only job is decomposition and synthesis. Domain reasoning belongs to the specialists.
## Pattern 5 : Evaluator-Optimizer
1. Generator agent produces output. Evaluator agent scores it against explicit criteria. Score plus feedback returns to the generator. Loop until the output passes or max iterations hit.
2. When to use: Output quality is critical and evaluation criteria are writable as explicit rules. Security findings that must not be false positives. Migration plans that must survive adversarial review. Test cases that must cover specified edge cases.
Claude workflow shape:
```
Phase 1: Generator agent produces initial output
Phase 2: Evaluator agent scores against criteria schema
- Score >= threshold: forward to output
- Score < threshold: feedback -> Phase 1 with iteration count + 1
Phase 3: Max iterations reached: flag for human review
Set a hard max iteration count (3-5). Without it, the loop can run indefinitely on ambiguous evaluation criteria.
```
## Module 8 : System Design from Scratch
A repeatable process for designing a multi-agent system before writing a single workflow prompt.
## Step 1 : Task Decomposition
Write down the top-level task in one sentence. Then list every distinct operation needed to complete it. For each operation, answer two questions:
1. Does this operation depend on another operation's output? (sequential dependency)
2. Can this operation run at the same time as other operations? (parallel candidate)
Group sequential-dependent operations into phases. Group parallel candidates into fan-outs within each phase.
Output: A phase diagram with explicit dependency arrows.
## Step 2 : Specialist Identification
For each operation in your phase diagram, identify the specialist agent it needs. Define:
- The agent's role (one sentence, no ambiguity)
- The agent's tool access (read-only? write to which paths? which shell commands?)
- The agent's output contract (exact JSON schema)
- The agent's failure behavior (what it does when it cannot complete its task)
Avoid general-purpose agents. A "code agent" that does everything is a single agent with a bloated context, not a specialist.
## Step 3 : Communication Design
Decide: substrate-mediated or direct? For most systems, the answer is substrate-mediated via the workflow's script variables (for dynamic workflows) or a shared filesystem (for agent teams).
Map the data flow: which agent writes what, to which location, when. Draw the read/write graph. If any agent reads from a location that more than one other agent writes to, you have a potential context poisoning vector. Add a validation step before that read.
## Step 4 : Governance Contracts
Write the CLAUDE.md agent rules before writing any workflow prompt. This forces you to specify permissions, error handling, and HITL gates as explicit decisions rather than afterthoughts. The artifacts from Module 6 are your template.
## Step 5 : Pre-Flight Checklist
Before running any multi-agent workflow on a real repository:
- Working in a git worktree or feature branch, not main
- Each agent's permission scope is explicitly bounded in the task prompt
- Output contracts defined for every agent that writes to the shared store
- Verifier/evaluator agents in place for every generator agent on critical paths
- HITL gates defined for all irreversible actions
- Max iteration counts set on all evaluator-optimizer loops
- Failure behavior defined for every agent (fail loud, never silent substitution)
- /usage checked before running to understand token budget
## Module 9 : Building with Claude's Orchestration Stack
## The Practical Architecture: Dynamic Workflows + Agent Teams
For most production engineering tasks, the architecture combines two Claude primitives:
1. Outer layer: Dynamic Workflow
Claude writes the orchestration script. The script handles decomposition, fan-out, result collection, and phase sequencing. Intermediate state lives in script variables. The workflow is rerunnable: save it as a slash command and the entire orchestration becomes a team command.
2. Inner layer: Specialist Subagents
Each phase in the workflow dispatches specialist subagents. Each subagent has a scoped system prompt (via the task in the workflow), specific file paths, defined output schema, and a failure policy.
3. For tasks requiring inter-agent communication: Agent Teams
When specialists need to message each other directly (not just report back to the orchestrator), use Claude Code's Agent Teams. Each teammate is a full Claude Code session with its own context. They communicate via mailbox. The team lead coordinates without micromanaging.
Claude Code's Built-in Observability
The /workflows command gives you live observability into every running dynamic workflow:
- Phase-level status (running, complete, failed)
- Agent-level drill-down: task prompt, current status, output so far
- Ability to pause, restart individual agents, or stop the whole workflow
- Resume from checkpoint within the session
For agent teams, each teammate session is independently inspectable. You can interact directly with a teammate without going through the lead.
## Module 10 : Scaling and Cost Control
Multi-agent systems do not have linear cost curves. Costs compound with agent count.
## Token Cost Architecture
Token usage in a multi-agent system comes from three sources:
1. Orchestration planning: Writing the workflow script or decomposing the task costs tokens upfront. This is fixed per job, not per agent.
2. Agent execution: Each agent reads its task, reads its input files, calls tools, and produces output. Cost scales with agent count.
3. Synthesis: The orchestrator reads all agent outputs and synthesizes. Cost scales with total output volume.
Dynamic workflows cut synthesis cost by keeping intermediate results in script variables rather than piping them all into the orchestrator's context.
## The 3-7 Agent Rule
Keep teams small. 3-7 agents per workflow phase. Beyond that, create hierarchical structures: one team lead per group, team leads report to a global orchestrator. Flat architectures with 20+ agents in one coordination layer have quadratic communication overhead and coordination deadlock risk.
## Module 11 : Decision Guide: When to Build Multi-Agent
The most expensive mistake is building a multi-agent system for a job that one good agent (or one good function) can handle.
## Build Multi-Agent When
- The task has genuinely independent parallel paths (and you can enumerate them)
- The work exceeds a single agent's context window and cannot be summarized without loss
- You need adversarial verification (findings that survive refutation are worth more than findings from a single pass)
- The job runs for hours to days and needs checkpoint recovery
- The process is repeatable (audits, migrations, test generation) and the orchestration itself should be a reusable artifact
- Different phases require genuinely different specialist expertise or tool sets
## Stay Single-Agent When
- The task is sequential with no parallelism
- The work fits comfortably in one context window
- Coordination overhead would exceed execution time
- You are still building and changing the system rapidly (multi-agent architectures are expensive to refactor)
## The Single Biggest Architectural Mistake
Routing all agent results back through the orchestrator's context. Once you do that, you have rebuilt the single-agent context bottleneck with extra network hops. Intermediate state belongs in the substrate (script variables, filesystem, structured docs), not in the orchestrator's conversation history.
> The orchestrator's context should hold the plan and the final synthesis. Nothing else.
## Disclaimer
This article was written by the author based on his notes, research, and personal experiences, and edited by an AI model (Sonnet 4.6).
The thumbnail image was taken from Pinterest and modified using AI
## 相关链接
- [Avid](https://x.com/Av1dlive)
- [@Av1dlive](https://x.com/Av1dlive)
- [42K](https://x.com/Av1dlive/status/2061386872321130782/analytics)
- [Upgrade to Premium](https://x.com/i/premium_sign_up)
- [5:58 PM · Jun 1, 2026](https://x.com/Av1dlive/status/2061386872321130782)
- [42.8K Views](https://x.com/Av1dlive/status/2061386872321130782/analytics)
- [View quotes](https://x.com/Av1dlive/status/2061386872321130782/quotes)
---
*导出时间: 2026/6/2 09:14:39*
---
## 中文翻译
# 如何构建多智能体工作流(完整指南)
**作者**: Avid
**日期**: 2026-06-01T09:58:23.000Z
**来源**: [https://x.com/Av1dlive/status/2061386872321130782](https://x.com/Av1dlive/status/2061386872321130782)
---

## 我使用单智能体处理一切长达 12 个月。
然后我转为多智能体工作流用了 2 天。
## 以下是我的发现
## 概述
2026 年的多智能体系统面临一个核心定义性问题:如何协调那些无法在不造成相互干扰(上下文污染)的情况下共享上下文的智能体?这个答案决定了你的系统是扩展还是崩溃。
本课程将从基本单元开始构建你的心智模型,然后将每个概念直接联系到 Claude Code 的动态工作流目前提供的功能。
学完后你将知道:何时使用每种编排拓扑,如何设计不会破坏信息的智能体间通信,哪些故障模式会扼杀生产系统,以及如何使用 Claude 的原生编排栈将所有这些连接起来。
## 模块 1:多智能体系统究竟是什么
## 单元与运行时
智能体是单元:一个 LLM 实例,拥有自己的系统提示词、工具集、记忆窗口,有时还有自己的模型。多智能体系统是运行时:协调两个或更多智能体、在它们之间路由任务、处理交接并执行治理层的机制。
这种区分至关重要,因为多智能体系统中的大多数失败都是运行时失败,而非智能体失败。单个智能体通常能正确推理。系统在协调、上下文传播和权限边界上失败。
## 为什么单智能体会崩溃
处理大型任务的单智能体会遇到三个硬性限制:
- 上下文饱和:每个中间结果都会消耗上下文窗口。在规模化时,智能体是在对其自身的一堆历史记录进行推理,而不是针对实际问题。
- 顺序瓶颈:智能体一次只执行一步。一个本可以并行处理的 200 个文件迁移,会串行运行数小时。
- 脆弱的恢复:如果智能体在任务中途崩溃或漂移,整个作业都会重启。没有检查点。
多智能体系统通过以下方式解决这三个问题:将工作分配给隔离的智能体,在智能体上下文之外存储中间状态,并添加阶段级的恢复点。
## 模块 2:Claude 的三种编排原语
在选择拓扑之前,先了解 Claude Code 为您提供的三种协调原语。为任务选择错误的类型是最常见的架构错误。
决策规则:
- 当你需要一两个隔离的调研并向单个会话汇报时,使用**子智能体**。
- 当队友需要直接相互通信以及与你通信,而无需经过中央协调器时,使用**智能体团队**。
- 当编排本身应该是可重复的、计划必须超越上下文限制,或者作业需要数小时到数天时,使用**动态工作流**。
## 模块 3:六种编排拓扑
您构建的每个多智能体系统都使用六种拓扑中的一种或它们的组合。让拓扑与问题匹配,而不是与框架匹配。
## 1. 顺序流水线
智能体按链排列。智能体 A 产生输出,将其传递给智能体 B,后者再传递给智能体 C。
```
text[智能体 A: 解析] -> [智能体 B: 分析] -> [智能体 C: 格式化]
```
**使用场景**:工作严格依赖。每一步必须完成后才能开始下一步。易于调试,因为数据只有一条路径。
**Claude 实现**:单个动态工作流脚本内的提示词链。每个阶段运行一个子智能体,等待完成,将结果作为输入传递给下一阶段。
**故障模式**:延迟累积。如果智能体 B 慢,整个流水线都会等待。不要用于具有独立并行路径的工作。
## 2. 协调器-工作器(中心辐射型)
一个协调器智能体接收顶层任务,将其分解为子任务,并将每个任务路由给专家工作器。工作器将结果返回给协调器,协调器进行综合。
```
text[协调器]
/ | \
[安全] [性能] [认证] [覆盖率]
\ | /
[协调器: 综合]
```
**使用场景**:工作分解为不同的专业领域。路由逻辑在计划时是稳定且可知的。
**Claude 实现**:这是 Claude 动态工作流的默认形状。工作流脚本是协调器;子智能体是工作器。Claude 将分解逻辑写入脚本,而不是写入对话中。
**故障模式**:协调器存在单点故障。如果协调器的上下文填满或漂移,整个系统都会降级。通过保持协调器的工作狭窄来修复:只进行分解和路由,不做领域推理。
## 3. 并行发散与合并
多个智能体同时处理独立的子任务。合并步骤收集并协调它们的输出。
```
text[编排器]
| | | |
[A][B][C][D] <- 同时进行
| | | |
[合并 + 协调]
```
**使用场景**:子任务之间没有依赖关系。经典用例:审计 200 个文件,查询多个数据源,同时运行五个错误类别调查。
**Claude 实现**:Claude 的动态工作流默认运行最多 16 个并发智能体。构建工作流阶段,使发散任务真正独立。结果落入脚本变量中,而不是编排器的上下文中。
**性能提升**:对于没有步骤依赖的任务,并行执行可将处理时间缩短 60-80%。
**故障模式**:合并逻辑是难点。如果智能体返回不一致的架构或冲突的发现,简单的合并会产生垃圾。在编写发散逻辑之前设计输出合约。
## 4. 生成器-验证器
一个智能体生成输出。第二个智能体根据明确标准对其进行评估。结果反馈给生成器。循环运行直到输出通过或达到最大迭代次数。
```
text[生成器] -> [验证器] -> 通过? -> 完成
^ |
|-- 反馈 --| 失败? -> 迭代
```
**使用场景**:输出质量至关重要且评估标准可以明确写出。测试写作、安全发现、迁移计划。
**Claude 实现**:两阶段动态工作流。第一阶段并行运行生成器智能体。第二阶段对每个生成器输出运行独立的验证器智能体。只有通过验证的输出才会被合并。这是所有 Claude 动态工作流默认内置的对抗性验证。
**故障模式**:如果验证器的标准模糊,它就会变成橡皮图章。将验证标准作为工作流提示中的明确、可检查规则来编写。
## 5. 共享状态
智能体通过它们都直接读写的持久存储进行协调。没有中央协调器路由消息;共享存储就是协调机制。
```
text[智能体 A] ---|
[智能体 B] ---|--> [共享存储: Markdown / JSON / DB]
[智能体 C] ---|
```
**使用场景**:智能体逐步建立彼此的发现。一个智能体发现的上下文对处理同一问题的其他智能体立即可用。
**Claude 实现**:实际上,这是 git 工作树中的文件系统或结构化的文档文件夹。我的 Claude Code 生产环境设置使用这个:每个决策、每个计划、每个完成的项目都作为 Markdown 文件落入结构化的文档文件夹中。下游的智能体会自动拾取它们。
**故障模式**:上下文污染(在第 5 模块中涵盖)。一个智能体将错误的发现写入共享存储。每个下游智能体将其视为基本事实。错误在整个系统中传播。
## 6. 辩论(对抗性多智能体)
两个或更多智能体从对立的角度攻击同一个问题。法官智能体(或编排器)协调辩论的输出。
```
text[智能体: 发现问题] -> 主张
[智能体: 反驳问题] -> 反驳
[法官: 协调] -> 验证后的发现
```
**使用场景**:您希望在发现结果到达您之前经受对抗性压力。安全审计、迁移风险评估、任何假阳性或假阴性具有实际成本的工作。
**Claude 实现**:Claude 动态工作流原生包含此模式。“智能体从独立的角度解决问题。然后其他智能体试图反驳他们的发现。运行迭代直到答案收敛”。您无需显式编写辩论逻辑即可获得它;它作为工作流验证阶段的一部分运行。
## 模块 4:通信架构
智能体如何传递信息是大多数系统崩溃的地方。设计决策不在于使用哪种消息格式。而在于智能体是直接通信还是通过底层进行通信。
## 直接通信与底层通信
来自生产系统的实用规则:
> 智能体不应直接相互对话。它们应写入共享内存层并从中读取。规范知识存在于一个地方。每个智能体在隔离状态下运行,具有定义的角色、定义的工具和定义的输出。
Claude 的动态工作流默认实现底层介导的通信。中间结果存在于脚本变量中,而不是在任何智能体的上下文窗口中。这就是为什么编排脚本是 JavaScript 在架构上很重要的原因:脚本变量就是底层。
## 输出合约
生产系统中的每个智能体都需要一个明确的输出合约:一个精确定义它必须返回什么的架构。没有它,合并步骤和下游智能体就只能猜测它们收到了什么。
```
/ 安全审计智能体的示例输出合约
{
"finding_id": "string",
"file_path": "string",
"line_number": "number",
"severity": "critical | high | medium | low",
"description": "string",
"confirmed": "boolean",
"suggested_fix": "string"
}
```
在工作流提示中强制执行此操作:
```
以此确切的 JSON 架构返回结果。如果无法填充字段,请为该字段返回 null。请勿添加架构中不包含的字段。
```
## 上下文窗口预算
每个智能体都有一个有限的上下文窗口。在多智能体系统中,您正在同时管理一组上下文窗口。重要的设计决策:
- 保持编排器狭窄。编排器应该进行分解和路由。领域推理属于专家智能体。狭窄的编排器不会用它们不使用的领域知识填满上下文。
- 限制智能体接收的内容。仅传递智能体特定任务所需的内容。不要将完整的文件树传输给只需要三个文件的智能体。
- 对短期记忆使用热路径限制。在智能体循环中,仅在活动上下文中保留最后 3-5 次交换。将较旧的上下文丢弃到共享存储中。
## 模块 5:故障模式
这是扼杀生产多智能体系统的五种故障。每一种都是可预测和可预防的。
## 1. 上下文污染
一个智能体将错误的输出(幻觉发现、错误架构、损坏状态)写入共享存储。下游智能体将其视为真实信息并在此基础上构建。错误在流水线中复合。
生产中的迹象:看似合理但无法追溯到实际文件内容的发现。智能体对同一个文件自信地相互矛盾。
**预防**:
- 在每个写入点进行架构验证。没有智能体向共享存储写入原始文本;所有内容都通过类型化架构。
- 验证器智能体在输出到达共享存储之前检查它们,而不是之后。
- 人工审查门控,在一个阶段的结果作为种子进入下一阶段之前。
## 2. 级联故障
一个智能体失败。编排器未隔离故障并将坏结果路由到下游。构建在失败输出之上的智能体也失败。没有适当编排的多智能体系统的记录故障率为 41-86.7%。
**预防**:
- 断路器:如果智能体返回错误或空输出,停止该分支,不要转发。
- 流水线检查点的置信度评分:低于阈值的输出不会通过。
- 来自多个智能体的独立发现:如果其他智能体独立达到相同或不同的结论,一个故障无法破坏整个运行。
## 3. 范围蔓延
编排器的分解太宽泛。智能体宽泛地解释其指令。一个被指派“审计代码库”的智能体开始编辑它不应该接触的文件。
**预防**:
- 每个智能体在其任务提示中获得明确、有界的范围:路径、文件类型、允许的操作。
- 编辑策略:除非明确授予特定路径的写入访问权限,否则为只读。
- Anthropic 自己的设计指导:最小占用空间,仅请求必要的权限,首选可逆操作。
## 4. 静默替换
智能体无法完成一个步骤(API 调用失败,文件不可读)并在 try/catch 后悄悄插入占位符数据。它报告成功。流水线将占位符视为真实结果。
**预防**:
在 CLAUDE.md 或您的工作流的智能体系统提示中:
```
错误处理
- 永远不要用模拟或占位符数据替换真实结果
- 如果步骤失败,报告错误并停止此智能体的执行
- 只有在明确记录为带有原因的回退时,回退才是可接受的
```
## 5. 协调死锁
两个智能体相互等待。智能体 A 在智能体 B 完成之前无法继续。智能体 B 在智能体 A 写入共享存储之前无法开始。工作流停滞。
**预防**:
- 工作流脚本中的显式依赖关系图。Claude 的编排脚本将依赖关系编码在代码中,而不是隐含的对话顺序中。
- 每次智能体调用的超时。如果智能体在 X 秒内未返回,编排器将其标记为失败并绕过它路由。
- 设计阶段在发散之前真正独立。依赖映射是第 8 模块的飞行前检查清单。
## 模块 6:治理层
每个多智能体系统都需要三个结构层才能可靠工作:
治理层是将演示与生产系统区分开来的关键。
## 治理层的作用
1. **权限范围界定**:每个智能体都有声明的权限集。安全审计智能体获得只读访问权限。迁移智能体仅获得对特定路径的写入访问权限。没有智能体获得比其任务所需的更广泛的权限。
2. **人在回路门控**:定义哪些操作需要在执行前获得人工批准。不可逆操作(文件删除、生产 API 调用、架构迁移)始终通过 HITL 门控。
3. **审计跟踪**:每个智能体决策、每个操作、每个工具调用都随智能体 ID 和导致它的推理一起记录。当出现问题时,您需要准确重放发生了什么。
4. **爆炸半径限制**:定义任何单个智能体在行为不端时可能造成的最大损害范围。文件系统写入范围限定为工作树,而不是仓库根目录。API 调用限制在没有明确生产访问权限的暂存环境。
## 在 Claude 动态工作流中实现治理
治理层转化为三个具体的工件:
```
CLAUDE.md 规则(适用于会话中的所有智能体):
t## 智能体权限
- 读取访问:整个仓库
- 写入访问:仅任务提示中列出的路径
- Shell 命令:仅批准列表中的命令
- 网络:除非任务提示指定端点,否则不得进行外部调用
## 错误处理
- 不允许静默失败
- 每个错误必须在停止前报告
## 不可逆操作策略
- 数据库写入需要任务提示中的明确批准
- 文件删除需要任务提示中的明确批准
- 没有任务提示中的“production: true”,不得进行生产 API 调用
```
## 模块 7:生产环境中五种 Claude 原生模式
这是 Anthropic 从生产 Claude 系统中可靠运行的经验中记录的五种模式。每一种都直接映射到动态工作流结构。
## 模式 1:提示词链
1. 将复杂任务分解为一系列更简单的提示词。一个的输出成为下一个的输入。每一步都是