Skip to content

What is prompt chaining?

Mykhailo Poliarush

Definition

Prompt chaining is a technique that splits one LLM task into a fixed sequence of prompts, where each call takes the previous call's output as its input. Code between the steps checks each intermediate result before the next prompt runs. A chain costs extra calls and latency but gives steps you can test and debug separately.

How does prompt chaining work?

You split one job into steps that always run in the same order, and write a separate prompt for each. Your code sits between the steps.

  1. Decompose. List the subtasks, and write down what each must hand to the next (a JSON list, an outline, a short summary).
  2. Prompt each step. Each call does one thing and gets only the input it needs.
  3. Check between steps. Code validates the output before the next call: does it parse, does it match a schema, did it keep every item.
  4. Decide on failure. Retry the step, stop the chain, or pass the case to a person.
  5. Log every intermediate output. That log is what makes a chain easier to debug than one long prompt.

Anthropic's Building effective agents (December 2024, an older source; Anthropic has since added a note that much of the tooling landscape it describes has changed) describes the trade in one line: the goal is "to trade off latency for higher accuracy, by making each LLM call an easier task." Its examples are writing marketing copy and then translating it, or drafting an outline, checking it against criteria, then writing the document. LangGraph's documentation draws the same boundary: chaining suits "well-defined tasks that can be broken down into smaller, verifiable steps" (LangGraph, workflows and agents).

Where does the idea come from?

The idea was named and studied in a research paper: AI Chains by Tongshuang Wu, Michael Terry and Carrie J. Cai (first posted October 2021, revised March 2022, so an old source but the original one). The authors chained LLM steps "where the output of one step becomes the input for the next" and built a tool that let people edit the steps and their intermediate results.

In their 20-person user study, chaining improved the quality of results and made the system feel more transparent and controllable. One finding still matters for engineers: participants debugged unexpected outputs by "unit-testing" single parts of a chain. That is the main practical reason to chain today.

Prompt chaining vs a single prompt vs an agent

Single promptPrompt chainAgent
Who sets the stepsThe model, inside one answerYour code, before the runThe model, during the run
Model callsOneA fixed numberVaries per run
Where you can checkOnly the final outputAfter every stepAfter tool calls, if the harness does it
Latency and costLowestGrows with the number of stepsHardest to predict
Best fitTasks a model does well in one passTasks with stable subtasksTasks whose path depends on what the agent finds

A chain is the simplest pattern in an agentic workflow, which also covers routing, parallel calls and evaluator loops. When the next step depends on what a tool returns, you need an agent instead, such as a ReAct agent.

Example: release notes in three chained prompts

The chain extracts changes as JSON, writes notes from that JSON, then asks a reviewer prompt to confirm the result. The stub model returns invalid JSON on the first try, so you can see the first check reject it.

// chain.ts: three prompts in a fixed order, with a code check between each step.
// llm() is a stub that replays answers, so the chain runs without an API key.
const replies = [
  "Sure! Here are the changes: ...",                                    // step 1, attempt 1: not JSON
  '[{"type":"fix","text":"Totals no longer subtract tax twice"},' +
    '{"type":"feature","text":"CSV export for invoices"}]',             // step 1, attempt 2
  "- Fixed: totals no longer subtract tax twice.\n- New: export invoices as CSV.", // step 2
  "PASS",                                                               // step 3
];
let call = 0;
const llm = async (_prompt: string) => replies[call++];

type Change = { type: "fix" | "feature"; text: string };

function parseChanges(out: string): Change[] | null { // gate after step 1
  try {
    const list = JSON.parse(out);
    return Array.isArray(list) && list.every((c) => ["fix", "feature"].includes(c.type)) ? list : null;
  } catch {
    return null;
  }
}

async function releaseNotes(commits: string): Promise<string> {
  let changes: Change[] | null = null;
  for (let attempt = 1; attempt <= 2 && !changes; attempt++) {
    const out = await llm(`Extract user-facing changes from these commits as JSON: ${commits}`);
    changes = parseChanges(out);
    console.log(`step 1, attempt ${attempt}: ${changes ? "valid JSON" : "rejected"}`);
  }
  if (!changes) throw new Error("step 1 failed twice; stop the chain");

  const notes = await llm(`Write release notes, one bullet per change: ${JSON.stringify(changes)}`);
  const bullets = notes.split("\n").filter((l) => l.startsWith("- ")).length;
  console.log(`step 2: ${bullets} bullets for ${changes.length} changes`);  // gate after step 2
  if (bullets !== changes.length) throw new Error("step 2 dropped or invented a change");

  const review = await llm(`Answer PASS or FAIL: do these notes match the changes? ${notes}`);
  console.log(`step 3: review says ${review}`);
  if (review !== "PASS") throw new Error("step 3 review failed");
  return notes;
}

console.log(await releaseNotes("fix tax calc; add csv export; bump deps"));

We ran it with bun run chain.ts (Bun 1.2). Output:

step 1, attempt 1: rejected
step 1, attempt 2: valid JSON
step 2: 2 bullets for 2 changes
step 3: review says PASS
- Fixed: totals no longer subtract tax twice.
- New: export invoices as CSV.

Notice that the dependency bump never reached the notes. Step 1 dropped it as not user-facing, and the step 2 check only counts against step 1's list. A chain is only as complete as its first step, so test that step hardest.

Do reasoning models still need prompt chaining?

Less often. Anthropic's current prompting best practices say that with adaptive thinking and subagent orchestration, Claude "handles most multistep reasoning internally." The same page keeps chaining for two cases: when you need to inspect intermediate outputs, and when you must enforce a specific pipeline structure. It names self-correction as the most common pattern: draft, review against criteria, refine, each as a separate call you can log, evaluate or branch.

So the reason to chain has shifted. It used to be about making each step easy enough for the model. Now it is mostly about control: a place to validate, log, branch or hand off.

When should you not chain prompts?

  • The task fits one call. Each extra step adds latency and another output to monitor.
  • The steps depend on what you find. A fixed chain cannot change course; use an agent.
  • Errors carry forward unchecked. A chain without checks between steps passes the first mistake to every later step.
  • Steps need the full original input. If step 3 needs details that step 1 summarized away, merge the steps or pass the source along.

What should you check before putting a chain in production?

  1. A test set per step, not only for the final output. Our post on LLM evaluation covers how to grade outputs and keep graders honest.
  2. Structured handoffs. JSON with a schema between steps, validated in code.
  3. A retry cap and a stop. Every step has a limit and a clear failure message.
  4. Versioned prompts. Each step's prompt and model are versioned together, because a change in one step changes the input of the next.

SDCLabs builds multi-step LLM pipelines as part of generative AI development, with automated evals on every prompt change and senior engineers deciding what ships.

Sources

  1. AI Chains: Transparent and Controllable Human-AI Interaction by Chaining Large Language Model Prompts, Tongshuang Wu, Michael Terry and Carrie J. Cai (arXiv), 2022-03-17
  2. Building effective agents, Anthropic, 2024-12-19
  3. Prompting best practices, Anthropic, 2026-11
  4. Workflows and agents, LangChain, 2026-11-12

Frequently asked questions

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

Chain-of-thought asks one model call to reason step by step inside a single answer. Prompt chaining makes several calls, and your code sees and checks the output of each one before the next starts.

Is prompt chaining the same as an AI agent?

No. In a chain your code fixes the steps before the run. An agent decides its own next step from what its tools return, so its path can differ on every run.

Do you need a framework for prompt chaining?

No. A chain is a few function calls with checks between them, as the example on this page shows. Frameworks such as LangGraph model each step as a node in a graph, which helps once a chain branches or grows.

How many steps should a prompt chain have?

As few as the task needs. Every step adds a model call and a place where output can drift, so split only where you want to check, log or branch.

Building with AI agents? Talk to an engineer.