Topic 1 of 5 · 4 min read
Prompt chaining with code gates
Goal: Design a prompt chain for a described task with a code gate after each step that stops bad output from flowing on.
A prompt chain splits one task into fixed, sequential model calls, and puts a code gate between the calls so a bad output stops there instead of flowing downstream. The model does the language work. Ordinary code decides whether the work is good enough to continue.
Check yourself · 1 of 3
In a prompt chain, what is a code gate?
Why it matters
One long prompt that says "extract the data, validate it, write the summary and translate it" asks the model to hold four jobs at once, and you cannot see which job failed. A chain gives each call one narrow job, so each prompt is shorter and each failure has an address. The price is latency and cost: every step is another call. Chain only when a single call gets the task wrong, or when the steps need different prompts, models or tools.
How to build one
- Write the steps as a plan. Each step has one input, one output and one job. "Extract invoice fields to JSON" is a step. "Handle the invoice" is not.
- Make each output checkable. Ask for JSON or another structure code can parse, not prose.
- Add a gate after every step. A gate is plain code: a schema check, a regex, a range check, a lookup, a length limit. It returns pass or fail, never "looks fine".
- Decide what a failed gate does. Retry the step once with the error message appended, route to a human, or stop the run with a clear status. Never pass the bad output on.
- Log each step's input, output and gate result, so a wrong final answer can be traced to the step that caused it.
Before and after
# Before: one call, no checks
report = llm("Read this invoice, pull out the fields, check the total and write a summary for finance.")
# After: three calls, two gates
fields = llm_json(EXTRACT_PROMPT, invoice_text)
gate(fields, schema=INVOICE_SCHEMA) # required keys, types
gate(abs(sum(l["amount"] for l in fields["lines"]) - fields["total"]) < 0.01)
summary = llm(SUMMARY_PROMPT, fields) # sees checked data only
gate(len(summary) <= 600)
The summary step never sees fields whose line items do not add up to the total.
What goes wrong
- Gates that ask another model "is this good?" with no criteria. That is a second guess, not a check. Use code where the rule can be written as code.
- Passing prose between steps. Free text changes shape from run to run, so the next prompt breaks in ways that are hard to see.
- Over-chaining. Seven steps for a task one call handles reliably only adds latency and seven places to fail.
- No failure path. A gate that raises an exception with no retry or hand-off turns every rare bad output into an outage.
Examples
Support-ticket summary chain
Step 1 extracts {customer, product, issue, urgency} as JSON. Gate: urgency must be one of low, normal, high, else retry once with the validation error. Step 2 drafts a reply from the checked JSON. Gate: the reply must contain the customer name and be under 150 words. Step 3 translates the reply. If any gate fails twice, the ticket goes to a human queue with the step log attached.
A gate that earns its place
A chain turns meeting notes into tasks. A code gate checks that every task has an owner who appears in the attendee list. In testing it catches invented owner names the team never noticed before the gate existed. A model-based gate would have needed its own prompt and could make the same mistake.
Key points
- A prompt chain splits a task into fixed sequential calls, each with one narrow job.
- A gate is plain code, such as a schema or range check, placed between steps so bad output stops early.
- Pass structured data such as JSON between steps so the gate and the next prompt see a stable shape.
- Every gate needs a failure path: retry with the error, hand off to a person, or stop with a clear status.
- Chain only when one call fails at the task or the steps need different prompts, models or tools.
Common mistakes
- Using a model call as the gate when a schema, regex or lookup would do.
- Passing free-text prose between steps instead of structured data.
- Adding steps without measuring whether a single call already works.
- Letting a failed gate raise an exception with no retry, hand-off or status.
Check yourself · 2 of 3
A chain extracts invoice fields as JSON, then writes a finance summary. Which gate belongs between the two steps?
Check yourself · 3 of 3
A gate fails on step two of a four-step chain. What is the safest default?
Practice items, not counted towards your mastery.
Start here
- Building effective agents (Anthropic) (opens in a new tab)ArticleFree
Defines the five workflow patterns in this skill and when each earns its added cost.
- Workflows and agents (LangGraph docs) (opens in a new tab)DocsFree
Runnable code for chaining, routing, parallelization, orchestrator-workers and evaluator-optimizer.
- How we built our multi-agent research system (Anthropic) (opens in a new tab)ArticleFree
A production orchestrator-workers system, with the failures and trade-offs the team met.