Sub topic 9
Splitting Complex Tasks into Chained Prompts
This chapter assumes you can write a clear instruction, use delimiters, request structured output, and validate JSON in Python. It builds on the output-format and reasoning chapters. Here you will learn to split one large task into several smaller prompts, pass results between them, and decide when splitting is worth the cost.
Why one big prompt often fails
A single prompt that asks for many things at once makes the model balance competing goals in one pass. Consider this request:
"Read this customer email, work out what the customer wants, check it against our refund policy, draft a reply in our brand voice, and translate the reply into German."
The model may do all five steps. Common failures appear as the task grows:
- A step is skipped or done shallowly, such as the policy check.
- Constraints from one step leak into another. The German reply may lose the brand tone.
- When the output is wrong, you cannot tell which step caused it.
- The prompt grows long, and instructions in the middle get less attention.
Prompt chaining is the practice of splitting a task into a sequence of prompts, where the output of one step becomes part of the input to the next. Each prompt has one job, one output format, and one way to be tested.
The shape of a chain
A chain is a pipeline. Ordinary code sits between the model calls. That code parses, validates, filters, and routes data.
Three properties make this design useful:
- Single responsibility. Each prompt does one kind of work: extract, classify, decide, write, or check.
- Explicit interfaces. Each step's output has a defined format, so the next step knows what it receives.
- Checkpoints. Code can inspect the data between steps and stop the chain early.
A worked example: ticket triage
The task is to turn a raw support ticket into a short manager summary and a suggested priority. We split it into three steps.
| Step | Job | Input | Output |
|---|---|---|---|
| 1. Extract | Pull out facts | Raw ticket text | JSON with `product`, `symptom`, `customer_impact`, `cause` |
| 2. Classify | Assign a priority | The JSON from step 1 | One of `low`, `medium`, `high` |
| 3. Summarize | Write the summary | JSON and priority | At most 3 bullet points |
The first prompt only extracts. It does not interpret or advise.
Extract facts from the support ticket below.
Return only a JSON object with these keys:
- "product": string
- "symptom": string
- "customer_impact": string
- "cause": string, or "Cause unknown" if the ticket does not state one
Do not guess. Use only what the ticket says.
Ticket:
"""
{ticket_text}
"""The second prompt receives the extracted fields, not the raw ticket. That keeps its input small and prevents it from being distracted by unrelated ticket text.
Assign a priority to this issue.
Rules:
- high: customer cannot use the product at all, or data may be lost
- medium: a feature is broken but a workaround exists
- low: cosmetic problem or question
Reply with exactly one word: low, medium, or high.
Issue:
"""
{issue_json}
"""The third prompt writes the final text. By now the facts and the priority are settled, so the model can spend its effort on wording.
The chain in Python
The code below runs the three steps. It takes call_model as an argument, as in the evaluation chapter, so you can plug in any model client. The stub at the bottom lets you run the file without an API key.
import json
ALLOWED_PRIORITIES = {"low", "medium", "high"}
REQUIRED_KEYS = {"product", "symptom", "customer_impact", "cause"}
EXTRACT = (
"Extract facts from the support ticket below.\n\n"
"Return only a JSON object with the string keys \"product\", \"symptom\", "
"\"customer_impact\" and \"cause\". If the ticket does not state a cause, "
"use \"Cause unknown\". Do not guess.\n\n"
'Ticket:\n"""\n{ticket}\n"""'
)
CLASSIFY = (
"Assign a priority to this issue.\n\n"
"- high: the customer cannot use the product, or data may be lost\n"
"- medium: a feature is broken but a workaround exists\n"
"- low: cosmetic problem or question\n\n"
"Reply with exactly one word: low, medium, or high.\n\n"
'Issue:\n"""\n{issue}\n"""'
)
SUMMARIZE = (
"Write a summary for an engineering manager.\n\n"
"- Use at most 3 bullet points.\n"
"- State the customer impact first.\n"
"- Mention the priority.\n\n"
'Facts:\n"""\n{issue}\n"""\n\nPriority: {priority}'
)
def parse_facts(reply):
try:
data = json.loads(reply)
except json.JSONDecodeError:
return None
if not isinstance(data, dict) or not REQUIRED_KEYS <= data.keys():
return None
return data
def triage(call_model, ticket):
facts = parse_facts(call_model(EXTRACT.format(ticket=ticket)))
if facts is None:
return {"status": "needs_review", "failed_step": "extract"}
issue = json.dumps(facts, indent=2)
priority = call_model(CLASSIFY.format(issue=issue)).strip().lower()
if priority not in ALLOWED_PRIORITIES:
return {"status": "needs_review", "failed_step": "classify"}
summary = call_model(SUMMARIZE.format(issue=issue, priority=priority))
return {"status": "ok", "priority": priority, "summary": summary.strip()}
def fake_model(prompt):
# Stand-in for a real model so the example runs offline.
if prompt.startswith("Extract"):
return ('{"product": "Mobile app", "symptom": "Crashes on login", '
'"customer_impact": "Cannot sign in", "cause": "Cause unknown"}')
if prompt.startswith("Assign"):
return "high"
return "- Customers cannot sign in.\n- Priority: high.\n- Cause unknown."
print(triage(fake_model, "The app crashes every time I log in."))Notice what the Python code does that no prompt could do reliably. It checks the keys, rejects any priority outside the allowed set, and stops the chain with a record of which step failed.
Passing data between steps
How you pass output forward affects reliability.
- Pass structured data, not prose. A JSON object with named fields is easier to check and to insert into the next prompt than a paragraph.
- Pass only what the next step needs. The classifier above never sees the raw ticket. This lowers cost and reduces the chance of unrelated text steering the result.
- Keep the delimiters. When one step's output becomes the next step's input, treat it as data and wrap it in delimiters. Model output can contain text that looks like instructions.
- Carry forward the original when a step needs it. If the final step must quote the customer, pass the original text as well as the extracted fields. Extraction loses detail.
Common chain patterns
Most chains are variations on a few shapes.
| Pattern | How it works | Typical use |
|---|---|---|
| Sequential | Step N feeds step N+1 | Extract, then classify, then write |
| Branching | A classifier chooses which prompt runs next | Billing questions go to one prompt, bug reports to another |
| Map and combine | The same prompt runs on each chunk, then a final prompt merges the results | Summarizing a long document in sections |
| Draft and critique | One step writes, another checks against a list of criteria, a third revises | Reports with strict style rules |
| Generate and verify | One step produces an answer, code or a second prompt verifies it | Extracted quotes checked against the source |
Branching example
A routing step keeps specialized prompts short. The router returns one label, and ordinary code picks the prompt.
ROUTES = {
"billing": "Answer the billing question below using only the policy text.",
"bug": "Summarize the bug report below and list the steps to reproduce it.",
"other": "Write a polite reply saying a human will follow up.",
}
def pick_prompt(label):
# Unknown labels fall back to the safest route.
return ROUTES.get(label.strip().lower(), ROUTES["other"])
print(pick_prompt("Billing"))
print(pick_prompt("shipping"))The fallback matters. A router can return something outside its label set, and the chain must still behave sensibly.
Map and combine example
When a document is too long for one prompt, run a summarization prompt on each chunk, then run a second prompt over the chunk summaries.
def chunk_text(text, max_chars=2000):
paragraphs = text.split("\n\n")
chunks, current = [], ""
for p in paragraphs:
if current and len(current) + len(p) + 2 > max_chars:
chunks.append(current)
current = p
else:
current = f"{current}\n\n{p}" if current else p
if current:
chunks.append(current)
return chunks
def summarize_long(call_model, text):
partials = []
for chunk in chunk_text(text):
prompt = f'Summarize in 2 sentences:\n"""\n{chunk}\n"""'
partials.append(call_model(prompt).strip())
joined = "\n".join(f"- {s}" for s in partials)
final = ("Combine these section summaries into one summary of at most "
f'5 sentences.\n"""\n{joined}\n"""')
return call_model(final).strip()This splits on paragraph boundaries, so a single paragraph longer than max_chars becomes its own oversized chunk. Handle that case if your documents can contain very long paragraphs.
Costs and failure modes
Chaining is not free. Weigh these before you split a task.
- More calls. Each step adds latency and cost. A four-step chain takes roughly four times as long as one call when the steps run in sequence.
- Error propagation. A wrong extraction in step 1 produces a confident wrong answer in step 3. Later steps trust earlier output unless you check it.
- Information loss. Each handoff compresses. Details dropped in an early step cannot be recovered later.
- Format drift. A step may wrap JSON in prose, as in "Sure! Here is the JSON:". Validate every handoff, and do not assume the format held.
- Interface changes. If you change the output keys in step 1, you must update step 2. Treat each interface as a contract.
Deciding whether to split
Start with a single prompt. Split when you see evidence that it is failing, not by default.
Signs that splitting will help:
- The model reliably does some parts of the task and skips or blurs others.
- Different parts need different formats, tones, or constraints.
- You need to inspect or log intermediate results, for example for audits.
- Some steps are better done by code, such as arithmetic, lookups, or schema checks.
- The input is too long for one prompt.
Signs that a single prompt is enough:
- The task is short and has one output.
- The steps depend tightly on each other's reasoning, so separating them loses context.
- Latency or cost limits are strict.
A middle path exists. If the problem is reasoning quality rather than task size, ask for step-by-step reasoning inside one prompt first. Reach for a chain when you need checkpoints or when the steps have different requirements.
Testing a chain
Test each step alone, then test the whole chain.
- Build a small set of labeled cases for each step. For the classifier, that means issue JSON paired with the expected priority.
- Score each step on its own cases with the same kind of accuracy loop used for single prompts.
- Run end-to-end cases and compare the final output against expectations.
- When an end-to-end case fails, find the first step whose output is wrong. Fix that step.
Per-step tests are the main advantage of a chain. A failing single prompt gives you one score. A failing chain tells you where the failure began.
Summary of working rules
- Give each step one job and one output format.
- Validate every handoff in code and stop with a clear status when a check fails.
- Pass the smallest structured input each step needs.
- Wrap passed-along text in delimiters and treat it as data.
- Test steps separately before testing the whole chain.
- Split only when a single prompt shows a real problem.
Exercise
A three-step chain extracts facts from an email, classifies urgency, and drafts a reply. The drafts are often wrong. You check the end-to-end results and see that in many failing cases the extracted facts are already wrong. What should you do first, and why?
Show answer
Fix and test the extraction step on its own before touching the other steps. Errors propagate forward, so the classifier and the drafter receive bad input and cannot produce good output. Build labeled cases for extraction, score that step alone, revise its prompt, and add a validation check on its output. Then re-run the end-to-end cases.
Exercise
You are designing a chain where a router prompt returns a category label, and code selects the next prompt. The router sometimes returns "Billing issue" instead of "billing". Name two changes that make the chain robust.
Show answer
First, normalize the reply in code, for example with strip and lower, and restrict the router prompt to a fixed list of labels with an instruction to reply with exactly one of them. Second, add a fallback route for any label not in the allowed set, such as sending the item to human review, so an unexpected reply never causes a crash or a wrong branch.