Lesson 15.1 · 1 of 5 · 4 min read · Reviewed 24 Nov 2026
Breaking a task into a chain
By the end, you can
- Split a complex task into a chain of focused prompts.
- Pass outputs between steps in tags.
Prompt chainingPrompt chaining: Splitting a task into steps where each model call handles one step and passes its output to the next. is also a workflowWorkflow: A system where LLM calls and tools follow a path defined in code, rather than chosen by the model. pattern, which chapter 41 revisits for agentsAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done.. This chapter covers the prompting side.
Why chain
A single prompt that researches, outlines, drafts and formats must juggle everything at once. Split it:
- Extract the key facts from the sources into
<facts>. - Outline a report from
<facts>. - Draft each section from the outline and facts.
- Format the draft to the house style.
Each step has one clear job, so each prompt is short and focused.
Benefits
- Accuracy: full attentionAttention: The mechanism that lets each token weigh every other token in the context when building its representation. on one thing.
- Debugging: when the report is wrong, you can see which step went wrong.
- Testing: each step can have its own evalEval: A repeatable test that measures how well an AI system performs on a set of cases with defined success criteria..
- Gates: add code checks between steps, such as “are there at least five facts?”
Cost
More calls and more latencyLatency: The time from sending a request until you get the response, or until the first token arrives when streaming.. Use a chain where a single prompt is clearly struggling, and use smaller models for simple steps.
Key points
- A chain breaks one big prompt into steps, each with one clear job.
- Each step is easier to get right, test and debug.
- Pass each step's output to the next in tags, and check between steps where it matters.
Chain three steps with a code gate
Split one big task into focused steps that pass tagged output along, with a code check that stops a bad run early.
You will have: A three-step chain (extract, outline, draft) with a gate, run on a good source and an empty one.
Steps
- Read the simulated steps: each one stands in for a focused prompt and returns tagged text.
- Complete gate so it counts the <fact> lines and fails when there are fewer than three.
- Complete run_chain so it calls extract, checks the gate, then outline and draft, and records how many calls it made.
- Run it on both sources and compare the number of calls.
Done when
- The good source produces a draft after 3 calls.
- The empty source stops at the gate after 1 call and prints 'stopped at gate'.
- Each step's output is printed, so you can see which step a problem came from.
Open in the Playground No API key needed.
Starter code (Python)
import re
def extract(source):
# Stands in for the "extract the key facts" prompt.
facts = [s.strip() for s in source.split(".") if any(ch.isdigit() for ch in s)]
return "<facts>\n" + "\n".join(f"<fact>{f}</fact>" for f in facts) + "\n</facts>"
def outline(facts_block):
n = facts_block.count("<fact>")
return f"<outline>1. Headline numbers ({n} facts)\n2. What changed\n3. What to watch</outline>"
def draft(outline_block, facts_block):
first = re.search(r"<fact>(.*?)</fact>", facts_block).group(1)
return f"<draft>This week: {first}. More in the sections below.</draft>"
def gate(facts_block, minimum=3):
# TODO: return True only if there are at least `minimum` <fact> entries.
return True
def run_chain(source):
calls = 0
# TODO: call extract (calls += 1), print it, check gate; if it fails, print "stopped at gate" and return calls.
# TODO: then outline and draft (each calls += 1), printing each step's output.
return calls
GOOD = "Sales rose 12 percent. Returns fell to 3 percent. Two new stores opened in 2026. Weather was mild."
EMPTY = "The upload was a blank page."
for name, src in [("good", GOOD), ("empty", EMPTY)]:
print(f"--- {name}")
print("calls:", run_chain(src))
Show a solution
import re
def extract(source):
# Stands in for the "extract the key facts" prompt.
facts = [s.strip() for s in source.split(".") if any(ch.isdigit() for ch in s)]
return "<facts>\n" + "\n".join(f"<fact>{f}</fact>" for f in facts) + "\n</facts>"
def outline(facts_block):
n = facts_block.count("<fact>")
return f"<outline>1. Headline numbers ({n} facts)\n2. What changed\n3. What to watch</outline>"
def draft(outline_block, facts_block):
first = re.search(r"<fact>(.*?)</fact>", facts_block).group(1)
return f"<draft>This week: {first}. More in the sections below.</draft>"
def gate(facts_block, minimum=3):
return facts_block.count("<fact>") >= minimum
def run_chain(source):
calls = 0
facts = extract(source); calls += 1
print(facts)
if not gate(facts):
print("stopped at gate: not enough facts")
return calls
plan = outline(facts); calls += 1
print(plan)
text = draft(plan, facts); calls += 1
print(text)
return calls
GOOD = "Sales rose 12 percent. Returns fell to 3 percent. Two new stores opened in 2026. Weather was mild."
EMPTY = "The upload was a blank page."
for name, src in [("good", GOOD), ("empty", EMPTY)]:
print(f"--- {name}")
print("calls:", run_chain(src))