Chapter 1 · Instructions, Models and Reasoning
Reasoning Task Design: Decomposition, Rationales and Intermediate Schemas
- Page 3 of 24
- 17 min read
Some tasks need one clean piece of writing. Others need several facts to be found, combined by rules, and turned into a decision, where one slip gives a confident but wrong answer. The way you design the prompt should follow that difference. This page shows how to tell the two kinds apart, how to split a hard task into steps you can check, and how to ask for an explanation you can verify instead of a story you must trust.
You need Python 3.12 or newer and the standard library only. The blocks share variables, so type them in order. The "model" functions in the code are toy providers: small deterministic stand-ins that make the checks repeatable. Real models are less predictable, which is why you test them, and a toy result is never evidence about a real model.
What you will learn
- How to tell simple generation from multi-step reasoning, and how to rate a task by difficulty and by the cost of an error.
- When a direct instruction is enough, and how to split a hard task into subtasks with dependencies.
- How to give each step an output schema and check it before the next step starts.
- How to ask for a short rationale with evidence you can verify, why hidden reasoning is not that, and where chain-of-thought requests stop helping.
Simple generation or multi-step reasoning
Distinguish simple generation from multi-step reasoning tasks. In simple generation, many different outputs are acceptable and you can judge the result by reading it: rewrite this sentence, suggest three headlines. In multi-step reasoning the answer depends on several facts combined in a certain order, and a wrong middle step still produces a fluent final answer: decide whether a return qualifies for a refund and compute the amount. The second kind fails quietly.
| Simple generation | Multi-step reasoning | |
|---|---|---|
| Acceptable outputs | Many | Usually one correct answer |
| Where an error hides | Visible in the text | In a middle step; the final text still reads well |
| How you check | Read it | Check each step and recompute the result |
Classify tasks by difficulty and error cost
Classify tasks by difficulty and error cost. Difficulty alone is the wrong measure. A one-step extraction of an invoice number is easy, but a wrong number may pay the wrong supplier. Rate each task on two axes, the number of dependent steps and the cost of a wrong answer, and let the rating choose the design. The function below is a small policy you can argue about and change; it is a teaching rule, not a standard.
TASKS = [ # (task, dependent steps, cost of an error)
("Rewrite a two-line apology calmly", 1, "low"),
("Pull the invoice number out of an email", 1, "high"),
("Draft three newsletter headlines", 1, "low"),
("Decide a return and compute the refund", 4, "high"),
("Plan shift cover from five notes", 3, "low"),
]
def route(steps, cost):
design = "direct instruction" if steps == 1 else "explicit subtasks"
if cost == "high":
design += " + independent check" + (" + human review" if steps != 1 else "")
return design
for task, steps, cost in TASKS:
print(task.ljust(42), str(steps), cost.ljust(5), route(steps, cost))Rewrite a two-line apology calmly 1 low direct instruction
Pull the invoice number out of an email 1 high direct instruction + independent check
Draft three newsletter headlines 1 low direct instruction
Decide a return and compute the refund 4 high explicit subtasks + independent check + human review
Plan shift cover from five notes 3 low explicit subtasksEasy tasks with a low cost get a plain instruction. Easy tasks with a high cost still get an independent check. Multi-step tasks get explicit subtasks, and the expensive ones also get a person in the loop.
Direct instructions for simple tasks
Use direct instructions for simple, well-defined tasks. Extra machinery costs time and money and adds new places to fail. If the task is one step with a clear output, say what you want and stop.
Weak prompt:
First analyse the tone of this apology in depth, then list its weaknesses, then plan a
rewrite, then rewrite it, then evaluate your rewrite and improve it again: "Sorry, we messed up."Better prompt:
Rewrite this apology in a calm, professional tone, in two sentences or fewer:
"Sorry, we messed up."What changed: the better prompt names the goal, the tone and the length, and leaves out five steps that add nothing to a one-step task. Use the saved effort for the tasks that do need structure.
Decompose into subtasks and define dependencies
Decompose a complex task into explicit subtasks, and define dependencies between subtasks. Our running problem is a return request with two rules: R1, a return must happen within 30 days of delivery; R2, a restocking fee of 10% of the unit price applies to each opened unit. The work splits into five parts. Three of them are plain code, not model calls: the policy values, the date check and the money calculation. Dates and money are better done by a program, which gives the same answer every time. (The same idea appears in Core Patterns II: Decompose, Critique and Revise.)
from graphlib import CycleError, TopologicalSorter
SUBTASKS = { # name: (done by, needs)
"policy": ("code", []),
"extract": ("model", []),
"eligible": ("code", ["extract", "policy"]),
"amount": ("code", ["extract", "eligible", "policy"]),
"reply": ("model", ["eligible", "amount"]),
}
def rounds(subtasks):
sorter = TopologicalSorter({name: needs for name, (_, needs) in subtasks.items()})
sorter.prepare()
out = []
while sorter.is_active():
ready = sorted(sorter.get_ready())
out.append(ready)
sorter.done(*ready)
return out
for i, batch in enumerate(rounds(SUBTASKS), 1):
print(f"round {i}:", ", ".join(f"{n} ({SUBTASKS[n][0]})" for n in batch))
try:
rounds(dict(SUBTASKS, policy=("code", ["reply"])))
except CycleError as error:
print("cycle between:", sorted(set(error.args[1])))round 1: extract (model), policy (code)
round 2: eligible (code)
round 3: amount (code)
round 4: reply (model)
cycle between: ['amount', 'eligible', 'policy', 'reply']Round 1 holds two independent subtasks that could run at the same time. Every other subtask waits for the ones it needs. Writing the dependencies as data has two benefits: you can see the order and the parallel parts, and a mistaken circular dependency is reported instead of discovered in production.
Intermediate output schemas
Provide intermediate output schemas. Each model step should return a small record with fixed fields, and your code should check it before the next step reads it. Here the extraction step must return six fields; money stays a string with two decimals so no float rounding enters. The extractor is a toy stand-in; toy_extract_sloppy imitates a step that returns the right content with wrong types.
import json
import re
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
def is_iso(v):
try:
date.fromisoformat(v)
return True
except (TypeError, ValueError):
return False
STAGE1 = {
"item": lambda v: isinstance(v, str) and v != "",
"qty": lambda v: type(v) is int and v in range(1, 1000),
"unit_price": lambda v: isinstance(v, str) and re.fullmatch(r"\d+\.\d\d", v) is not None,
"delivered": is_iso,
"returned": is_iso,
"opened_units": lambda v: type(v) is int and v in range(0, 1000),
}
MESSAGE = ("Hi, I am Lena. I bought 2 Trail Lamp at 24.50 each, delivered 2026-09-20. "
"I opened one and want to return both on 2026-10-05.")
def problems(record, schema):
out = [f"missing: {k}" for k in schema if k not in record]
out += [f"bad value: {k}={record[k]!r}" for k, ok in schema.items() if k in record and not ok(record[k])]
return out + [f"unexpected: {k}" for k in sorted(record) if k not in schema]
def toy_extract(text): # stand-in for the extraction model
qty, item, price, delivered, returned = re.search(
r"bought (\d+) (.+?) at (\d+\.\d\d) each, delivered (\S+)\. .*return both on (\S+)\.", text).groups()
return {"item": item, "qty": int(qty), "unit_price": price, "delivered": delivered,
"returned": returned, "opened_units": 1} # "I opened one"
def toy_extract_sloppy(text): # stand-in that returns the right content in the wrong types
return dict(toy_extract(text), qty="2", delivered="20 Sep")
def decide(rec):
days = (date.fromisoformat(rec["returned"]) - date.fromisoformat(rec["delivered"])).days
if days not in range(0, 31):
return {"eligible": False, "rule": "R1", "days": days}
price = Decimal(rec["unit_price"])
fee = (price * Decimal("0.10") * rec["opened_units"]).quantize(Decimal("0.01"), ROUND_HALF_UP)
return {"eligible": True, "rule": "R2", "days": days, "fee": str(fee),
"refund": str(price * rec["qty"] - fee)}
def chain(message, extractor):
record = extractor(message)
bad = problems(record, STAGE1)
return {"stopped_at": "extract", "problems": bad} if bad else decide(record)
for extractor in (toy_extract, toy_extract_sloppy):
print(extractor.__name__, json.dumps(chain(MESSAGE, extractor), sort_keys=True))toy_extract {"days": 15, "eligible": true, "fee": "2.45", "refund": "46.55", "rule": "R2"}
toy_extract_sloppy {"problems": ["bad value: qty='2'", "bad value: delivered='20 Sep'"], "stopped_at": "extract"}The good extractor flows through: the return is 15 days after delivery, one opened unit costs a fee of 2.45, and the refund is 46.55. The sloppy extractor is stopped at the first stage with the names of the bad fields, so no wrong value reaches the date and money code. A stop with a named reason is cheaper to debug than a wrong refund. A fuller chain with a shared helper comes in Prompt Chaining: Stages, Fixed Schemas and the promptlab Helper.
A concise rationale with checkable evidence
Ask for a concise rationale or evidence summary, and distinguish a verifiable explanation from hidden internal reasoning. What you want next to the decision is something you can check: which rule decided it, which words in the input support it, and a one- or two-sentence reason. What you should not rely on is a claim about what happened inside the model. The visible text is a generated explanation, and it can be fluent and wrong.
Better prompt:
Decide whether the return is eligible, using only the rules and the customer message.
Rules:
R1. Return within 30 days of delivery.
R2. Restocking fee: 10% of the unit price for each opened unit.
Return JSON with these keys: decision ("approve", "reject" or "ask"), rule (deciding rule id),
evidence (up to 3 quotes copied exactly from the message), rationale (at most 25 words).
If a needed fact is missing, use "ask" and name the fact in the rationale.What changed: the model must point to a rule and to exact words in the input, the length is bounded, and there is an allowed way out when information is missing. Now a typical failure. This example reply is illustrative only:
Example reply (illustrative; yours will differ):
{"decision": "approve", "rule": "R2",
"evidence": ["delivered 2026-09-20", "the box was damaged"],
"rationale": "Returned within 30 days and the item arrived damaged, so a fee does not apply."}What to verify: the second quote does not appear in the customer's message, and the rationale rests on it. A human reading quickly may accept the whole record. Code can check the part that is checkable:
POLICY = {"R1": "Return within 30 days of delivery.", "R2": "Restocking fee, opened units."}
def check_explanation(source, out):
issues = [] if out.get("rule") in POLICY else [f"unknown rule: {out.get('rule')!r}"]
issues += [f"quote not in the message: {q!r}" for q in out.get("evidence", []) if q not in source]
if len(out.get("rationale", "").split()) > 25:
issues.append("rationale is longer than 25 words")
return issues
good = {"decision": "approve", "rule": "R2", "evidence": ["delivered 2026-09-20", "I opened one"],
"rationale": "Returned after 15 days, inside 30. One unit was opened, so one fee applies."}
invented = dict(good, evidence=["delivered 2026-09-20", "the box was damaged"])
for record in (good, invented):
print(check_explanation(MESSAGE, record) or "explanation checks pass")explanation checks pass
["quote not in the message: 'the box was damaged'"]This check proves only that the quotes exist and the rule id is known. It cannot prove that the quotes support the decision; the date code in the previous section is what checks the decision itself. Combining both is the point: use the explanation to make the model's claims inspectable, and use code or a person for the claims that matter.
Limits of chain-of-thought requests
Understand the limits of requests for chain-of-thought. Asking a model to write out its reasoning gives you more text, not a recording of its internals, and it has costs. It uses output tokens and time. It can lengthen an answer without making it more accurate. On models that already deliberate before answering, a hand-written reasoning script can be redundant or even interfere. And some products summarise, hide or decline to return their internal reasoning, so your code must not depend on seeing it.
Provider note (as of 2026-10-12): OpenAI documents that reasoning tokens are not visible through the API, take up context, are billed as output tokens and count toward the output-token limit, so a response can end as incomplete before any visible text. Anthropic documents that thinking tokens are billed as output and count toward the maximum-token limit, that the thinking text shown is a summary and never the raw chain of thought, and that asking for step-by-step reasoning inside schema-constrained output may trigger a refusal; it advises asking for a short explanation instead. Google documents that thought summaries are optional and that billing uses the full thought tokens. Check the current documentation.
Direct prompting or stepwise instructions
Compare direct prompting with explicit stepwise instructions. "Think step by step" is not a universal booster. Here are three versions of the same decision prompt, each introduced as a prompt to try on the same cases.
Prompt:
Direct: Decide the refund using rules R1 and R2. Return JSON with decision, refund and a
rationale of at most 25 words.Prompt:
Stepwise: Step 1, list the two dates. Step 2, count the days. Step 3, compare with the 30-day
rule. Step 4, apply the fee to opened units. Show each step, then return the JSON.Prompt:
Outcome: Goal: a correct refund decision. Constraints: use only R1 and R2 and the message; use
exact quotes as evidence. Output: JSON with decision, refund, evidence, rationale (25 words).| Situation | Usual starting point |
|---|---|
| Model with no thinking mode, multi-step task | Stepwise instructions or a short reasoning request may help; test them |
| Model that deliberates before answering | Outcome version: goal, constraints, output contract, no scripted steps |
| Any model, steps that code can do | Move the steps into code, as in the chain above |
Provider note (as of 2026-10-12): OpenAI's reasoning guide recommends a clear goal, strong constraints and an explicit output contract, and advises against prescribing every intermediate step. Anthropic's guide prefers general instructions over prescriptive steps, and treats manual chain-of-thought as a fallback when thinking is off. Google's guide says it is generally not necessary to have the model outline or detail its reasoning steps in the returned response. A 2025 study (Meincke et al.) of earlier models found a small average gain from chain-of-thought on non-reasoning models, with less consistent answers and more tokens, and marginal gains at best on reasoning models. Read that as a direction, not as numbers for your model. Check the current documentation.
The table is a starting point, not a verdict. Pick one version, run it on a fixed set of cases, and compare; the next page, Reasoning Trade-offs: Stepwise Prompts, Checks, Stopping Rules and Cost, shows how to measure accuracy and cost on the same cases.
Where this shows up at work
Refund and claims desks, invoice approval and eligibility checks all combine rules with facts. Teams that do this well keep the rules in code or in a reviewed rule list, let the model read messy text into a fixed record, and keep the decision traceable with a rule id and quotes. A reviewer can then open a case and check the evidence in seconds.
Common mistakes
- Using one big prompt for a multi-step decision. A mistake in any step is hidden. Split the task and check each step's output.
- Asking a model to do arithmetic or date maths it could leave to code. Use a program for sums, dates and rules that are exact.
- Treating a written rationale as proof. It is generated text. Ask for rule ids and exact quotes, and verify them.
- Pasting "think step by step" into every prompt. It costs tokens, may not help, and may conflict with a model's own thinking mode. Test it on your cases.
- Over-structuring easy tasks. A one-step task with a clear output needs a direct instruction.
Try it yourself
Use the code from this page; the blocks share one namespace. The exercises revisit Summarising and Extracting: Summaries, Key Facts and Evidence from the Beginner tutorial and the provider-difference checks from Provider Differences and Portability: Reading Guides, Testing Across Models.
- Easy. Rate these three tasks by steps and error cost, then call
routefor each: "Translate a greeting" (1, low), "Check a payslip total against a policy" (3, high), "Summarise a meeting" (1, low). - Medium. Add a required field
currency(a string of three capital letters) toSTAGE1. Runproblemson the output oftoy_extractand say what you would change in the extraction prompt. - Hard. Design a decomposition for "approve or reject a travel expense claim" with these parts: read the claim into a record, look up the limit, convert to one currency, compare, and write a note. Write it as a
SUBTASKSdictionary, print the rounds, and mark which subtasks should be code.
Answers
Easy. Expected designs: a greeting is a direct instruction; the payslip check is explicit subtasks with an independent check and human review; the meeting summary is a direct instruction. Run it to confirm:
for steps, cost in ((1, "low"), (3, "high"), (1, "low")):
print(route(steps, cost))direct instruction
explicit subtasks + independent check + human review
direct instructionPass checklist: you counted dependent steps, not words; you gave the payslip the strongest design because an error costs more there.
Medium.
STAGE1["currency"] = lambda v: isinstance(v, str) and re.fullmatch(r"[A-Z]{3}", v) is not None
print(problems(toy_extract(MESSAGE), STAGE1))['missing: currency']Pass checklist: the problem list names exactly the missing field; you decided that the extraction prompt should say which currency symbols or words map to a code, and what to return when the currency is not stated (for example a null that stops the chain for a person to decide).
Hard. One possible solution:
CLAIM = {
"read": ("model", []),
"limit": ("code", []),
"convert": ("code", ["read"]),
"compare": ("code", ["convert", "limit"]),
"note": ("model", ["compare"]),
}
for i, batch in enumerate(rounds(CLAIM), 1):
print(f"round {i}:", ", ".join(f"{n} ({CLAIM[n][0]})" for n in batch))round 1: limit (code), read (model)
round 2: convert (code)
round 3: compare (code)
round 4: note (model)Pass checklist: reading the claim and the limit lookup are independent and share round 1; conversion, comparison and the limit lookup are code because they must be exact; only reading the messy text and writing the note use a model; there are no cycles, and each model step has an output schema in front of the next step.
Summary
- Simple generation can be judged by reading; multi-step reasoning fails quietly and needs checks at each step. Choose the design from step count and error cost.
- Use a direct instruction for a simple task. Split a hard task into subtasks with written dependencies, and give exact work such as dates and money to code.
- Define a small schema for each intermediate result and stop the chain at the first bad field.
- Ask for a short rationale with rule ids and exact quotes, and verify what can be verified; visible text is not a recording of hidden reasoning.
- "Think step by step" is a tool for some models, not a rule. Test direct, stepwise and outcome-focused versions on your own cases.
Next: Reasoning Trade-offs: Stepwise Prompts, Checks, Stopping Rules and Cost compares plans and checklists, adds independent checks, and measures accuracy and cost on the same task set.

