AI
Prompt Chaining: Break Big Tasks Into Steps
Prompt chaining splits a complex AI task into steps, each prompt using the last output. How it works, examples, code, and when it beats one big prompt.
Prompt chaining is a way of using a language model in several smaller steps instead of one big prompt. Each step is a separate model call with its own focused instructions, and the output of one step becomes the input to the next. Instead of asking "read this contract and write a summary email with risks and next steps", a chain might extract the key clauses, then flag risks in those clauses, then draft the email from the flagged risks, with a check between steps.
Breaking work up this way makes each step easier for the model, easier for you to test and easier to fix when something goes wrong. It costs more calls and more time. This guide explains how prompt chaining works, gives a worked example with code, compares prompt chaining vs chain of thought and vs agents, lists the common patterns, and covers when chaining helps and when one prompt is better.
Prompt Chaining at a Glance
| Single prompt | Prompt chain | |
|---|---|---|
| Model calls | One | Several, in a fixed or branching order |
| Instructions per call | Everything at once | One focused job per call |
| Debugging | Hard to see which part failed | Inspect each step's input and output |
| Testing | End-to-end only | Each step can be tested and improved separately |
| Checks between steps | None | Code can validate, filter or stop the chain |
| Latency and cost | Lowest | Higher: more calls, though each can use a cheaper model |
| Best for | Simple or tightly connected tasks | Multi-stage tasks with clear sub-steps |
The term goes back to research on "AI Chains" by Wu and colleagues, published in 2021. In a 20-person user study, chaining LLM steps improved the quality of results and made the system more transparent and controllable.
How Prompt Chaining Works
Here is how prompt chaining works, in four parts:
- Decompose the task. List the stages a skilled person would go through: understand, extract, analyse, write, check.
- Write one prompt per stage. Each prompt gets only the context it needs and a clear output format.
- Pass outputs forward. Your code takes the output of step one, puts it into the prompt for step two, and so on. Structured outputs such as JSON make this reliable.
- Add gates. Between steps, your code can check the output: is the JSON valid, is a required field present, is the classification one of the allowed labels? If not, it retries, takes another branch or stops.
Anthropic's guide to building effective agents describes prompt chaining in just these terms. Each LLM call processes the output of the previous one, programmatic checks ("gates") can be added on intermediate steps, and the pattern suits tasks that can be cleanly split into fixed subtasks, trading latency for higher accuracy by making each call an easier task.
What Is Prompt Chaining? An Example
The standard answer to "what is prompt chaining example" questions is a support inbox. A company wants to answer incoming support emails with a draft reply for a human agent to review.
As one prompt: "Read this email, figure out what the customer wants, look at their order data, decide if a refund is allowed under our policy, and write a polite reply." This often works, but when it fails you can't tell whether it misread the email, misapplied the policy or just wrote badly.
As a chain:
- Classify: "Which category is this email: refund, delivery, technical, account, other? Return JSON." A gate checks the label is valid; "other" goes straight to a human.
- Extract: "Extract order number, product, problem and the customer's request as JSON." A gate checks the order number exists in the database.
- Decide: "Given this policy text and these order facts, is a refund allowed? Answer yes, no or needs review, with the policy clause." Code adds the real order data, not the model.
- Draft: "Write a reply in our tone using these facts and this decision. Don't promise anything not in the decision."
- Check: "Does this draft contradict the decision or include any information not provided? Answer pass or fail with reasons." Failures go to a human.
Each step is simple, has a clear correct answer and can be tested with examples.
A Minimal Prompt Chain in Python
The pattern doesn't need a framework. Here's the skeleton, with call_llm standing in for your provider's SDK call:
import json
def call_llm(prompt: str) -> str:
... # call your model provider here and return the text response
def classify(email: str) -> str:
out = call_llm(
"Classify this support email as one of: refund, delivery, technical, account, other. "
'Reply only with JSON like {"category": "refund"}.\n\n' + email
)
category = json.loads(out)["category"]
if category not in {"refund", "delivery", "technical", "account", "other"}:
raise ValueError("invalid category") # gate
return category
def extract(email: str) -> dict:
out = call_llm(
"Extract order_number, product and request from this email. "
"Reply only with JSON.\n\n" + email
)
return json.loads(out)
def draft_reply(facts: dict, decision: str) -> str:
return call_llm(
"Write a short, friendly support reply using only these facts and this decision.\n"
f"Facts: {json.dumps(facts)}\nDecision: {decision}"
)
def handle(email: str) -> str | None:
if classify(email) == "other":
return None # route to a human
facts = extract(email)
decision = "needs review" # your business rules decide here
return draft_reply(facts, decision)Frameworks such as LangChain and LangGraph offer building blocks for the same idea, plus tracing and retries. Start with plain code until you need them.
Common Prompt Chaining Patterns
| Pattern | How it works | Example |
|---|---|---|
| Sequential | Fixed order, A then B then C | Extract, analyse, write |
| Conditional (branching) | Code or a classifier picks the next step | Route refunds and technical issues to different prompts |
| Map then reduce | Run the same prompt on many pieces in parallel, then combine | Summarise each chapter, then summarise the summaries |
| Generate, critique, revise | One step drafts, another reviews against criteria, a third revises | Marketing copy checked against brand rules |
| Gated | A check after a step decides whether to continue | Stop if extracted data fails validation |
| Human in the loop | A person approves before the chain continues | Legal or financial outputs |
Prompt Chaining vs Chain of Thought
Prompt chaining vs chain of thought is the most common confusion, because both break problems into steps. The difference is where the steps happen:
| Chain of thought | Prompt chaining | |
|---|---|---|
| Steps happen | Inside one model response | Across several model calls |
| Who controls the steps | The model | Your code |
| Can you check between steps? | No | Yes |
| Different instructions or models per step? | No | Yes |
| Cost | One call, longer output | Several calls |
| Best for | Reasoning within one problem (maths, logic) | Pipelines with distinct stages and formats |
They combine well: a step in a chain can ask the model to reason step by step before giving its answer, and reasoning models do that internally. Our guide to chain of thought prompting covers the in-prompt technique in depth.
Prompt Chaining vs Agents
Prompt chaining vs agents is about who decides the path. In a prompt chain, you define the steps in code: the order is fixed or branches on simple rules. In an agent, the model decides what to do next: which tool to call, whether to search again, when it's done.
Anthropic's guidance calls chains, routing and similar fixed patterns workflows, and recommends starting with the simplest pattern that works. Move to agents only when the task genuinely needs open-ended, model-directed steps. Chains are more predictable, cheaper and easier to test; agents handle situations you can't map out in advance. Many production systems are mostly chains with an agent-like step in the middle. For building the autonomous kind, see how to build an AI agent.
When to Use Prompt Chaining
Good fits:
- The task has clear stages that need different instructions or output formats.
- One step's output must be validated before the next acts on it.
- Parts of the task suit a cheaper or faster model (classification) while others need a stronger one (writing).
- You need to show your work: logs of each step for audit or debugging.
- A single prompt works most of the time but fails in ways you can't diagnose.
Poor fits:
- Simple tasks a single prompt already does reliably.
- Latency-critical chat replies where several sequential calls would feel slow.
- Tasks whose steps depend heavily on each other's full context, where splitting loses information.
Cost and Latency: A Quick Comparison
Say one large prompt takes 6 seconds and costs 1 unit. A four-step chain where each step is smaller might take 2 seconds per step, 8 seconds in total, and cost 1.5 units in total. Using a small model for the classification and checking steps, it might cost 0.8 units.
The chain is slower in this example but can be cheaper, and it's usually more reliable. You can also run independent steps in parallel (the map pattern) to cut total time. Measure both on your own workload; the trade-off varies a lot.
Tips for Better Chains
- Use structured outputs (JSON with a defined schema) between steps, and validate them in code.
- Pass only what each step needs. Smaller, focused context reduces confusion and cost.
- Put facts in from code, not from the model. Look up order data, prices and policies yourself and insert them; don't ask the model to remember them.
- Log every step's input and output. This is your main debugging tool.
- Evaluate per step. Build small test sets for each prompt, and an end-to-end test for the whole chain. Our guide to LLM evaluation covers building test sets.
- Handle failures explicitly: retries with a limit, fallbacks, and a route to a human.
Common Mistakes
- Chaining for its own sake. If one prompt works reliably, extra steps only add latency and cost.
- Free-text hand-offs. Passing unstructured prose between steps makes parsing fragile. Ask for JSON.
- Losing important context. A later step may need a detail from the original input that an earlier step dropped. Pass the original alongside step outputs where needed.
- No gates. Without checks, an early mistake flows through every later step and comes out as a confident, wrong final answer.
- Too many steps. Each step adds a chance of error. Merge steps that don't need separate checks.
FAQ
Is prompt chaining the same as a pipeline?
Essentially yes. A prompt chain is a pipeline where some or all stages are language model calls, connected by code that passes outputs forward and checks them.
Do I need LangChain for prompt chaining?
No. A few functions in any programming language are enough. Frameworks help with tracing, retries and complex graphs, but they're optional.
Can prompt chaining reduce hallucinations?
It can reduce them by keeping each step narrow, supplying facts from code and adding checks. It doesn't eliminate them; each step still needs validation.
Can I chain prompts in ChatGPT or Claude without code?
Yes, manually: run one prompt, then paste its output into the next. That's useful for prototyping a chain before automating it.
How many steps should a prompt chain have?
As few as possible. Most useful chains have two to five steps. Add a step only when it makes the task clearly easier or lets you check something important.