Skip to content

Prompt chaining: when to split a prompt into steps

Prompt chaining splits one LLM task into steps that feed each other. When a chain beats one prompt, the four patterns, and how to pass data and test each step.

Published
Reading time
14 min read

In short

  • Prompt chaining splits one task into a fixed sequence of model calls, where each call works on the output of the one before it. Your code decides the steps, so the chain is a workflow, not an agent.
  • Split a prompt when you need to see, check, or branch on an intermediate result, or when one prompt keeps failing at a task that has clear stages. Current models handle most multistep reasoning in a single call, so a chain needs a reason.
  • Every sequential step adds a full round trip of latency and resends whatever context it needs. Errors compound: five steps that are each right 95% of the time, failing independently, produce a correct result about 77% of the time.
  • Pass data between steps as JSON validated against a schema, put a gate in code after any step whose output the next step trusts, and evaluate each step on the real outputs of the step before it.

Prompt chaining is a way to build an LLM feature as a fixed sequence of model calls, where each call takes the output of the previous one as its input. Instead of one prompt that classifies a support ticket, looks up the policy, and drafts a reply, a prompt chain makes three calls, and your code checks the result between them.

The split costs latency and tokens, and it adds places for errors to start. This article covers when the split pays for itself, the patterns a chain can take, how to pass data and test each step, and where a chain should become an agent loop.

What prompt chaining is

A prompt chain is a workflow in which the steps, their order, and the data passed between them are written in code before any request arrives. Anthropic's Building effective agents defines it in one sentence: "Prompt chaining decomposes a task into a sequence of steps, where each LLM call processes the output of the previous one."

The same guide separates workflows, which it describes as "systems where LLMs and tools are orchestrated through predefined code paths," from agents, in which the model directs its own process and tool use. A prompt chain sits on the workflow side. The model never picks the next step. Your code does.

The idea predates that guide. A 2021 paper by Tongshuang Wu, Michael Terry, and Carrie Cai, AI Chains, described "Chaining LLM steps together, where the output of one step becomes the input for the next." In its 20-person user study, chaining improved the quality of results and made the system easier to understand and control, and participants debugged chains by unit-testing individual steps. That last finding is still the main practical reason to chain.

Provider docs describe the same technique under different names. Google's prompt design strategies list three ways to break a prompt into components: one prompt per instruction, chained prompts for sequential steps, and parallel tasks over parts of the data whose results are aggregated.

When to split a prompt into steps

Split a prompt when you need to inspect, check, or branch on an intermediate result, or when a single prompt keeps failing at a task with distinct stages. Without one of those reasons, keep the single prompt.

Anthropic's prompting best practices say that with adaptive thinking and subagents, Claude handles most multistep reasoning internally, and that explicit chaining "is still useful when you need to inspect intermediate outputs or enforce a specific pipeline structure." The agents guide calls chaining ideal when a task "can be easily and cleanly decomposed into fixed subtasks."

Symptom with one promptDoes a chain helpCheaper fix to try first
The output skips an instruction when the prompt carries ten of themOften: give each stage its own promptReorder and tag the instructions, and add examples
You cannot tell which stage of the task went wrongYes: each step leaves a record you can readAsk for intermediate fields in one structured response
Bad input should stop the task before the expensive part runsYes: a gate between stepsA cheap classifier call before the main prompt, which is a two-step chain
Different inputs need different instructionsYes: a routing stepA conditional in code that picks the prompt
One stage needs a different model, tool, or temperatureYesNone: this needs separate calls
Parts of the task are independent and the call is slowYes: parallel stepsShorter output, or a faster model
The steps change from one input to the nextNoAn agent loop
Quality is fine and latency mattersNoLeave it as one call

A chain also needs steps that can be stated precisely. "Extract the order ID and the complaint type" is a step. "Think about the customer" is not, because nothing downstream can check it.

Prompt chain patterns

Four patterns cover most prompt chains: a sequence, a gate between steps, a routing step, and a parallel fan-out that merges. Production chains usually combine them.

INPUTSTEP 1 · ROUTEGATE · CODESTEP 2 · PARALLELSTEP 3 · MERGETicketRAW TEXTClassifyTYPE + ORDER IDValidateSCHEMA · IDOther typesOWN CHAINRejectedRETRY ONCE2a · PolicyRULES THAT APPLY2b · HistoryPAST ORDERSDraftONE REPLY
A support ticket chain that uses all four patterns. The first step classifies and extracts, a gate in code checks the result, two lookups run in parallel, and a final step merges them into a reply. Other ticket types route to their own chains, and a rejected result is retried once before the chain stops.
  • Sequential. Each step reads the previous step's output. Anthropic's examples are writing marketing copy and then translating it, and writing an outline, checking it against criteria, and then writing the document from it.
  • Gate. A check between steps decides whether the chain continues. Anthropic's guide notes that "You can add programmatic checks" on any intermediate step. A gate is code: a schema check, a count, a lookup. If it is a model call, it is another step with its own error rate.
  • Routing. A first step classifies the input, and code sends it to one of several follow-up chains. The agents guide's examples are sending customer service queries to different processes and sending easy questions to smaller models. The model-selection half of this is covered in LLM routing.
  • Parallel fan-out and merge. Independent steps run at the same time, and a final step or plain code combines them. Anthropic splits this into sectioning, "Breaking a task into independent subtasks run in parallel," and voting, "Running the same task multiple times to get diverse outputs."

A fifth shape, generate, review, refine, is the chain Anthropic's prompting docs call the most common: draft an answer, have the model review it against criteria, and revise from the review. Each step is a separate call, so you can log, evaluate, or branch at any point. When the review repeats until it passes, the agents guide calls that an evaluator-optimizer and puts it among its separate workflow patterns.

What a chain costs compared with one prompt

A prompt chain trades latency and input tokens for control. The agents guide states the trade directly: "The main goal is to trade off latency for higher accuracy, by making each LLM call an easier task."

Latency adds up along the longest path. Each sequential step is a full request with its own time to first token and its own generation time, and the next step cannot start until the previous output is complete, so streaming helps only the last step. A three-step chain is slower than one call of the same total length. Parallel steps cost the time of the slowest branch, not the sum.

Tokens add up wherever steps share context. If step 1 reads a 6,000-token document and step 3 needs the same document to check a quote, the document is billed twice. Pass each step only what it needs: the extracted fields instead of the document when the fields are enough, and the source text only to the step that must check against it.

Three changes reduce what a chain costs:

  • Put a cheaper, faster model on the steps that classify or extract, and keep the larger model for the step that writes.
  • Order each prompt so that shared material, such as a long policy document, comes first and step-specific instructions come after it. A prompt cache matches on an identical prefix, so steps that start the same can reuse it.
  • Stop early. A gate that rejects bad input after a cheap first step saves the cost of every step after it.

On Claude, changing the structured output format invalidates the prompt cache for that conversation thread, and the first request with a new schema waits while its grammar compiles. Compiled grammars are cached for 24 hours from last use. OpenAI's Structured Outputs guide also warns that the first request with any schema has additional latency. Keep each step's schema stable between deployments.

Error compounding across steps

Errors compound in a chain because each step treats the previous step's output as correct. If every step is right 95% of the time and the steps fail independently, a five-step chain is right about 77% of the time (0.95⁵ ≈ 0.774). At 99% per step, five steps give about 95%.

The independence assumption rarely holds exactly. A step can repair an upstream mistake, as a review step is meant to. More often a step makes it worse, because a wrong classification sends the ticket down the wrong route and every later step does careful work on the wrong problem. The arithmetic still sets the expectation: per-step accuracy that looks acceptable in isolation can produce an end-to-end rate that is not.

Gates change the math. Without one, a wrong extraction flows into the reply. With a gate that confirms the extracted order ID appears in the ticket, the same error becomes a retry or a stop, which you can count, alert on, and fix. Put gates after the steps whose errors are both likely and expensive downstream, usually classification and extraction.

What to do when a gate fails:

  1. Retry the step once, and include the gate's error message in the retry so the model can correct the specific problem.
  2. If the retry fails, stop the chain and return an explicit failure, or send the input to a person.
  3. Do not pass a failed result forward with a warning attached. The next step will treat it as input.

Passing structured data between steps

Pass data between steps as JSON that matches a schema you define, and validate it in code before the next step reads it. Free text between steps leaves each step parsing the previous one's prose, and a change in wording in step 1 becomes a failure in step 3.

Both major APIs can constrain output to a JSON Schema. Claude's structured outputs use constrained decoding through output_config.format, and OpenAI's Structured Outputs use text.format with type: "json_schema" and strict: true. OpenAI's guide draws the line with JSON mode: both produce valid JSON, but "only Structured Outputs ensure schema adherence."

A schema guarantee is narrower than it sounds, and the Claude docs list the cases where output can still break it:

  • A refusal returns 200 with stop_reason: "refusal", and the refusal message takes precedence over the schema.
  • A response cut off at max_tokens can be incomplete JSON.
  • String enum values are not guaranteed to match in capitalization, so compare them case-insensitively.
  • Constraints the API does not support, such as minimum on a number, are not enforced unless your own validator checks them.

The schema checks shape. Your code still has to check meaning: that an extracted ID exists in the source, that a date is in range, that a list is not empty. That second check is the gate.

triage-step.ts
import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
 
const client = new Anthropic();
const MODEL = process.env.TRIAGE_MODEL!; // a small, fast model is enough for this step
 
export class GateError extends Error {}
 
// What the next step is allowed to read. Enum casing is normalized before the check.
const Triage = z.object({
  type: z.string().transform((s) => s.toLowerCase()).pipe(z.enum(["refund", "shipping", "other"])),
  order_id: z.string().nullable(),
  summary: z.string().min(1),
});
export type Triage = z.infer<typeof Triage>;
 
const schema = {
  type: "object",
  properties: {
    type: { type: "string", enum: ["refund", "shipping", "other"] },
    order_id: { type: ["string", "null"] },
    summary: { type: "string" },
  },
  required: ["type", "order_id", "summary"],
  additionalProperties: false,
};
 
export async function triage(ticket: string): Promise<Triage> {
  const res = await client.messages.create({
    model: MODEL,
    max_tokens: 1024,
    system: "Classify the support ticket. Copy the order ID exactly as written, or return null.",
    messages: [{ role: "user", content: `<ticket>\n${ticket}\n</ticket>` }],
    output_config: { format: { type: "json_schema", schema } },
  });
 
  // A refusal or a truncated response can break the schema, so check before parsing.
  if (res.stop_reason !== "end_turn") throw new GateError(`triage stopped: ${res.stop_reason}`);
  const text = res.content.find((block) => block.type === "text")?.text ?? "";
  const out = Triage.parse(JSON.parse(text));
 
  // The gate: a check the schema cannot express.
  if (out.order_id && !ticket.includes(out.order_id)) {
    throw new GateError(`order_id ${out.order_id} does not appear in the ticket`);
  }
  return out;
}

The chain itself is then ordinary code: call triage, retry once on a GateError, route on type, run the policy and order-history lookups with Promise.all, and pass the validated fields to the drafting step.

Three more rules keep the data clean between steps:

  • Carry identifiers and source quotes forward, not paraphrases. A later step that must cite the ticket needs the ticket's words.
  • Keep the fields one step needs and drop the rest. A step that receives everything tends to use everything.
  • Where a step must read prose, such as a document to summarize, wrap it in tags like <ticket> or <document> so instructions and data stay separate. The Claude prompting docs recommend XML tags for the same reason.

When a step's output is an action, such as issuing a refund, make that step a tool call with a strict input schema instead of parsed text.

How to evaluate a prompt chain

Evaluate a prompt chain one step at a time and end to end, because the end-to-end score tells you the chain is wrong and only the step scores tell you where.

Build each step's test set from the real outputs of the step before it, taken from logged production runs. A test set for the drafting step written by hand will contain clean inputs that step 1 never produces. Record every step's input, output, model, latency, tokens, and gate result on every run, so that a bad final answer can be traced back to the step that caused it.

Step typeWhat to measureTypical grader
Classify or routeAccuracy per class, and the confusion between classesExact match against labels
ExtractField-level precision and recallExact or normalized match
GatePass rate, and how often a passed result was still wrongCounts from production, plus a labeled sample
GenerateTask quality against criteriaRubric with an LLM judge, calibrated on human labels
Whole chainTask success and cost per taskThe same rubric on the final output

Changing one step changes the inputs of every step after it. A prompt fix that raises extraction accuracy can shift the format the drafting step sees, so rerun the end-to-end suite after any step changes, not only that step's tests. The LLM evaluation article covers datasets, error bars, and release gates in detail.

The gate pass rate is the cheapest online signal a chain has. A drop in it after a model or prompt change shows up before users report bad answers.

Prompt chaining and other advanced prompt engineering techniques

Prompt chaining is often confused with chain-of-thought prompting, and it combines with most other advanced prompt engineering techniques rather than replacing them.

  • Chain-of-thought asks one model call to reason step by step before it answers. The technique comes from a 2022 paper by Jason Wei and colleagues. It happens inside a single call, and you cannot check or branch between its steps. Prompt chaining makes each step a separate call that code can inspect. A step in a chain can use chain-of-thought, or the model's built-in thinking, internally.
  • Self-consistency samples several reasoning paths for one question and takes the most common answer, as described in Wang and colleagues' 2022 paper. It is the voting form of a parallel chain.
  • Few-shot examples go inside each step's prompt. A narrow step needs fewer and simpler examples than one prompt covering the whole task.
  • Self-correction is the generate, review, refine chain described above.

Where prompt chains stop and agents begin

A prompt chain becomes an agent when the model, not your code, decides what the next step is. Keep the chain while you can write the steps down in advance, and switch when you cannot.

The OpenAI Agents SDK draws the same line between orchestrating with code and orchestrating with a model. Its multi-agent guide says that "orchestrating via code makes tasks more deterministic and predictable, in terms of speed, cost and performance," and lists chaining, classification with structured outputs, parallel runs, and evaluator loops as ways to do it.

Prompt chainOrchestrator-workersAgent loop
Who picks the next stepYour codeA model plans the subtasks, code runs themThe model, after each tool result
Number of callsFixed, or one of a few fixed routesDepends on the planVaries per run
Cost per taskPredictableVaries with the planA distribution with a long tail
Where errors show upAt a gate between stepsIn the plan or in a worker's resultAnywhere in the run
How to test itPer-step tests plus end to endPlan quality plus worker testsEvaluations over whole runs

Anthropic's guide describes orchestrator-workers as the case where "subtasks aren't pre-defined, but determined by the orchestrator based on the specific input." That is usually the next step after a chain, when the number of lookups or files depends on the input. The full agent loop, with its stop conditions and budgets, is covered in the agent loop article, and splitting work across several agents in multi-agent systems.

The common mistake runs the other way: building an agent for a task whose steps never change. A support flow that always classifies, looks up, and drafts is a chain. Giving the model control of that order adds cost and variance and buys nothing.

Frequently asked questions

What is prompt chaining?

Prompt chaining is a technique for building an LLM task as a fixed sequence of model calls, where each call takes the previous call's output as input. Code between the calls can validate results, choose a route, or run steps in parallel. It is a workflow pattern, because the steps are defined in code before the task runs.

What is a prompt chain in AI?

A prompt chain in AI is the sequence of prompts that implements a prompt-chaining workflow, along with the code that connects them. A typical chain classifies or extracts in a first step, checks the result, and generates a final answer in a later step.

What is the difference between prompt chaining and chain-of-thought?

Chain-of-thought asks a single model call to reason through steps before answering, so all the steps happen inside one response. Prompt chaining splits the task into separate calls, so code can inspect, validate, or branch on each intermediate result. The two combine: any step in a chain can reason step by step internally.

When should you not use prompt chaining?

Skip prompt chaining when one prompt already meets your quality bar, when latency matters more than the gain from splitting, or when the steps change from input to input. Each sequential step adds a full round trip, and a task whose steps depend on what the model finds needs an agent loop instead.

How do you pass data between steps in a prompt chain?

Have each step return JSON that matches a schema, using the provider's structured output feature, and validate it in code before the next step reads it. Check for refusals and truncated responses, which can break the schema, and add checks the schema cannot express, such as whether an extracted ID appears in the source.

Is a prompt chain an agent?

No. In a prompt chain your code decides every step. In an agent the model decides the next step after reading each result, and the number of steps varies. Many systems described as agents run the same steps on every input and work better as chains.

Sources

  1. 01Building effective agentsAnthropic
  2. 02Prompting best practices: chain complex promptsClaude API docs
  3. 03Structured outputsClaude API docs
  4. 04Structured OutputsOpenAI API docs
  5. 05Prompt design strategiesGoogle AI Studio docs
  6. 06Orchestrating multiple agentsOpenAI Agents SDK
  7. 07AI Chains: Transparent and Controllable Human-AI Interaction by Chaining Large Language Model PromptsarXiv
  8. 08Chain-of-Thought Prompting Elicits Reasoning in Large Language ModelsarXiv
  9. 09Self-Consistency Improves Chain of Thought Reasoning in Language ModelsarXiv