Sub topic 9
Splitting complex tasks into chained prompts
Prerequisites
This chapter assumes you can write a clear instruction prompt, request structured output such as JSON, and read short Python snippets. It builds on the chapters about output formats and step-by-step reasoning.
Why one prompt is not always enough
A single prompt that asks for many things at once often fails in quiet ways. The model may skip a step, mix two tasks together, or format only part of the answer correctly. When it fails, you cannot tell which part went wrong.
Prompt decomposition means splitting a task into several smaller prompts. Each prompt does one job. The output of one step becomes part of the input to the next. This pattern is called a prompt chain.
Chaining helps in three ways:
- Each step has one goal, so its instructions can be short and specific.
- You can inspect and test the output of every step.
- You can check or fix an intermediate result before it spreads into later steps.
The cost is more model calls, so more latency and more spend. Use a chain when a single prompt is unreliable, not by default.
A worked example
Suppose you want a short report on a batch of customer reviews. A single prompt would say "read these reviews, find the main complaints, rank them, and write a summary for the manager." Instead, split it into three steps.
Step 1 extracts facts. Step 2 organizes them. Step 3 writes prose. Each step uses a different type of work, so each prompt can be tuned separately.
Implementing the chain
The code below chains two model calls. call_model is any function that sends a prompt string to a model and returns its text. Step 1 returns JSON, and the code validates it before step 2 runs.
import json
def extract_complaints(call_model, review):
prompt = (
"List the complaints in the review below as a JSON array of short strings.\n"
"If there are no complaints, return [].\n"
"Return only the JSON.\n\n"
f'Review:\n"""\n{review}\n"""'
)
reply = call_model(prompt)
try:
data = json.loads(reply)
except json.JSONDecodeError:
return None
if not isinstance(data, list) or not all(isinstance(x, str) for x in data):
return None
return data
def summarize(call_model, complaints):
prompt = (
"Write a summary of at most 3 bullet points for an engineering manager.\n"
"Use only the complaints below.\n\n"
f"Complaints:\n\"\"\"\n{json.dumps(complaints)}\n\"\"\""
)
return call_model(prompt)
def run_chain(call_model, reviews):
all_complaints = []
for review in reviews:
complaints = extract_complaints(call_model, review)
if complaints is None:
complaints = extract_complaints(call_model, review) # one retry
if complaints is None:
continue # skip and, in real code, log the failure
all_complaints.extend(complaints)
if not all_complaints:
return "No complaints found."
return summarize(call_model, all_complaints)Notes on this design:
- The validation function sits between the steps. A bad reply from step 1 never reaches step 2.
- Step 2 receives only the data it needs, not the original reviews. This keeps its prompt short and limits what it can get wrong.
- The delimiters (triple quotes) separate data from instructions at each step.
Choosing where to split
Split where the type of work changes. Good split points include:
- Extraction versus writing. Pulling facts out of text is a different skill from composing text.
- Analysis versus formatting. Decide the content first, then present it.
- Per-item work versus whole-set work. Process each item alone, then combine the results.
- Generate versus check. One prompt drafts an answer. A second reviews it against a list of rules.
Do not split where the pieces depend on shared context that is hard to pass along. If step 2 needs nuance from the original text that step 1 dropped, your chain loses information.
Common errors
- Passing along unvalidated output. One malformed reply can break every later step. Validate at each boundary.
- Error compounding. A small mistake in step 1 becomes a larger one in step 3. Keep early steps simple and check them.
- Too many steps. Each step adds cost and a new place to fail. If two steps are always done together and work fine, merge them.
- Lost context. Passing only a summary can drop details the later step needs. Pass the minimum necessary, but test that it is enough.
- Untested steps. Evaluate each step alone with its own test cases, then test the whole chain.
Exercise
A single prompt asks a model to read a legal contract, list all payment deadlines, convert them to a calendar format, and write a plain-language summary. It sometimes omits deadlines and sometimes breaks the calendar format. Propose a chain of steps, and name where you would add validation.
Show answer
Step 1: extract payment deadlines as a JSON list of objects with a date and a description, and validate that it parses and each date is in a known format. Step 2: convert the validated list to calendar format using ordinary code, or a prompt if code is not possible, and validate the format. Step 3: write the plain-language summary from the validated list. Validation belongs after step 1 and step 2, because those are the points where bad output would pass into later steps.
Exercise
Give two reasons not to turn a task into a prompt chain.
Show answer
Each extra step adds latency and cost, and each adds another place where output can fail or lose information. If a single prompt already works reliably on your test cases, a chain adds complexity without benefit.