Pattern: prompt chaining

In one sentence

Split a task into a fixed sequence of LLM calls, each consuming the previous output, with code checks between steps: you trade extra latency for accuracy and per-step debuggability.

Analogy: An assembly line with inspection stations: each worker does one simple job, and an inspector rejects a bad part before the next station spends work on it.

Each step is one narrow LLM call; code gates between steps stop a bad intermediate before you pay for the next call.

How it works

  • You fix the steps in code, not the model: that makes it a workflow, not an agent.
  • Gates check each intermediate result (schema, length, section count), then retry, repair or stop early.
  • Each call gets a narrower job and shorter prompt, so it errs less than one mega-prompt.
  • Errors compound: five steps at 95% each give ≈ 77% end-to-end unless gates catch them.
  • Chain only when you can name the steps in advance; input-dependent steps need Pattern: routing or Pattern: orchestrator–workers.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your chain: (1) extract an invoice's line items and printed total as JSON, (2) write a summary from that JSON. The gate after step 1 validates the JSON schema, yet ~1 in 10 summaries is wrong because a line item went missing. Highest-leverage fix?

Go deeper

Full explanation

Prompt chaining breaks one hard task into a fixed sequence of simpler LLM calls, where each call receives the previous call's output. You decide the steps, in code, not the model: that is what makes it a workflow rather than an agent (Agents vs workflows).

Between steps you put gates: plain code that checks the intermediate result before you pay for the next call. Does the outline have 3–6 sections? Does the JSON validate against the schema (Structured outputs & JSON mode)? Is the summary under 200 words? If a gate fails, you retry that step, repair it, or stop early.

Why it works: each call gets a narrower job and a shorter, focused prompt, so it makes fewer mistakes than one mega-prompt juggling ten instructions. You also get one eval per step: when the output is bad, you know which link broke.

The cost is latency and tokens: N sequential round-trips, and errors compound (five steps at 95% each ≈ 77% end-to-end) unless gates catch them. Chain only when the task decomposes cleanly into steps you can name in advance; if the steps depend on the input, you need Pattern: routing or Pattern: orchestrator–workers.

Code Outline → gate → write → translate
pythonOutline → gate → write → translate
import json
from anthropic import Anthropic

client = Anthropic()
MODEL = "claude-sonnet-4-5"  # any chat model

def llm(prompt: str) -> str:
    msg = client.messages.create(model=MODEL, max_tokens=2048,
                                 messages=[{"role": "user", "content": prompt}])
    return msg.content[0].text

OUTLINE = ('Outline a blog post for this brief. Reply with JSON only: '
           '{"sections": [{"title": str, "points": [str]}]}\n\n')

def outline_gate(raw: str) -> dict | None:
    # Gate = plain code: deterministic, free, microseconds
    try:
        sections = json.loads(raw)["sections"]
    except (json.JSONDecodeError, KeyError, TypeError):
        return None
    return {"sections": sections} if 3 <= len(sections) <= 6 else None

def launch_post(brief: str, retries: int = 2) -> str:
    for _ in range(retries + 1):                     # retry only the step that failed
        if outline := outline_gate(llm(OUTLINE + brief)):
            break
    else:
        raise ValueError("outline failed its gate")  # stop before paying for steps 2-3
    # Carry the original brief forward: later steps must not lose its constraints
    draft = llm(f"Brief:\n{brief}\n\nWrite the post following this outline:\n{json.dumps(outline)}")
    if len(draft.split()) > 900:                     # gate 2: length budget -> repair step
        draft = llm(f"Cut this to under 800 words, keep every section:\n{draft}")
    return llm(f"Translate to Latin-American Spanish; keep product names:\n{draft}")
Real example

A SaaS team turns ~40 merged PRs into customer release notes. One mega-prompt (summarize, group by feature, write for customers, translate) dropped about 1 in 5 user-facing changes and leaked internal ticket ids. They split it: (1) a small model labels each PR user-facing or internal; (2) a larger model writes grouped notes, tagging each item with its PR id; (3) a code gate checks that every user-facing PR appears exactly once and no JIRA- id leaked; (4) translate. Latency rose from ~8 s to ~20 s, irrelevant for a nightly job, and each step now has its own eval set, so a regression points at one prompt.

Trade-offs +4 · −4

+ You gain

  • Each call does one narrow job, which usually beats one mega-prompt juggling every instruction.
  • Debuggable: every intermediate output can be logged and evaluated, so failures point at one step.
  • Gates are plain code: deterministic, free, and they stop bad runs early.
  • Mix models per step: a small one to classify, a strong one to write.

− You pay

  • Latency is additive: N sequential round-trips with no parallelism.
  • Errors compound across steps unless gates catch them.
  • Rigid: the step list is fixed, so unusual inputs get forced down the same path.
  • Later steps see only what you pass forward; nuance from the original input can get lost.

Use it when

The task decomposes cleanly into steps you can name in advance (extract → check → write → translate), and you'd rather spend latency than accuracy.

Avoid it when

Latency-critical chat turns, tasks one good prompt already handles, or steps that depend on the input: that's routing or orchestrator–workers.

Numbers to know 3
  • Reliability multiplies: five steps at 95% each ≈ 77% end-to-end (0.95⁵). Gates exist to break this math.
  • Latency is additive: end-to-end ≈ sum of step latencies, plus any retries the gates trigger.
  • A code gate costs microseconds and $0; an LLM-judge gate adds a full call (~0.5–3 s). Prefer code gates where possible.
Common pitfalls 4
  • Passing only the previous output forward: step 4 never sees the user's original constraints. Carry the original input through.
  • Gates that check only format: valid JSON with wrong content sails through. Check invariants too (counts, ids, required facts).
  • Rerunning the whole chain when one step fails; retry or repair just that step.
  • Chaining what one prompt already does well: 3× the latency for nothing. Measure a single-prompt baseline first.
Interview questions 3

Answer out loud first, then reveal.

When would you chain prompts instead of writing one bigger prompt?Show answer

When the task has distinct sub-jobs that compete for the model's attention (extract, then reason, then format) or when I need to check something in between. I start with a single-prompt baseline and an eval. If it fails consistently in one place, I split there, put a code gate on the intermediate output, and evaluate each step on its own. The trade-off is latency: every step is a sequential round-trip, so in an interactive turn I keep it to two or three calls and push longer chains into async jobs.

Your four-step chain succeeds 70% of the time end to end. How do you debug it?Show answer

I log every intermediate output and score each step on its own eval set, because reliability multiplies: four steps at 92% already land near 70%. That shows me where success drops. Then I fix the weakest link: tighten its prompt, give it a structured-output schema, or add a gate with a retry right after it. I also check the hand-offs; often step 3 fails because step 1 dropped a constraint it needed, so I pass the original input forward too.

How is a prompt chain different from an agent?Show answer

In a chain, code fixes the steps and their order, and the model only fills in each step. In an agent, the model chooses the next action and when to stop. That makes chains predictable in cost and latency and easy to test step by step, while agents handle open-ended work at the price of variance and harder evals. I default to a chain and hand control to the model only when I can't list the steps in advance.