Prompt chaining runs a task as an ordered series of LLM calls, where each call completes one defined step and feeds its output to the next. Application code can validate intermediate results before the chain continues, helping developers identify errors and prevent incorrect outputs from affecting subsequent steps.
Chaining works best when a task divides into distinct stages, but additional calls increase latency, token costs, and opportunities for errors to propagate. Comparing the full chain against a single-prompt baseline on the same dataset shows whether the output-quality gain justifies the added cost and complexity.
In Braintrust, developers trace individual calls and validation steps, evaluate complete chains and individual components, and compare experiments to confirm that changes improve the final output. Start free with Braintrust to test prompt chains against representative inputs.
What is prompt chaining?
Prompt chaining breaks a task into a predefined sequence of LLM calls, with each call performing a specific operation and passing its output to the next. AWS Prescriptive Guidance describes each step as a discrete LLM invocation, while Anthropic's guide to building effective agents explains how programmatic checks can validate intermediate results before the chain continues.
A prompt chain has three main components: the original input, such as a user request or source document; intermediate outputs, such as extracted facts, classification labels, or outlines that subsequent steps use; and the final output, which is delivered to the user or a downstream application.
For example, a customer support application receives an email describing an order problem. The first LLM call extracts the order number, product, and issue description into structured fields. The second classifies the issue as billing, shipping, or a product defect, while the third drafts a reply using the extracted information and relevant support policy. Validation checks confirm the required fields are present and that the draft includes the correct order number without promising refunds outside the policy.

How prompt chaining works
A prompt chain's execution depends on how information moves between LLM calls, whether the sequence follows a fixed path or branches based on intermediate results, and how the application coordinates those calls.
Passing outputs between LLM calls
Each handoff passes the previous call's output into the next prompt, either as text or structured data. Text handoffs suit tasks that process an entire response, such as revising a draft, while structured outputs provide named fields that subsequent prompts or application code can reference directly.
Each step should receive the context necessary to complete its assigned task. In the support example, the drafting step needs the extracted order details and relevant policy, but may not need the entire customer email. For tasks where missing information could affect accuracy, passing the original request alongside the intermediate output lets subsequent steps check whether important details were omitted.
Linear and branching prompt chains
Linear chains execute the same sequence for every request. A document generation chain might produce an outline, check it against predefined requirements, and generate the full document using the approved outline.
Branching chains use intermediate results to select among predefined execution paths. In the customer support example, the classification step could direct billing questions to a billing-specific prompt and product defects to a separate troubleshooting prompt.
Classification-based branching determines which step executes next, while model routing selects the LLM best suited to a request, as explained in Braintrust's model routing guide. Both linear and branching chains follow paths defined by developers, even when intermediate results determine which path executes.
Prompt chaining in code and in chat tools
Production prompt chains typically run in application code or orchestration services, which execute validation, logging, and conditional logic between LLM calls and check each intermediate output before the next step runs.
Chat tools can also queue prompts so each new prompt runs automatically after the previous response finishes. Some support assigning different models and configurations to individual steps, making it possible to experiment with connected prompts without implementing the execution logic in code.
Applications that execute prompt chains for users need additional controls for handling invalid intermediate outputs, failed calls, and execution records. These controls determine how the application recovers from failures and whether developers can investigate problems after a run.
When to use prompt chaining
Prompt chaining is most useful when a task has distinct stages that benefit from focused instructions or intermediate validation. For straightforward requests, a single LLM call may achieve the same quality with less latency, cost, and maintenance.
Tasks that benefit from prompt chaining
Stages that need different instructions: Extracting structured information and generating prose require different output formats and success criteria. Separate prompts keep instructions focused and let developers choose the model and settings best suited to each stage.
Work that needs auditable intermediate results: Tasks involving fact extraction, classification, or structured planning benefit from outputs that reviewers can inspect independently. Recording intermediate results makes it easier to determine which step influenced the final answer and investigate errors.
Checks that must run between stages: Schema validation, policy enforcement, and database lookups may need to happen before subsequent processing begins. Prompt chaining creates explicit points where application code can verify intermediate results and prevent invalid information from reaching later steps.
Tasks too large for one call: Long documents and complex tasks may exceed a model's context window or its ability to complete all required operations reliably in one request. Dividing the work into manageable stages lets each call focus on a defined portion while retaining the context necessary for accurate results.
Multi-stage generation pipelines: Code generation workflows may involve planning an implementation, writing code, running tests, and explaining the results. Separating these operations lets each stage use the previous output and incorporate validation results before continuing.
When a single prompt is enough
Short, self-contained tasks: Simple questions, transformations, and other requests that a model already handles accurately in one call rarely benefit from additional stages. Chaining increases processing time and token usage without a corresponding improvement in output quality.
Tightly coupled reasoning: Some tasks require the model to consider several pieces of information together, such as identifying conflicts between contract clauses. Separating the analysis across multiple calls can remove relationships or context necessary for an accurate conclusion.
Latency-sensitive features: Sequential LLM calls accumulate processing time because each stage waits for its predecessor to finish. Interactive applications with strict response-time requirements may be better served by a single call.
A single prompt that already passes evaluations: When a single-prompt implementation meets established quality requirements on a representative evaluation dataset, additional stages have no demonstrated benefit. Introduce chaining when evaluation results identify specific failures that dividing the task can address.
Prompt chaining vs. chain-of-thought prompting vs. AI agents
Prompt chaining, chain-of-thought prompting, and AI agents can all handle multi-step tasks. The main differences are how those steps are executed, who controls their sequence, and which intermediate results an application can inspect.
Prompt chaining vs. chain-of-thought prompting
Chain-of-thought prompting asks an LLM to produce intermediate reasoning within a single model call. Any reasoning the model exposes becomes available only after the call finishes, leaving no opportunity for application code to validate individual steps during generation. Reasoning models add a further limitation: providers generally return a summary of the model's internal reasoning rather than the raw chain of thought, so the trace available for inspection is not necessarily the computation that produced the answer.
Because prompt chaining produces each intermediate output as a separate call result, application code can validate it before execution continues. The two techniques can also be combined when an individual step in a prompt chain requires additional reasoning.
Prompt chaining vs. agent workflows
AI agents select actions and tools dynamically based on the task's current state, while prompt chains follow developer-defined execution paths. Agents are better suited to open-ended tasks where the required steps cannot be determined in advance.
Braintrust's prompt-chaining cookbook shows how both patterns can work together. Its travel-planning agent selects actions at runtime, while application code validates proposed actions before execution.
The following table summarizes how each approach handles execution and intermediate results.
| Approach | Who decides the steps | LLM calls per task | Intermediate outputs available for inspection | Best fit |
|---|---|---|---|---|
| Single prompt | No separate execution stages | One | No separate step outputs | Short, self-contained tasks |
| Chain-of-thought prompting | Model, within one call | One | Any exposed rationale, after the call completes | Reasoning-intensive tasks handled in one call |
| Prompt chain | Developer defines the steps and possible branches | One per executed LLM step | Each step's output before subsequent processing | Tasks with defined stages and dependencies |
| AI agent | Model selects actions within application constraints | Variable | Recorded actions, intermediate results, and tool outputs | Open-ended tasks with unpredictable execution paths |
Intermediate outputs and validation gates
The reliability of a prompt chain depends on the accuracy and structure of the information passed between steps. Output contracts establish what each step must return, while validation gates check whether the result meets the requirements for subsequent processing.
Output contracts between steps
An output contract defines the fields, data types, allowed values, and format that an LLM call must return. Structured formats such as JSON allow application code to parse intermediate results and verify that downstream steps receive the expected information.
In the customer support example, the extraction step might return an order number, product name, and issue summary, while the classification step must select a label from a predefined list. A missing order number or unsupported classification can then be identified before the drafting step uses the result.
In a Braintrust travel-planning example, a Pydantic schema restricts model responses to four permitted actions: GET_WEATHER, GET_FLIGHTS, GENERATE_ITINERARY, or DONE. Each action also has defined parameters, allowing the application to validate responses before execution.
Validation gates between steps
Validation gates check whether an intermediate result satisfies the conditions required to continue processing. Depending on the task, applications can use three types of checks:
Programmatic checks: Code verifies that outputs match the expected schema, required fields are present, values belong to allowed sets, and content meets defined limits. Deterministic checks are appropriate when explicit rules can establish correctness.
Lookups against a source of truth: Application code verifies generated or extracted information against authoritative records. For example, a support chain can confirm that an order number exists in the database before using it to generate a customer response.
LLM judge steps: A separate model call evaluates requirements that are difficult to express through fixed rules. For example, a judge can check whether a proposed action is appropriate given the information already collected, flagging an unnecessary weather lookup when the required data is already available.
Every validation gate also needs a defined failure response. Depending on the error, the application may retry the failed step, request a corrected output, route the result for human review, or stop execution. Recording failed checks helps developers identify recurring validation problems and determine which steps require improvement.
Error propagation in prompt chains
An error in an early prompt-chain step can affect every subsequent result. For example, if the extraction step identifies the wrong order number, the classification and drafting steps may process that incorrect information without recognizing the mistake. The final response can appear accurate and complete while referring to the wrong customer order.
Tracing the error to its source can be difficult when the problem only becomes visible in the final response. When evaluating individual steps, developers need to examine the actual outputs received from preceding steps, since an apparent failure in one component may originate earlier in the chain.
Three practices help limit error propagation and identify its cause:
Prioritize checks at high-risk handoffs: Apply stricter checks after steps that produce information critical to downstream decisions, such as extracted customer details, financial values, or policy classifications. Catching an incorrect value early prevents subsequent steps from incorporating it into their outputs.
Preserve original inputs where necessary: Pass the original request or relevant source information to later steps that need to verify earlier results. For example, a drafting step can compare extracted order details against the customer email to identify missing or inconsistent information. Limit additional context to the steps that need it to avoid unnecessary token costs.
Record inputs and outputs for every step: Capture what each step received and returned so developers can identify the first point where results diverged from expected behavior. The same handoff testing principles apply to multi-agent systems, where incomplete or incorrect information can affect several downstream components.
How prompt chaining affects quality, latency, and cost
Adding steps to a prompt chain can improve task accuracy, but each additional LLM call also affects response time, token usage, and maintenance. Whether chaining is worthwhile depends on whether the final output improves enough to absorb those costs.
Quality: Focused prompts give each model call a more specific task, while intermediate checks help identify errors before later steps use the results. However, missing context at handoffs or incorrect intermediate outputs can reduce final-answer quality, even when individual steps perform well.
Latency: Sequential chains accumulate the execution time of every LLM call and the checks between them. A four-step chain waits for four model responses in order, which can make the overall response significantly slower than a single call.
Cost: Every call incurs input and output token charges, including the instructions and context passed between steps. Assigning smaller, less expensive models to straightforward tasks such as classification can reduce costs, provided step-level evaluations confirm that output quality remains acceptable.
Maintenance: Each additional step introduces a prompt to version, an output contract to maintain, and dependencies to test. Changes to one step's output format can break subsequent steps, requiring coordinated updates and regression testing.
Compare the complete chain against a single-prompt baseline using the same representative dataset. Measure final-output quality, end-to-end latency, and cost per run, then keep the chain when its measured quality improvements justify the added processing and maintenance.
Evaluating prompt chains end to end and step by step
Evaluating a prompt chain requires checking both the completed task and the individual steps that produce it. End-to-end evaluations measure whether the chain meets its quality requirements, while step-level tests help locate failures and verify changes to individual components.
End-to-end evaluation: Run representative inputs through the complete chain and score the final outputs against defined success criteria. The resulting scores set the baseline that every later change to the chain is measured against, whether the change touches one step or the whole sequence.
Tracing: Record each step's inputs and outputs within the complete execution trace. When an evaluation fails, developers can inspect the sequence to identify where information was lost, incorrectly transformed, or passed forward.
Step-level evaluation: Build a focused dataset from the actual inputs a particular step received, including relevant upstream outputs, and compare its results against expected values where available. The same single-step testing methods used for AI agents apply to prompt chains, letting developers isolate failures and test changes without repeatedly running the entire workflow.
Confirmation run: After a modified step passes its individual evaluation, rerun the full chain against the end-to-end dataset. An improved extraction step, for example, may change the output structure in a way the drafting step cannot handle correctly. Testing the complete chain confirms whether the modification improves the final result without introducing regressions.
Tracing and evaluating prompt chains with Braintrust
Braintrust connects execution traces, component-level evaluations, and end-to-end experiments, allowing developers to identify failures, measure changes, and enforce quality requirements before releasing an updated chain.
Trace every step of the chain
Braintrust records a complete chain execution as a trace, with model calls, application functions, validation checks, and tool operations represented as nested spans. Each span captures its inputs, outputs, metadata, and timing information, while LLM spans also record model usage, token counts, and cost.

Auto-instrumentation captures calls to supported AI providers, while manual application spans cover operations such as validation, database lookups, and branching logic. Custom metadata on each span records the chain step, prompt version, or validation outcome.
For a customer support chain, the extraction, classification, validation, and drafting operations appear within the same execution. Developers can examine traces to locate the first incorrect result and filter production logs by step metadata, errors, or other recorded fields to investigate recurring failures.
Evaluate the complete chain
A Braintrust evaluation runs the entire chain against a dataset of representative inputs. Scorers assess the final output against defined success criteria, and each run is saved as an experiment containing test cases, scores, metadata, and execution traces.
In a travel-planning chain evaluated end to end, an LLM-as-a-judge scorer checks whether the generated itinerary satisfies the traveler's preferences. Developers can inspect the complete execution when an itinerary receives a low score, including the intermediate decisions that contributed to the result.
Experiment comparison measures changes against a selected baseline, exposing both aggregate score differences and individual test-case regressions. Sorting by regressions and examining output differences helps identify failures that an improved overall score might otherwise conceal.
Evaluate one chain step in isolation
When an experiment identifies an unreliable component, Braintrust can evaluate that component separately. The travel-planning example uses a judge-only dataset containing proposed actions, relevant context, and expected Y or N decisions. The Autoevals ExactMatch scorer checks the judge's decisions without executing the complete travel-planning process.
Production evidence can strengthen component-level evaluation. Developers can promote production traces into datasets individually, while dataset pipelines transform production spans or traces into dataset rows in bulk. A pipeline is defined in code with DatasetPipeline(...) and run through the bt datasets pipeline CLI command, so the selection and transformation logic stays version controlled. The resulting cases preserve the inputs a component encountered during actual application execution.
With Braintrust Loop, product, support, and engineering teams investigate recurring failures in natural language and generate evaluation cases from production patterns, which cuts the engineering work needed to build and maintain relevant test coverage.

Once the modified component beats its previous experiment, developers rerun the full-chain experiment to confirm that the end-to-end scores held.
Enforce quality requirements before release
Braintrust runs experiments in CI/CD so changes to prompts, models, and chain logic are evaluated before merging. The GitHub Action runs evaluations on pull requests and posts a results summary as a PR comment. Custom reporters define minimum scores, acceptable regression limits, and critical cases that must pass.
Posting results does not block a merge on its own. By default, bt eval returns a non-zero exit code only when an eval throws an exception, so a reporter has to return a failing status when evaluation results violate the defined requirements. Configuring the CI job as a required repository check then prevents merges that fail the release criteria. Using the same evaluation datasets and baseline comparisons across pull requests helps keep release decisions consistent as individual chain components change.
Score spans and traces in experiments and production
Braintrust scores individual spans or complete traces, depending on the behavior under evaluation. A span scorer can verify whether a classification step returns an allowed label, while a trace scorer can check whether the final response matches the information extracted earlier in the chain.
These quality checks extend to live applications through online scoring. Scoring automation rules specify which scorers run, whether they evaluate individual spans or complete traces, and which requests qualify through filters and sampling rates. Evaluations execute asynchronously without adding latency to application requests. Autoevals scorers evaluate individual spans, so a rule that runs one needs its scope set to Span.
Braintrust dashboards display quality scores alongside latency, usage, and cost, so developers can track whether a change improved the final output without raising latency or spend. Alerts can notify responsible teams through Slack, PagerDuty, or webhooks when production traces meet configured failure conditions.

Reviewed production failures can become regression cases, ensuring that newly observed errors are included in subsequent evaluations before additional chain changes reach production.
Prototype chains with playground workflows
Braintrust playground workflows connect multiple prompts so each step receives the previous output through template variables. Developers can select saved prompt versions, connect them into a sequence, and evaluate the complete workflow against a shared dataset without implementing the chain in application code. Later prompts reference the previous node's output as {{input}}, with dot notation for structured fields, while {{dataset}} keeps the original dataset values available at any node.
Workflows are in public preview. They run only in playgrounds and are limited to prompt chaining, so a production chain still needs its execution logic in application code or an orchestration service.
Diff mode places chain variants side by side and marks differences in output, score, execution time, and token usage. Once a configuration meets the required criteria, developers can save the playground run as an experiment, preserving an immutable result for later comparisons.

For implementations involving custom application logic, remote evaluations connect code-based tasks to Braintrust playgrounds and experiments.
Trace prompt chains, evaluate changes, and enforce quality requirements before production. Start free with Braintrust.
FAQs about prompt chaining (2026)
What is an example of prompt chaining?
A document-generation chain might use one LLM call to draft an outline, a programmatic check to confirm the outline covers every required section, and a second call to write the full document from the approved outline. Each stage produces something the next depends on, and the check between them stops a missing section from reaching the final draft.
How many steps should a prompt chain have?
There is no ideal number of steps. Each call should serve a distinct purpose and contribute to the quality of the final output. Combining stages that perform reliably together can reduce latency, token usage, and maintenance without sacrificing accuracy.
Can each step in a prompt chain use a different model?
Each LLM call can use its own model, parameters, and instructions. For example, a smaller model may handle classification while a more capable model handles complex generation, and a step that must return a strict schema can run at a lower temperature or a narrower top-p than a drafting step where more varied wording is acceptable. Braintrust Gateway provides a unified API for accessing models across providers, making it easier to assign different models to individual steps and evaluate their performance.
Does prompt chaining reduce hallucinations?
Prompt chaining can reduce hallucinations when intermediate checks verify generated information against reliable sources. However, breaking a task into separate calls does not guarantee factual accuracy, and incorrect information can still propagate between steps. The improvement must be established by evaluating the completed outputs.
What is a validation gate in prompt chaining?
A validation gate determines whether an intermediate result meets the conditions required for further processing. It may check a response against a schema, verify information against a database, or assess an output using an LLM judge. Failed checks should trigger a defined action, such as retrying, requesting human review, or stopping execution.
How do you debug a prompt chain?
Braintrust traces preserve the inputs and outputs of individual steps, allowing developers to identify where incorrect information entered a chain. A failed execution can then become a regression test, with separate evaluations checking the corrected step and the complete chain before the change reaches production.