rumblr Work in progressWIP

● The AI Primer · Lesson 39 · Part 6: building systems people rely on

Orchestration

how much autonomy to give the model

This lesson covers When to script the steps and when to let the language model choose them, and the named patterns in between

Members · open during launch 22 min11 figures and diagrams

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

  1. Designs run from a fixed workflow, where code decides every step, to several agents. Use the least autonomy that solves the problem.
  2. The named workflow patterns: prompt chaining with gates, routing with a fallback, sectioning and voting, orchestrator-workers, evaluator-optimizer.
  3. Several agents buy focused context and parallelism, and cost tokens, context lost at hand-offs and debuggability.
  4. 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

Reading it: each box to the right moves one more decision from your code to the model. A box further right handles more requests you did not plan for, and is harder to predict, dearer in tokens and harder to debug. Stop at the leftmost box that handles the requests you actually get.

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

fixed workflow router agent loop multi-agent 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 model calls Calls for the same question fixed workflow router agent loop multi-agent 0 200 400 600 800 1000 tokens (input + output) Tokens for the same question

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

Reading it: the left panel counts model calls and the right panel tokens. Calls stay at 2 until multi-agent doubles them, but tokens climb sooner. The agent loop sends about ten times the fixed workflow's, because every call re-sends the tool definitions and tool results, and multi-agent adds a planning call and the messages between agents. Those tokens pay for handling requests the workflow was not written for, and are wasted on requests it already answers.

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

Reading it: two model calls run in a fixed order, with plain code (the diamond) between them. An outline that fails takes the "no" arrow and ends the run with the reason, before a draft is paid for or built on it.

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

Reading it: the classifier is the only model call that chooses anything. The "anything else" arrow catches every label not on the list, since a model's free text can be anything.

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

Reading it: the three calls run at once, so the wait is the slowest one's, and plain code counts the answers. Sectioning has the same shape, with a different sub-task on each branch.

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

2 4 6 8 10 12 14 number of independent voters (odd) 0.5 0.6 0.7 0.8 0.9 1.0 P(majority is right) Voting: many noisy judges beat one (if their errors are independent) each voter right 60% each voter right 70% each voter right 80% each voter right 90%

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

Reading it: each curve is one voter's accuracy, from 60% to 90%, and the x-axis adds voters. Every curve rises, slowly at 60%. All of them assume independent mistakes. Five copies of one model given one prompt tend to make the same mistake, and then a vote adds little, so vary the prompt, the model or the evidence.

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

Reading it: the shape is sectioning's, but the worker boxes did not exist until the orchestrator call wrote them, so the split fits each request, including ones you could not list in advance.

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

Reading it: the loop has two ways out, PASS and the round limit. Without the limit, an evaluator that is never satisfied would keep it running forever. The pattern works when the criteria can be checked, as "cites a policy document" can.

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

Reading it: time runs downward. The two messages from the supervisor are the hand-offs, and each is all its specialist knows. That keeps each specialist's context small and focused, and anything the supervisor leaves out is lost. Peer designs, where agents hand control to one another, lose context at hand-offs the same way.

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

Reading it: every box is a state and every arrow a transition. Only two arrows are labelled "LLM"; the rest are rules you can read, test and audit. When a run goes wrong, its history shows which state it was in and which rule moved it on.

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

resume from checkpoint restart from scratch 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 model calls to finish one invoice Posting crashed once: what did it cost? 2 4

After one crash while posting, resuming from the checkpoint finishes in 2 model calls, while restarting from scratch takes 4

Reading it: both bars meet the same crash, while posting. The resumed run finishes with the 2 model calls it had already made. The restarted run asks the model both questions again, doubling the cost, and the model may give a different answer the second time.

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

Yao et al., ReAct: Synergizing Reasoning and Acting in Language Models (2022).

It established the reason-act-observe loop that the "agent loop" rung of the spectrum is built on.

Read on rumblr →The paper

Researcher'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.