Skip to content

Lesson 15 of 40Agents

Agent Design Patterns

Pick the simplest AI pattern that works: chaining, routing, parallel calls, orchestrator-workers, evaluator loops or a full agent.

16 min read0/5 questions

Most useful AI systems are not one giant autonomous agent. They are a handful of small, well-known shapes: a few model calls in a fixed order, a cheap classifier that sends work to the right place, a draft followed by a critique. Each shape has a name, a job it does well, and a cost. Knowing them lets you design an AI feature the way you design any other code: start with the simplest thing that could work, measure it, and only add moving parts when the numbers say you should. This lesson walks through the patterns from least to most autonomous, with a tiny example and the price of each.

A ladder of patterns

Think of the patterns as rungs on a ladder. The bottom rung is a single model call: classify this email, summarise this document, extract these fields. Each rung above it gives the model more control over what happens next, and each one costs more tokens, more latency and more ways to fail.

PatternWho decides the stepsTypical callsGood for
Single callNobody, there is one step1Classify, summarise, extract
Prompt chainingYour code, fixed order2 to 5Tasks with clear stages
RoutingYour code, after a model classifies2Mixed inputs needing different handling
ParallelizationYour code, many calls at onceNIndependent parts, or a second opinion
Orchestrator-workersA model, on the fly1 + NWork you cannot split in advance
Evaluator-optimizerYour code loops, a model judges2 to 10Output with clear quality criteria
Autonomous agentThe model, every stepUnknownOpen-ended tasks with good checks

The middle rungs are workflows: your code controls the steps, and models fill in the parts that need language. The top rung is an agent: the model chooses its own next step in a loop. The what-is-an-agent lesson covers that difference in detail. The rule from the official guidance applies to every rung: climb only as high as the task needs.

From fixed steps to full autonomy
Single call: one promptSingle callone promptChain: fixed steps + gatesChainfixed steps + gatesRouter: classify, then sendRouterclassify, then sendParallel: split or voteParallelsplit or voteOrchestrator: plans on the flyOrchestratorplans on the flyEvaluator: draft, judge, retryEvaluatordraft, judge, retryAgent: model picks each stepAgentmodel picks each stepmore stagesvaried inputindependent partsparts unknownneeds quality baropen-ended

Start here. One clear prompt solves more problems than people expect.

1/6

Prompt chaining

Prompt chaining means breaking a task into a fixed sequence of model calls, where each call's output becomes the next call's input. Between steps you put a gate: a plain code check that stops the chain early if something looks wrong.

Example: turning a support email into a reply. Step 1 extracts the order number. The gate checks that an order number was found. Step 2 drafts the reply using it. Without the gate, step 2 happily writes a confident reply about an order that does not exist.

When to use it: the task has clear stages you can name in advance, and each stage is easier for a model than the whole. Each call gets a shorter, more focused prompt, which usually means better answers.

Cost: one call per step, run one after another, so latency adds up. In exchange, each step is simple enough to test on its own.

Routing

Routing means classifying the input first, then sending it to a specialised prompt, tool or model. The classifier is usually a small, cheap model, because "is this billing, technical or general?" is an easy question.

Example: a support inbox where billing questions need the order system, technical questions need careful troubleshooting from a capable model, and "do you have a student discount?" can go to a small model with a short prompt.

When to use it: your inputs fall into distinct groups that are handled better separately. One prompt that tries to cover every case gets long and confused; three focused prompts each do their job well.

Cost: one extra cheap call per request. It often saves money overall, because most traffic can go to a cheaper model.

Here is a routing step in front of a short chain, over a fake model so it runs in your browser. The fake model uses keyword rules where a real one would understand the text, but the structure is exactly what you would build with the API.

Python
PRICE = {"small": 0.10, "large": 4.00} # $ per million input tokens (course snapshot)calls = [] def fake_model(tier, prompt): """Stand-in for an LLM call. Real code would call the API here.""" calls.append((tier, len(prompt.split()))) p = prompt.lower() if p.startswith("classify"): if "refund" in p or "charged" in p: return "billing" if "error" in p or "crash" in p: return "technical" return "general" if p.startswith("extract"): ids = [w.strip(".,!?") for w in prompt.split() if w.startswith("#")] return ids[0] if ids else "NONE" if p.startswith("draft billing"): order = prompt.split()[2] return f"We are checking the charge on order {order} and will refund it if it is a duplicate." if p.startswith("draft technical"): return "Sorry about the crash. Which app version are you on?" return "Thanks for writing in. A teammate will reply within a day." def handle(ticket): # Step 1, routing: a cheap model picks the lane. route = fake_model("small", "classify as billing, technical or general: " + ticket) if route == "billing": # Prompt chaining: extract, check, then draft. order = fake_model("small", "extract the order id: " + ticket) if order == "NONE": # the gate between steps: plain code, no model return route, "Could you send your order number (it starts with #)?" return route, fake_model("large", f"draft billing {order} reply to: " + ticket) if route == "technical": return route, fake_model("large", "draft technical reply to: " + ticket) return route, fake_model("small", "draft a short friendly reply to: " + ticket) tickets = [ "I was charged twice for order #4821, please refund one.", "The app shows an error and then crashes on launch.", "Do you have a student discount?", "I want a refund but I lost the email.",]for t in tickets: route, reply = handle(t) print(f"[{route:9}] {reply}") small = sum(1 for tier, _ in calls if tier == "small")large = len(calls) - smallrouted = sum(n * PRICE[tier] for tier, n in calls)all_large = sum(n * PRICE["large"] for _, n in calls)print(f"\n{len(calls)} model calls: {small} small, {large} large")print(f"input cost with routing is {routed / all_large:.0%} of sending every call to the large model")
Output
Press Run (⌘ Enter) to see what happens.

Look at the fourth ticket: the gate caught the missing order number, so no expensive draft call was made. Try adding a ticket of your own, or change the gate so it lets NONE through, and see what the draft says.

Predict the outputPython

What does this print?

steps = ["extract", "check", "draft"]
done = []
for s in steps:
  if s == "check" and "order" == "NONE":
      break
  done.append(s)
print(len(done))
Need a nudge? Hints walk you through it.

Parallelization

Parallelization means running several model calls at the same time and combining the results in code. It comes in two flavours:

  • Sectioning: split a task into independent parts and do them at once. Example: reviewing a pull request for security, performance and readability as three separate calls, each with a focused prompt. Each reviewer does better than one call asked to check everything.
  • Voting: run the same task several times and compare. Example: ask three times "does this comment break our community rules?" and flag it if two or more say yes. Disagreement itself is useful information: it tells you the case is hard and may need a human.

When to use it: the parts genuinely do not depend on each other, or you need more confidence than one answer gives.

Cost: you pay for every call, so three-way voting triples the token bill. Wall-clock time stays close to one call, because they run together.

Match the pairs0/5 matched

Match each situation to the pattern that fits it best.

Choose an item, then its match on the other side.

Orchestrator-workers

In orchestrator-workers, a capable model looks at the task, decides what the subtasks are, hands each to a worker (another model call), and combines the results. The difference from sectioning is that nobody wrote the list of parts in advance. The orchestrator figures it out at run time.

Example: "rename this setting everywhere it is used". You cannot know beforehand which files are involved, so the orchestrator searches, then sends each affected file to a worker. Coding tools work this way constantly. The subagents and orchestrators lesson covers how to build this in Claude Code, including giving workers their own context and cheaper models.

Cost: one planning call plus one call per worker, plus a combining step. The number of calls is decided by the model, so put a cap on it.

Evaluator-optimizer

In evaluator-optimizer, one call produces a draft and a second call grades it against written criteria. If it fails, the critique goes back to the first call for another try. Your code runs the loop and enforces a maximum number of rounds.

Example: writing release notes. The evaluator checks: under 150 words, every change mentioned, no internal ticket numbers, plain language. The critique ("mentions JIRA-482, remove it") is specific enough for the next draft to fix.

When to use it: you can state clear criteria, and a critique genuinely improves the next draft. If you cannot say what "good" means, the evaluator just adds cost. This is the same idea as the build, test, review loop, applied inside an application.

Cost: two calls per round, times the number of rounds. Two or three rounds is usually where improvements stop.

Two rounds of evaluator-optimizer
Your codeWriterEvaluatordraft release notesdraft 1grade draft 1FAIL: remove JIRA-482revise with critiquedraft 2grade draft 2PASS

Your code sends the task and the criteria to the writer call.

1/8
Quick check
When does an evaluator-optimizer loop add the most value?
Need a nudge? A hint rules out a wrong answer.

Autonomous agents

At the top of the ladder, the model runs in a loop with tools, choosing every step until it decides it is done. You give it a goal, tools, and an environment, and it plans, acts, observes results and adjusts. Claude Code doing a multi-file change and running the tests is an agent.

When to use it: the task is open-ended, the steps cannot be predicted, the work is valuable, and mistakes can be caught by tests, review or rollback. That last point decides most cases. An agent that edits code behind a test suite and a pull request is safe to try. An agent that sends emails to customers with no review is not.

Cost: the highest and the least predictable. Each turn resends a growing context, and the number of turns is up to the model. Always set a maximum number of turns.

Start simple, measure, then climb

The common mistake is reaching for an agent because it sounds impressive. A practical process:

  1. Write the single-call version first, with a good prompt.
  2. Build a small set of real test inputs and measure how often it is right (the evals lesson shows how).
  3. If it fails in a pattern you can name ("it mixes up billing and technical questions"), add the one pattern that fixes that failure, here routing.
  4. Measure again. Keep the change only if the numbers improve enough to pay for the extra calls.

Patterns combine. The runnable example above is routing in front of a chain. A real product might route, then chain, with a voting step for the risky lane. Each addition should earn its place with a measurement.

Put it in order4 steps

Put these patterns in order from least to most autonomous.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Your single-call ticket classifier is right 82% of the time. Most errors are long emails that mention two topics. What is the best next step?
Need a nudge? A hint rules out a wrong answer.
Key terms
prompt chaining
A fixed sequence of model calls where each output feeds the next, with code checks between steps.
gate
A plain code check between chain steps that stops the chain when an output looks wrong.
routing
Classifying an input first, then sending it to a specialised prompt, tool or cheaper model.
parallelization
Running several calls at once: independent sections of a task, or the same task several times to vote.
orchestrator-workers
A model decides subtasks at run time, delegates them to worker calls, and combines the results.
evaluator-optimizer
One call drafts, another judges against criteria, and the loop repeats until the draft passes or a limit is hit.
workflow
An AI system where your code controls the steps and models fill in the language parts.