What this is
What is orchestration?
Orchestration is how much of a job you let an AI language model decide for itself. At one end, your code runs fixed steps and asks the language model to fill in each one. At the other, the language model picks its own next step until it says it is done; a system like that is called an agent. Between the two sit a handful of named designs, each handing the language model one more decision. On a help-desk question, a two-step script and an agent give the same answer, but the agent sends about ten times as much text. So the rule is to use the least autonomy that solves the problem.
Why it matters: The moment a task needs more than one call to a language model, you choose between a script that decides the steps and a language model that does. Give a script requests that vary and it grows a special case for each new one; give an agent a two-step job and it sends ten times the text to do it.
At a glance
Key takeaways
- Designs run from a fixed workflow, where code decides every step, to several agents. Use the least autonomy that solves the problem.
- The named workflow patterns: prompt chaining with gates, routing with a fallback, sectioning and voting, orchestrator-workers, evaluator-optimizer.
- Several agents buy focused context and parallelism, and cost tokens, context lost at hand-offs and debuggability.
- Production shape: an explicit state machine that asks the model only at chosen states and saves a checkpoint after every step.
How it works, from scratch
The examples come from one setting: an assistant that answers staff questions from company policy documents, such as how many days of paid time off (PTO) they get, or the meal allowance per day of travel (the per-diem).
Chapter 1
The autonomy spectrum
The simplest design is a fixed workflow: ordinary code that calls the model at set points, here once to rewrite the question as a search and once to answer from what the search found. A router gives the model one decision: which of several fixed paths handles the request. An agent loop hands over the rest: the model chooses which tools to call, reads their results and decides when it is done. A multi-agent system puts several agents on one job, one of them splitting the work among the others.
Figure 1 · Diagram
flowchart LR W[Fixed workflow<br/>code decides steps] --> R[Router<br/>LLM picks a path] R --> A[Agent loop<br/>LLM picks tools] A --> M[Multi-agent<br/>agents coordinate]
One question, "How many PTO days do I get, and what is the meal per-diem when travelling?", sent to each design, shows the cost:
| design | model calls | why |
|---|---|---|
| fixed workflow | 2 | rewrite as a search, then answer |
| router | 2 | classify, then the chosen handler answers |
| agent loop | 2 | one turn with two parallel tool calls, one answer turn |
| multi-agent | 4 | plan, one call per specialist (2), final answer |
Figure 2 · Chart
Workflow, router and agent loop each make 2 calls and multi-agent 4, but the agent loop uses about 990 tokens, ten times the workflow's 93
Chapter 2
The named patterns
Between the fixed workflow and the agent loop sit five designs common enough to have names, from Anthropic's guide Building effective agents. All five are workflows: code owns the flow and calls the model at set points. They differ in what the model is trusted to decide.
In code: every pattern below is built from ask, one model call with
one user message that returns the reply's text. View source
Prompt chaining
Prompt chaining splits a task into a fixed sequence of model calls,
each output feeding the next prompt. Between calls, a code check called a
gate can stop the chain. Here, step 1 writes an outline, and a gate checks that it has at
least three points. The outline "- scope" has one, so the chain stops after
one call and the draft step never runs.
Figure 3 · Diagram
flowchart LR
I[Input] --> S1[LLM: outline] --> G{Gate: 3+ points?}
G -->|yes| S2[LLM: draft] --> O[Output]
G -->|no| X[Stop with the reason]
In code: run_chain runs the steps in order and stops at the first
gate that reports a problem. View source
Routing
A chain gives the model no say in which steps run. Routing gives it
one: a model call classifies the request, and code sends it to that class's
handler, such as billing or technical support. The label comes back as free
text, so code checks it. " Technical\n" is normalized to technical and
routed. "Billing-ish, maybe refunds?" is not a known label, so the request
goes to the general fallback instead of crashing.
Figure 4 · Diagram
flowchart LR Q[Request] --> C[LLM classifier] C -->|billing| B[Billing handler] C -->|technical| T[Tech handler] C -->|anything else| F[Fallback]
In code: route makes the classifier call, normalizes the label and
swaps anything unknown for the fallback. View source
Parallelization: sectioning and voting
Chaining and routing make one call at a time. Parallelization makes
several at once. In sectioning, each call gets a different piece of the
work, such as a safety check running beside the answer. In voting,
every call gets the same prompt and code takes the majority. Three reviewers judge a SQL snippet: two
say "vulnerable" and one says "safe", so the verdict is ("vulnerable", {"vulnerable": 2, "safe": 1}).
Figure 5 · Diagram
flowchart LR
Q[Same prompt] --> R1[Reviewer 1]
Q --> R2[Reviewer 2]
Q --> R3[Reviewer 3]
R1 --> V{Majority}
R2 --> V
R3 --> V
A vote helps when the voters make their mistakes independently. The chance that the majority is right is then:
The formula and its symbols
Symbols
| Symbol | Meaning |
|---|---|
| number of voters (odd, so there are no ties) | |
| chance a single voter is right | |
| number of voters who are right | |
| ways to choose which of the are right |
In words: add up the chances of every outcome where more than half the voters are right.
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
On the example: , : . Three reviewers each right 80% of the time make a panel right 89.6% of the time.
In Python:
from math import comb
n, p = 3, 0.8
# the chance exactly k voters are right ...
P = sum(comb(n, k) * p ** k * (1 - p) ** (n - k)
# ... for every k from ⌊n/2⌋ + 1 to n
for k in range(n // 2 + 1, n + 1))
round(P, 3) # → 0.896
Figure 6 · Chart
Majority accuracy rises with more independent voters: at 70% per voter, 5 voters reach 84% and 15 reach 95%; at 60% per voter the climb is slow
In code: run_sections runs independent pieces of work at once; vote
sends every reviewer the same prompt and returns the majority with its
tally; majority_accuracy computes the formula. View source
Orchestrator-workers
In sectioning, you decide how to split the work when you write the code.
Orchestrator-workers lets the model split it, request by request. An
orchestrator call reads the request and lists the subtasks, a worker
handles each one, and a synthesizer call combines their results into one
answer. Asked "What's the meal per-diem, when are receipts due, and does
PTO roll over?", the orchestrator returns three subtasks. Each worker finds
one policy document (fin-002, fin-004, hr-001), and the synthesizer
writes one answer that cites all three.
Figure 7 · Diagram
flowchart TD Q[Request] --> O[Orchestrator LLM:<br/>decide the subtasks] O --> W1[Worker: per-diem] O --> W2[Worker: receipts] O --> W3[Worker: PTO rollover] W1 --> S[Synthesizer LLM:<br/>one cited answer] W2 --> S W3 --> S
In code: orchestrate asks the orchestrator for the subtasks, runs a
worker on each in parallel and asks the synthesizer for one answer. View source
Evaluator-optimizer
Each pattern so far runs once and stops. Evaluator-optimizer loops. A generator call writes a draft, and an evaluator call checks it against stated criteria and either passes it or sends back feedback for the next draft. Draft 1, "PTO rolls over.", gets the feedback "Missing a citation". Draft 2, "Up to 5 unused PTO days roll over [hr-001].", passes, after 2 rounds.
Figure 8 · Diagram
flowchart LR
T[Task] --> G[Generator drafts]
G --> E{Evaluator:<br/>PASS?}
E -->|feedback| G
E -->|PASS| D[Done]
E -->|max rounds| B[Stop: best effort, flagged]
In code: evaluate_optimize alternates drafts and verdicts, feeding
each critique back, and returns the last draft, the rounds used and whether
it passed. View source
Chapter 3
Multi-agent: a supervisor and specialists
The agent loop, the third box on the spectrum, is the first design in
which the model owns the flow, and it has a lesson of its own (see
The agent loop). The last box puts several agents on one job.
In the form built here, a supervisor agent does none of the work
itself: it splits the job, writes each specialist agent a short brief, and
assembles their answers. The supervisor sends "PTO days per year?" to the
hr specialist and "Meal per-diem?" to finance, and neither specialist
sees the other's question. A task for a legal specialist that does not
exist is reported back instead of crashing the run.
Figure 9 · Diagram
sequenceDiagram participant U as User participant S as Supervisor participant H as HR agent participant F as Finance agent U->>S: PTO and meal allowance? S->>H: "PTO days per year?" (only this) S->>F: "Meal per-diem?" (only this) H-->>S: 20 days [hr-001] F-->>S: 75 dollars a day [fin-002] S-->>U: combined answer
Several agents pay off when the subtasks are truly separate, such as independent research threads, or documents that together would overflow one context. They cost more tokens, lose context at every hand-off, and are much harder to debug.
In code: supervise gets a delegation plan from the supervisor, sends
each specialist only its own task, then asks the supervisor for the final
answer. View source
Chapter 4
An explicit state machine, with the model at specific nodes
A job whose steps are known in advance belongs at the other end of the spectrum, in a fixed workflow. One way to build that workflow so every move can be tested and audited is an explicit state machine: a fixed set of states, a rule for each move between them, and the model asked only at the states that need judgement. Take invoice intake. The model is asked twice: "is this an invoice?" and "extract the number, vendor and amount". Code does the rest. It validates the fields, holds any invoice over 5,000 for a person to approve, and posts the others to the ledger. Three documents go through it:
INVOICE INV-2041 ... 1200.00 -> RECEIVED > CLASSIFIED > EXTRACTED > VALIDATED > POSTED > DONE
INVOICE INV-2042 ... 18000.00 -> RECEIVED > CLASSIFIED > EXTRACTED > VALIDATED > AWAITING_APPROVAL
Acme newsletter -> RECEIVED > REJECTED
Figure 10 · Diagram
stateDiagram-v2 [*] --> RECEIVED RECEIVED --> CLASSIFIED: LLM says invoice RECEIVED --> REJECTED: LLM says other CLASSIFIED --> EXTRACTED: LLM extracts fields EXTRACTED --> VALIDATED: code checks pass EXTRACTED --> NEEDS_REVIEW: code checks fail VALIDATED --> AWAITING_APPROVAL: amount > limit VALIDATED --> POSTED: code posts to ledger AWAITING_APPROVAL --> POSTED: human approves POSTED --> DONE
In code: InvoiceWorkflow.run walks the states, calling the model only
at RECEIVED and CLASSIFIED, and InvoiceWorkflow.approve is the human step
that releases a held invoice. View source
Checkpoints and durable execution
A state machine always knows which state a run is in, so after every transition it can save the run to disk as a checkpoint. After a crash, the rerun loads the checkpoint and resumes after the last completed step. A workflow whose progress survives crashes this way has durable execution. Engines such as Temporal provide it at scale.
Figure 11 · Chart
After one crash while posting, resuming from the checkpoint finishes in 2 model calls, while restarting from scratch takes 4
In code: InvoiceWorkflow saves a checkpoint after every transition
and loads it at the start of InvoiceWorkflow.run. resume_comparison
crashes the ledger once and counts the model calls each way. View source
Chapter 5
Frameworks vs. plain code
Every design above can be written by hand or taken from a framework. LangGraph models agents as graphs with explicit state and checkpoints. The Claude Agent SDK and the OpenAI Agents SDK give you vendor-built agent loops, tools and hand-offs. CrewAI and AutoGen focus on teams of agents. Temporal provides durable execution for any code. A framework earns its place when you want its standard patterns, built-in tracing, saved state and hooks for a person to step in. Plain code suits simple flows, and gives full control with fewer dependencies. Each design in this lesson is under 100 lines of plain Python, and having seen them you can judge what a framework would add.
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1Q: When would you use a fixed workflow instead of an agent? Give an example.Think it through, then reveal
A: When the steps are known in advance and the variation is inside each step, not in which steps happen. Invoice intake is the example: classify, extract, validate, approve, post. A workflow is cheaper, faster, testable and auditable. The model is used where judgement is needed (classification, extraction), and code owns the flow. Reach for an agent only when the path genuinely depends on what's discovered along the way.
Question 2Q: Single agent vs. multi-agent for a document-processing workflow: what does each side have going for it?Think it through, then reveal
A: For one agent (or a workflow): documents flow through the same steps, hand-offs lose context, multi-agent multiplies tokens, and one trace is far easier to debug. For several agents: documents are independent and can be processed in parallel, each document or section may overflow a single context, and specialists (tables, legal clauses, figures) benefit from focused instructions and tools. A common answer is a workflow that fans out per document to a focused worker, which is orchestrator-workers rather than free-form agents talking to each other.
Question 3Q: A router's classifier sometimes returns labels that aren't in its list. How should the code handle that?Think it through, then reveal
A: Normalize (case, whitespace), accept only known labels, and send
everything else to a safe fallback. Log the misses and add them to the
classifier's evaluation set. Consider structured output with an enum so
the model can only produce valid labels.
Question 4Q: Why checkpoint after every step of a long workflow?Think it through, then reveal
A: So a crash costs one step, not the run. Resuming reuses completed work (no repeated model calls, no double-posted invoices when combined with idempotency keys) and avoids getting a different answer on the rerun.
Primary sources
The papers behind this lesson
It established the reason-act-observe loop that the "agent loop" rung of the spectrum is built on.
Read on rumblr →The paperResearcher's shelf
Further reading
- Anthropic, Building effective agents (the named patterns): https://www.anthropic.com/engineering/building-effective-agents
- LangGraph docs: https://langchain-ai.github.io/langgraph/
- OpenAI Agents SDK: https://openai.github.io/openai-agents-python/
- CrewAI docs: https://docs.crewai.com/
- AutoGen: https://microsoft.github.io/autogen/
- Temporal, durable execution: https://docs.temporal.io/
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.