Sequential pipeline (prompt chaining): fixed steps, checked in between
A pipeline runs a fixed series of model calls, each feeding the next, with gates that stop bad output early. Use it when the steps are known and you want predictable cost and behaviour.
Pipeline in 60 seconds
- What: a fixed sequence of steps, where each model call does one small job and passes its output to the next.
- Gates: simple checks between steps that stop the run early when something is wrong.
- Best for: tasks whose steps are known in advance, such as summarise, classify, then draft a reply.
- Weak spots: it cannot adapt to surprises, and an early error spreads to every later step.
- Who decides the path: your code, not the model, so cost and behaviour stay predictable.
Where this type fits
In the orchestration hub, patterns are grouped by who decides the path. The pipeline belongs to the family where your code decides, alongside the router, parallel fan-out, and state graph. It is the simplest of them: a straight line with optional exits.
The problem it solves
A single large prompt that says 'read this complaint, work out the issue, check the policy, and write a polite reply' often does several things badly. The model must juggle many goals at once, and you cannot see which part went wrong. If the reply is poor, was the summary wrong, the classification wrong, or the writing weak? You have one input and one output and nothing between.
One option is to let an agent work out the steps. That is flexible, but it is also less predictable and costs more, because the model decides the path each time. For a task whose steps never change, that flexibility is wasted.
A pipeline splits the task into stages you define. Each stage has a short, focused prompt, so it is easier to write and to test. You can inspect the output of every stage. You can use a cheaper model for easy stages. And you can insert gates, small checks that catch bad intermediate results before they reach the customer. The idea is often called prompt chaining. The trade is flexibility: if a case needs a step you did not build, the pipeline cannot invent one.
How it works
- Break the task into stages: each stage should have one clear job and a defined output format, such as a short summary or a label from a fixed list.
- Write a focused prompt per stage: give only the information that stage needs. Less input means fewer distractions and lower cost.
- Pass structured output forward: use a fixed shape, such as JSON, so the next stage reads fields instead of guessing at prose.
- Add gates: after a stage, run a check in code or with a small model. Is the JSON valid? Is the label in the allowed list? Is the text free of private data?
- Handle gate failures: on a failure, retry the stage once, fall back to a safe default, or stop and hand the case to a person.
- Return the final output: the last stage produces the result, and the run records every stage's input and output for later review.
The diagram has one path and one exit. The gate sits right after the summary because everything downstream depends on it. If the summary is empty or invalid, classifying and drafting would only produce confident nonsense. Catching it at the gate saves two model calls and prevents a bad reply.
The order of stages is fixed by your code. The model never chooses what runs next. This is the key difference from an agent. It makes the cost per request almost constant and the behaviour easy to test, because every run takes the same route.
A worked example
Acme Telecom handles a customer email with a three-stage pipeline.
Input email: 'I was charged 49.99 twice on 3 March for my fibre plan. Please sort this out. My account is 55-20871. I am very unhappy.'
- Stage 1, summarise and extract. Output:
{issue: 'duplicate charge', amount: 49.99, date: '2026-03-03', account: '55-20871', tone: 'upset'}. - Gate. Code checks the JSON is valid,
amountis a positive number, andaccountmatches the patterndd-ddddd. All pass, so the run continues. Had the account been missing, the gate would have stopped the run and passed the email to a person. - Stage 2, classify. Input is only the structured summary, not the whole email. Output:
{category: 'billing_dispute', priority: 'high'}. The label comes from a fixed list, and a second tiny check confirms it is on the list. - Stage 3, draft reply. Input is the summary and the category, plus the billing dispute policy text. Output: a short apology, a statement that the duplicate will be refunded within 5 working days, and the account reference.
- Output. The draft is saved for an agent to review and send.
Three small calls, one gate, and a full record of what each stage saw and produced. If the draft is off, the log shows whether the summary or the classification was at fault.
{
"issue": "duplicate charge",
"amount": 49.99,
"date": "2026-03-03",
"account": "55-20871",
"tone": "upset"
}Building it
The sketch below shows the stages as plain functions. llm.generate is a placeholder for your model call. The parts worth copying are the structured hand-off, the gate, the single retry, and the stage log.
import json
import re
MAX_RETRIES = 1 # one retry per stage, then give up
TIMEOUT_SECONDS = 20 # per model call
CATEGORIES = {'billing_dispute', 'outage', 'cancellation', 'other'}
# Placeholder: llm.generate stands in for your own model call.
def call_stage(llm, prompt, log, name):
for attempt in range(MAX_RETRIES + 1):
text = llm.generate(prompt, timeout=TIMEOUT_SECONDS)
log.append({'stage': name, 'attempt': attempt, 'output': text})
try:
return json.loads(text) # structured output, not prose
except ValueError:
continue # retry once on bad JSON
return None
def summary_gate(s):
# Why: later stages are only as good as this one, so check it in code.
ok = isinstance(s, dict) and isinstance(s.get('amount'), (int, float))
return ok and s['amount'] > 0 and re.fullmatch(r'\d\d-\d{5}', s.get('account', '')) is not None
def handle_email(email, llm, policy_text):
log = []
summary = call_stage(llm, 'Extract issue, amount, date, account, tone as JSON:\n' + email, log, 'summarise')
if not summary_gate(summary):
return {'status': 'needs_person', 'reason': 'summary failed gate', 'log': log}
label = call_stage(llm, 'Classify into ' + str(sorted(CATEGORIES)) + ' as JSON:\n' + json.dumps(summary), log, 'classify')
if not label or label.get('category') not in CATEGORIES:
return {'status': 'needs_person', 'reason': 'bad category', 'log': log}
draft = llm.generate('Write a short, polite reply using only this data and policy.\n'
+ json.dumps(summary) + '\n' + policy_text, timeout=TIMEOUT_SECONDS)
log.append({'stage': 'draft', 'output': draft})
return {'status': 'ok', 'category': label['category'], 'draft': draft, 'log': log}Design decisions
- Where to cut the stages: split where the output changes kind, such as extract, decide, and write. Default to three to five stages. Too many adds delay and cost, and each hand-off can lose detail.
- Interface between stages: use validated structured output with a fixed schema. Free text invites parsing errors and quiet drift.
- Gate placement: put a gate after any stage whose error would be costly downstream, and before any step with side effects. Prefer cheap code checks over a model check where you can.
- Model per stage: use a small, fast model for extraction and labelling, and a stronger one for the final writing. This often cuts cost with no loss of quality.
- Latency: stages run in series, so delay adds up. Where two stages do not depend on each other, run them together using parallel fan-out.
- Failure handling: retry once, then fall back or stop. Never loop without a cap. Hand uncertain cases to a person using a human checkpoint.
- Versioning: keep each stage's prompt under version control, and log the version with every run. A change in one stage should be testable alone.
Measuring it
- Per-stage accuracy: for each stage, compare its output with a labelled sample. For a classifier, that is the share of correct labels.
- End-to-end quality: score final outputs on a fixed set of cases using a rubric, such as correct facts, correct tone, and policy followed.
- Gate rate: the share of runs stopped at each gate. A sudden rise means an input change or a broken stage.
- Error propagation: among bad final outputs, the share traced to an earlier stage. This shows which stage to fix first.
- Cost and latency per run: tokens and seconds per stage, summed. Because the path is fixed, these should be steady, and drift is a warning.
- Human hand-over rate: the share of runs passed to a person, with reasons.
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Summarise, classify, then draft a reply | Yes | The steps are known and each is a small job. |
| Document processing with extraction, validation, and formatting | Yes | Gates between stages catch bad data early. |
| Requests that differ widely and need different steps | No | Use a router or an agent so the path can vary. |
| The next step depends on what a tool returns | No | A single agent or a state graph handles branching better. |
| High volume with tight cost limits | Yes | A fixed path gives steady, low cost and allows cheap models in early stages. |
| Open-ended research with unknown steps | No | A fixed line cannot explore. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Focused stages often beat one big prompt, but an early mistake carries forward. | Gate after risky stages and test each stage on its own. |
| Latency | Stages run in series, so total delay is the sum of all calls. | Keep stages few, use fast models early, and run independent work in parallel. |
| Cost | Predictable, and often lower, since easy stages use small models. | Pass each stage only what it needs, and track cost per run. |
| Complexity | Low. Plain code with clear logs. | Keep prompts and schemas versioned together. |
| Failure modes | Format errors, errors spreading downstream, and rigid handling of odd cases. | Validate outputs, stop early at gates, and send unusual cases to a person. |
Compared with related types
A router picks one of several paths for each request, while a pipeline always takes the same one. They combine well: route first, then run a pipeline per category. Parallel fan-out runs independent branches at the same time and merges them, which suits work that does not depend on earlier output.
A single agent lets the model choose steps. That is more flexible and less predictable. A common rule is to use a pipeline for the parts you can write down, and an agent only for the parts you cannot.
What this means for your role
Common mistakes
Further reading
- Orchestration patterns: the hub that compares all orchestration patterns.
- Guardrails and safety: checks that suit gates between stages.
- Evaluation and observability: measuring stages and tracing runs.
A pipeline is the plainest orchestration pattern, and often the right one. Define the stages, check the hand-offs, and add flexibility only where the task truly needs it.