Cheat sheets

Orchestration Patterns Compared

Pick supervisor, swarm, hierarchical, debate or a plain workflow. Stdlib Python from the lessons.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Comparisons
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Four topologies side by side#

FactorSupervisor-workerSwarmHierarchicalDebate
Who routesOne central LLMNo central routerSupervisors of supervisorsParallel proposers
Agents talkOnly through the supervisorDirect handoffsOnly leaves do workCross-critique
Demo traceCleanestShortestDeepestMost expensive
Fits2-4 specialistsLatency over reasoning clarityLarge agent populationsAccuracy over cost
Weak pointSupervisor is the bottleneckHard to reason aboutDecomposition driftCost
FrameworksLangGraph create_supervisorLangGraph swarm topologyNested subgraphs or crewsCustom

From Lesson 14.28, Lesson 16.09, Lesson 16.06

Decision order#

1Single agentstart with workflow patterns from Lesson 12.2Supervisor-workerwhen you have 2-4 specialists.3Swarmwhen latency matters more than reasoningclarity.4Hierarchicalonly when supervisor context budget fails.5Debatewhen accuracy matters more than cost.

From Lesson 14.28

Supervisor with parallel workers#

sub_qsub_qsub_qsummarysummarysummaryclientUser querymodelLead.plan3 sub-questionsprocessWorker 0fresh contextprocessWorker 1fresh contextprocessWorker 2fresh contextmodelLead synthesizessummaries onlysub_qsub_qsub_qsummarysummarysummaryclientUser querymodelLead.plan3sub-questionsprocessWorker 0fresh contextprocessWorker 1fresh contextprocessWorker 2fresh contextmodelLeadsynthesizessummariesonly

From Lesson 16.05, 16.05 code/main.py

Use each pattern when#

  • Use a workflow when you can enumerate the steps.
  • Use an agent when the next step depends on what the last step returned.
  • Use supervisor for research: each worker gets its own 200k-token window.
  • Use swarm for many independent tasks with variable duration.
  • Use hierarchical when the task has real independent sub-teams.
  • Use sequential when step 2 needs the output of step 1.
  • Use static graphs when audit and replay matter more than adaptability.
  • Use CrewAI Flow as the production starting point. Use Crew for autonomous roles.

From Lesson 14.12, Lesson 16.05, Lesson 16.09, Lesson 16.06, Lesson 14.28

Five workflow patterns in code#

TaskCode
Prompt chaining: output N feeds call N+1prompt_chain(input_text, llm, steps)
Routing: classify, then dispatchroute(input_text, classifier, handlers)
Parallelization: N runs, majority winsparallel_vote(prompt, llm, n=5)
Orchestrator-workers: pick workers, synthesizeorchestrator_workers(task, workers, synth)
Evaluator-optimizer: loop until PASSevaluator_optimizer(task, proposer, evaluator, max_iter=5)
Fallback handler for an unknown labelhandlers.get(label) or handlers.get("default")
Run all five demospython3 code/main.py

From 14.12 code/main.py, Lesson 14.12

Workflow or agent#

FactorWorkflowAgent
Who owns the graphEngineersThe model
Step countBoundedCan spiral
DebuggingEasierHarder failure modes
AuditAuditors read the graphInferred from trajectories
FitsPredictable tasksOpen-ended research

From Lesson 14.12

Lead fans out to threads#

sub_questions = self.plan(query)3 sub-questions
results: list[WorkerResult | None] = [None] * len(sub_questions)
threads: list[threading.Thread] = []
for i, sq in enumerate(sub_questions):
w = Worker(worker_id=i, trace=self.trace)fresh worker per sub-question
th = threading.Thread(target=w.run, args=(sq, results, i))
threads.append(th)
th.start()all workers run at once
for th in threads:
th.join()wall time near max, not sum
synthesis = self.synthesize(query, [r for r in results if r is not None])

From 16.05 code/main.py

Swarm workers pull from one queue#

q: queue.Queue = queue.Queue()
for t in tasks:
q.put(t)no orchestrator assigns work
def worker(wid: int) -> None:
while True:
try:
task = q.get_nowait()
except queue.Empty:
returnqueue drained, worker exits
fake_work(task)
with lock:
counts[wid] += 1fast workers pull more jobs
q.task_done()

From 16.09 code/main.py

Limits and budgets#

SettingDefaultNote
Swarm hops3while hops < 3 stops A to B to A bouncing
parallel_vote n5Same prompt, majority vote
max_iter5Evaluator-optimizer stops after 5 tries
Tree depth2Three levels hide most errors
Reconciliation rounds2Then the top manager must commit
Worker timeout2× median runtimeKill, then respawn narrower or skip
Worker token cap10×Of the expected synthesis input
Supervisor specialists2-4Step 2 of the decision order

From 14.28 code/main.py, Lesson 14.28, 14.12 code/main.py, Lesson 16.06, Lesson 16.05

Numbers that matter#

Research gain
+90.2% over single-agent Opus 4 on internal research evals.
Token share
80% of BrowseComp variance comes from token usage alone.
Token cost
multi-agent is ~15× the tokens of single-agent.
Scale effort
simple queries use one agent and 3-10 tool calls. Complex ones use 10+ agents.
Wall clock
three 0.3-second workers finish in ~0.35 seconds, not 0.9.
Swarm demo
8 tasks, 4 slow (0.4s) and 4 fast (0.1s), 4 workers.
Pattern size
each workflow pattern is ~10-15 lines of code.

From Lesson 16.05, 16.09 code/main.py, Lesson 14.12

Failures and fixes#

SymptomCauseFix
Precise answers to the wrong questionLead hallucinates the planLog the plan, diff it against the query
Synthesis gets pollutedWorkers over-exploreSet explicit scope boundaries
User never sees a conflictLead silently picks one sideRe-ask or state the disagreement
Branch answers the wrong topicManager mislabels a branchAdd a canary worker with the original query
Sub-managers loopConsensus loopSet a reconciliation budget
Long tasks never runQueue starvationPriority queue with aging
Task runs twice after a crashWorker crashed mid-runMake workers idempotent, use a durable queue

From Lesson 14.28, Lesson 16.05, Lesson 16.06, Lesson 16.09

Questions#

Why supervise through tool calls?
You decide exactly what each specialist sees.
Why does supervisor win on research?
Fresh context per subagent is the main mechanism.
Why rainbow deployments?
Agents are long-running and stateful. Blue-green does not work.
Where does a hierarchy error show?
At the top synthesis, one level from where a human could catch it.
Why not swarm for a report?
A swarm of researchers gives independent facts, not a coherent report.
How do you debug a swarm?
Give every task a trace ID. Log start and end with it.

From Lesson 14.28, Lesson 16.05, Lesson 16.06, Lesson 16.09