Lesson 10 of 15 · Advanced Techniques
Prompt Chaining
Split a complex AI task into a chain of small prompts where each output feeds the next: chain patterns, checks between steps, routing and a Python example.
- 7 min read
- Beginner
- Reviewed
- What prompt chaining is and why it beats one giant prompt for complex work
- Common chain patterns you can reuse
- How to add checks (gates) between steps
- The costs of chaining, and how it leads to AI agents
One giant prompt versus a chain
Suppose you want a monthly report from 500 customer reviews: find the problems, count them, and write recommendations. You could put it all in one huge prompt. The model would have to read, classify, count and write all at once, and if the result is wrong, you can't tell which part failed.
It's how people work too: a writer researches, then outlines, then drafts, then edits, rather than doing everything in one pass.
A chain in action
The program below runs a three-step chain over five reviews. Each function stands in for one model call with its own small prompt (shown in the comments). A real app would send each prompt to a model; here simple code plays the model's part so you can see the data flowing between steps.
reviews = [
"Delivery was late and the box was damaged.",
"Lovely plant, arrived healthy.",
"Late delivery again. Plant was fine though.",
"The pot was cracked when it arrived.",
"Arrived late, very disappointed.",
]
# Each function stands in for one model call with its own small, focused prompt.
def step1_extract(review):
# Prompt: "List the problems in this review: late delivery, damaged item, or none."
problems = []
text = review.lower()
if "late" in text:
problems.append("late delivery")
if "damaged" in text or "cracked" in text:
problems.append("damaged item")
return problems
def step2_count(problem_lists):
# Prompt: "Count how many reviews mention each problem."
counts = {}
for problems in problem_lists:
for problem in problems:
counts[problem] = counts.get(problem, 0) + 1
return counts
def step3_summarise(counts, total):
# Prompt: "Write one sentence for the manager from these counts."
top = max(counts, key=counts.get)
return (f"Of {total} reviews, the most common problem was {top} "
f"({counts[top]} reviews), so start there.")
# Run the chain, printing what passes between the steps
problem_lists = []
for review in reviews:
problem_lists.append(step1_extract(review))
print("Step 1 output:", problem_lists)
counts = step2_count(problem_lists)
print("Step 2 output:", counts)
print("Step 3 output:", step3_summarise(counts, len(reviews)))Look at what you can do with a chain that you can't with one big prompt:
- Inspect each step's output. If step 1 mislabels a review, you see it immediately.
- Fix one step without touching the others.
- Use different tools per step. Counting in step 2 doesn't need a model at all; ordinary code is cheaper and exact.
Common chain patterns
| Pattern | Steps | Example |
|---|---|---|
| Extract, then use | Pull out the relevant parts, then work with only those | Find the quotes that answer a question, then answer from the quotes |
| Outline, draft, edit | Plan, write, polish | Blog post, report, long email |
| Transform in stages | Each step changes the format | Notes, then a table, then a summary for a manager |
| Classify, then route | Decide what kind of input it is, then send it to a specialised prompt | Billing questions to a billing prompt, bugs to a bug prompt |
| In parallel, then combine | Run several independent steps at once, then merge | Summarise 10 chapters separately, then summarise the summaries |
Gates: checks between steps
A gate is a check between two steps that decides whether to continue. It can be ordinary code ("did step 1 return valid JSON?", "is the draft under 200 words?") or another prompt ("Does this draft answer every question in the email? Reply yes or no").
Gates stop one bad output from flowing through the rest of the chain, which matters because errors propagate: a mistake in step 1 becomes the input to step 2.
The trade-offs
Chaining is not free:
- More calls mean more time and usually more cost.
- Context must be passed on. Step 3 only knows what you give it; if it needs the original question, include it.
- More moving parts to build and maintain.
Use a single prompt for simple tasks. Reach for a chain when a task has distinct stages, when you need to check intermediate results, or when one prompt keeps getting part of the job wrong.
Common mistakes
Connect a two-step chain with a gate in the middle: the second step only runs if the first one found something.
def find_days(text): # step 1 (stands in for a model call)
days = []
for word in text.replace(",", "").replace("?", "").split():
if word in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]:
days.append(word)
return days
def make_reminders(days): # step 2 (stands in for another model call)
reminders = []
for day in days:
reminders.append("Reminder set for " + day)
return reminders
email = "Can we meet on Tuesday, and could you send the report by Friday?"
# Run step 1 on the email.
# If it found no days, print "No dates found" and stop.
# Otherwise pass its result to step 2 and print each reminder on its own line.
What is a main advantage of a prompt chain over one large prompt for a complex task?
Summary
- Prompt chaining splits a task into focused steps, each feeding the next.
- Chains let you inspect, fix and choose the right tool for each step, including plain code.
- Useful patterns: extract then use, outline-draft-edit, transform in stages, classify and route, parallel then combine.
- Add gates between steps so one bad output does not flow through.
- Chains cost more calls; use them when a task has real stages.
Next: getting a model to check and improve its own work.
Finished reading? Tick it off to track your progress.