Prompt Chaining: Agents in a Pipeline
Prompt chaining, or an agent pipeline, runs a fixed sequence of model calls where each stage takes the previous stage's output as input. Your code controls the order. Because the steps are known in advance, a pipeline is cheaper, faster to debug and more predictable than a team where agents decide who goes next. If your task can be written as "first A, then B, then C", build a pipeline.
When a pipeline fits
A pipeline works when the task decomposes into stages with clear inputs and outputs, and when each stage is easier for the model than the whole task at once. Typical examples include: extract facts from a document, then write a summary from those facts, then translate the summary; or draft marketing copy, then check it against brand rules, then format it as HTML. Each stage gets a narrow prompt and does one thing well.
The benefit is accuracy through focus. A single prompt that says "extract, summarise, translate and format" gives the model four goals to trade off. Four prompts give it one each, and you can inspect the output after each stage.
A three-stage pipeline
The example below turns a messy support email into a clean ticket. Stage one extracts the facts as JSON. Stage two classifies urgency using only those facts. Stage three writes a short reply draft. Each stage is a function; the pipeline is function composition.
import json
import re
import anthropic
client = anthropic.Anthropic()
def call(system: str, user: str) -> str:
r = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=2000,
system=system,
messages=[{"role": "user", "content": user}],
)
return "".join(b.text for b in r.content if b.type == "text").strip()
def extract(email: str) -> dict:
text = call(
"Extract facts from a support email. Reply with JSON only: "
'{"customer_issue": str, "product": str, "error_message": str|null}',
email,
)
return json.loads(re.search(r"\{.*\}", text, re.DOTALL).group(0))
def classify(facts: dict) -> str:
return call(
"Classify urgency as LOW, MEDIUM or HIGH using only these facts. "
"HIGH means the customer cannot use the product at all. Reply with one word.",
json.dumps(facts),
)
def draft_reply(facts: dict, urgency: str) -> str:
return call(
"Write a polite reply of at most 80 words. Do not promise a fix time.",
"Facts: " + json.dumps(facts) + "\nUrgency: " + urgency,
)
def pipeline(email: str) -> dict:
facts = extract(email)
urgency = classify(facts)
reply = draft_reply(facts, urgency)
return {"facts": facts, "urgency": urgency, "reply": reply}
email = "Hi, since this morning I get 'Error 502' when I open the dashboard. Nothing loads. - Sam"
print(json.dumps(pipeline(email), indent=2))
The output is a JSON object with the extracted facts, an urgency word and a reply. Each stage sees only what it needs: the classifier never reads the raw email, which protects it from irrelevant wording and from instructions hidden in the email.
Add gates between stages
A gate is a check between stages that stops or redirects the pipeline. Gates catch problems early, before bad data flows downstream and costs more calls. Examples: verify the extracted JSON has every required key; check that the urgency is one of three allowed words; run a length check on the final reply.
def gate_facts(facts: dict) -> None:
for key in ("customer_issue", "product", "error_message"):
if key not in facts:
raise ValueError("Missing key from extractor: " + key)
def gate_urgency(urgency: str) -> str:
value = urgency.strip().upper()
if value not in {"LOW", "MEDIUM", "HIGH"}:
raise ValueError("Unexpected urgency: " + urgency)
return value
Call the first gate right after extract and the second after classify. Gates are plain code, so they cost nothing and never hallucinate.
Pipeline versus team
| Aspect | Pipeline | Free-form team |
|---|---|---|
| Control flow | Fixed in code | Decided by models |
| Cost | Known in advance | Varies per run |
| Debugging | Inspect each stage | Trace a conversation |
| Flexibility | Low | High |
Tips
- Keep each stage's prompt short and single-purpose.
- Pass structured data between stages when later stages need exact values.
- Use cheaper models for mechanical stages such as extraction and classification.
- Log every intermediate value. When the final output is wrong, the intermediate values tell you which stage failed.
- Do not turn a pipeline into a team just because it sounds more advanced. Add branching only when needed.
Many production "agent" systems are really pipelines with one or two small loops inside. That is a good thing.
Branching inside a pipeline
A pure chain is rarely enough. A common upgrade is a conditional branch: after the classification stage, high-urgency tickets might go to a stage that also pages a human, while low-urgency ones skip it. Because the control flow is plain code, a branch is just an if statement. You keep the predictability of a pipeline and gain flexibility exactly where you need it. Avoid letting the model choose the next stage freely until you have shown that fixed branching cannot do the job.
Testing each stage alone
Pipelines make testing easy. Save a handful of real inputs and the expected output of each stage. You can then test the extractor with email text and no other stage running, and the classifier with a facts object and no email. When quality drops, you know which stage to blame, and you can tune one prompt without touching the others. This is the biggest practical advantage over a single large prompt, where any change can shift everything at once.
Comments
No comments yet. Have a question or a tip? Be the first to share it.