04.3 Reasoning Prompts: Chain-of-Thought and Friends

Understand LLMsLesson 3 of 1211,492 words10 parts
Module 04 · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12

Some prompts ask a model for an answer. Reasoning prompts ask it to show its working first — or, on today's reasoning models, simply get out of the way and let the model think. This lesson covers the whole family: chain-of-thought (CoT) prompting in its zero-shot and few-shot forms, structured and tagged reasoning you can parse, self-consistency voting, decomposition, self-refinement and verification prompts, the ordering question of answer-first versus reasoning-first, and the bigger search-based techniques (tree-of-thought, ReAct, program-of-thought) that lead into agents. It then answers the question every engineer now faces — do you still need CoT prompts when the model already thinks? — with what OpenAI, Anthropic and Google actually document, plus the costs, failure modes and a minimal test loop for deciding per task.

What you'll learn

  • What chain-of-thought prompting is, where it came from, and why writing intermediate steps out helps a model at all
  • Every CoT variant that matters in production: zero-shot "think step by step", few-shot worked examples, numbered-step and scratchpad prompts, plan-then-solve, self-consistency, least-to-most decomposition, self-refine, verification prompts, and answer-first vs reasoning-first ordering
  • How to structure a reasoning prompt so the working and the final answer are cleanly separable and parseable
  • What OpenAI, Anthropic and Google document about prompting reasoning models, and when explicit CoT prompts still earn their keep
  • Why the reasoning a model shows you — or claims — may not be the real reason for its answer, and what that means for audit and UX
  • The real costs: output tokens for working, time-to-first-answer, and streaming only the answer
  • Where CoT helps (arithmetic, multi-step logic, planning, code) and where it hurts (extraction, format-sensitive output, ambiguous classification)
  • Working code: a tolerant parser for tagged reasoning, a majority-vote self-consistency implementation, and a minimal with/without-CoT test loop you can run without API keys
  • The research frontier — tree-of-thought, graph-of-thought, ReAct, program-of-thought, prompt chaining — when each is worth the complexity, and a quick tour of the other named techniques (step-back, analogical, generated-knowledge, self-ask) you'll still meet in the wild

What you don't need

  • API keys. The runnable samples are pure Python; the provider calls are labelled illustrative and you can substitute any model or a recorded reply.
  • How reasoning models work internally or how to set their thinking controls — that's lesson 02.8, which this lesson links to rather than repeats.
  • Tool calling or agent loops — ReAct and program-of-thought are previews; Module 08A owns them.

Setup

The runnable samples need only Python 3.11+ (standard library). For the provider-call illustrations, the Module 03 SDKs apply (openai, anthropic, google-genai, python-dotenv; compatibility note in lesson 04.1's Setup). If you haven't set up the shared llm-apis project yet, see lesson 03.1, Part 4; otherwise:

bash
uv init cot-prompts --bare --python 3.13 && cd cot-prompts
uv add openai anthropic google-genai python-dotenv
# or: pip install openai anthropic google-genai python-dotenv

Provider samples read keys from .env (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY). No keys? Every technique here has a pure-Python part you can run today — and lesson 03.1, Part 12 covers a free local stand-in if you want real model calls without a hosted key.


What you must be able to do after this lesson#

  • Write a chain-of-thought prompt whose working and final answer can be separated
  • Decide when explicit reasoning helps and when it hurts
  • Explain why shown reasoning may not be the real reason for an answer
  • Estimate the token and latency cost of reasoning
  • Run a with and without reasoning test on a small task

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Just add 'let's think step by step'." Part 1 and Part 3
"The model reasoned its way to the wrong answer." Part 9: Failure modes and 02.10, Part 6
"We need the reasoning shown to the user." Part 4
"Why is the answer taking 30 seconds?" Part 5: Costs and latency
"Should this task use CoT at all?" Part 6: Task suitability
"How do we parse the answer out of the thinking?" Part 7.1
"Sample it five times and take the majority." Part 7.2
"The model's explanation doesn't match what it did." Part 4.3
"Is this still needed now that models think?" Part 3
"Should we use a tree search or just call the model again?" Part 8

Part 1: What chain-of-thought prompting is#

1.1 The idea in one sentence#

Chain-of-thought (CoT) prompting is the practice of getting a model to write out intermediate reasoning steps — the working — before it commits to a final answer.

text
Direct prompt:
  A shop sells pens in packs of 3 for $2. How much do 12 pens cost?

CoT prompt:
  A shop sells pens in packs of 3 for $2. How much do 12 pens cost?
  Think step by step, then give the final answer.

With the CoT version, the model writes something like "12 pens is 12 ÷ 3 = 4 packs. 4 packs × $2 = $8. Final answer: $8." — and it gets the question right far more often.

1.2 Why writing steps out helps#

The mechanism is the same one lesson 02.8, Part 1 explains for reasoning models, applied through the prompt instead of the weights:

  • An LLM produces one token per forward pass (02.5, 1.2). Every token it writes is fed back in as input for the next one. Written-out steps are scratch paper: each extra token is one more forward pass of computation the model can spend on the problem, and each intermediate result stays visible for the steps that follow.
  • Without written steps, a multi-step problem must be solved inside a single forward pass — like being asked a long-division problem with no paper. The model can only do what fits in its immediate pattern completion.
  • CoT doesn't add knowledge or new computation. It restructures the computation the model already does into a longer, shallower sequence of predictions it is good at, instead of one deep prediction it is bad at.

1.3 The original results#

The technique has a precise research lineage you should know by name:

Year Paper What it showed
2021 Nye et al., Show Your Work: Scratchpads for Intermediate Computation Training a model to write intermediate steps into a "scratchpad" before the answer dramatically improved arithmetic accuracy — the existence proof that intermediate computation helps
2022 Wei et al., Chain-of-Thought Prompting Elicits Reasoning in Large Language Models (NeurIPS 2022) A few worked examples containing step-by-step reasoning (about 8 exemplars) lifted a 540B-parameter model to state-of-the-art on GSM8K grade-school maths — roughly 18% to 57% accuracy — and helped on commonsense and symbolic tasks too
2022 Kojima et al., Large Language Models are Zero-Shot Reasoners (NeurIPS 2022) You don't even need examples: appending "Let's think step by step" to a prompt took MultiArith accuracy from about 18% to about 79% on sufficiently large models
2022 Wang et al., Self-Consistency Improves Chain of Thought Reasoning (ICLR 2023) Sampling many reasoning paths and taking a majority vote added another large gain on top of CoT (about +18 points on GSM8K)
2022 Zhou et al., Least-to-Most Prompting (ICLR 2023) Decompose a hard problem into easier sub-problems solved in sequence; on the SCAN compositional benchmark, 14 exemplars reached ~99% where plain CoT got ~16%
2022 Yao et al., ReAct (ICLR 2023) Interleave reasoning with actions (tool calls, searches) — the seed of modern agents
2023 Yao et al., Tree of Thoughts (NeurIPS 2023) Search over multiple reasoning branches with self-evaluation; Game of 24 went from ~4% (CoT) to ~74%
2023 Madaan et al., Self-Refine The same model critiques and revises its own output iteratively, no training needed
2024 Besta et al., Graph of Thoughts (AAAI 2024) Generalize the chain to an arbitrary graph of reasoning steps
2024 Sprague et al., To CoT or not to CoT? (ICLR 2025) The sober modern result: CoT's gains are concentrated on maths and symbolic reasoning; on general knowledge tasks (MMLU) direct answering is about as accurate — unless the problem contains symbolic operations

Two cautions about these numbers, taught throughout this module:

  • They were measured on 2022–2024-era models (PaLM, GPT-3, LaMDA-class, GPT-4). Today's models reason internally by default (02.8), so these results describe what prompted reasoning can do — and what trained reasoning does far better.
  • Even then, CoT helped mainly on multi-step symbolic tasks. Sprague et al.'s meta-analysis is the clearest statement of that, and Part 6 turns it into a decision table.

1.4 What CoT is not#

Before the toolkit, three things CoT is not:

  • ❌ Not a knowledge source. Reasoning reorganizes what the model knows; it cannot produce facts it never learned (02.8, 11.3). If the answer isn't derivable from the prompt and the weights, longer thinking won't save it.
  • ❌ Not a guarantee. A fluent chain of reasoning can reach a wrong answer confidently — 02.10, Part 6 catalogues the failure modes, and Part 9 covers the CoT-specific ones.
  • ❌ Not free. Every reasoning token is an output token: billed, slow, and visible to your parser. Part 5 prices it.

Part 2: The CoT toolkit#

Each technique below is taught with what it is, when it helps, when it hurts, what it costs, and how to test it — the module-wide pattern.

2.1 Zero-shot CoT: "Let's think step by step"#

The cheapest form: no examples, just an instruction to reason. Kojima et al.'s finding was that a single appended sentence — "Let's think step by step" — elicits reasoning on large models.

text
A jacket originally priced at $80 is on sale for 25% off, and then a
further 10% student discount applies at checkout. What is the final price?
Let's think step by step, then give the final answer.

Why it works: the phrase "think step by step" is in the model's training distribution millions of times over (worked solutions, tutorials, textbooks). It acts as a retrieval cue for reasoning-shaped text, which — per the mechanism in 1.2 — gives the answer more computation to stand on.

Variants that work the same way: "Explain your reasoning, then answer", "Show your work." They all trigger the same behaviour — the reliable lever is asking for the working, however you phrase it.

When it helps: arithmetic, multi-step word problems, logic puzzles, planning, code reasoning — on non-reasoning models, or reasoning models with thinking reduced/off (02.8, 11.2).

When it hurts:

  • On reasoning models that already think: redundant — they reason internally whether you ask or not, and asking them to also write reasoning into the answer makes them pay twice (or get declined; 3.3).
  • On extraction, classification and formatting tasks: the model may "reason" about things that have one right answer, add latency, and break your output format. Part 6.
  • On small or weak models: they produce plausible-looking but wrong reasoning, which is worse than a clean wrong answer because it's harder to catch.

Cost: every reasoning token is an output token — typically the most expensive token class. A 200-token answer preceded by 800 tokens of working costs ~5× the answer alone.

2.2 Few-shot CoT: worked examples with reasoning#

Wei et al.'s original finding: include 2–8 exemplars that each show question → reasoning → answer, and the model imitates the pattern on new questions.

text
Q: A rope 60 m long is cut into pieces of 4 m each. How many pieces?
A: 60 ÷ 4 = 15 pieces.

Q: Tom has 3 bags with 12 marbles each. He gives away 10. How many left?
A: 3 × 12 = 36 marbles. 36 − 10 = 26 marbles left.

Q: A shirt costs $45 after a 10% discount. What was the original price?
A:

The model continues: "Let the original price be x. Then x − 0.10x = 45, so 0.9x = 45, so x = 50. Original price: $50."

Why examples beat the bare phrase: they demonstrate the style of reasoning you want (how detailed, what notation, how the answer is formatted, how edge cases are handled), not just that reasoning should happen. This is in-context learning doing its job — 02.4 explains the mechanism; 04.2 owns example selection in depth.

Rules of thumb (cross-checked against provider guidance in Part 3):

  • 2–8 exemplars is the typical useful range; diminishing returns after ~8, and each exemplar is input tokens on every call.
  • Exemplars must match your instructions exactly — inconsistent examples teach inconsistency. OpenAI's reasoning guide warns that discrepancies between prompt and examples produce poor results.
  • Keep them diverse: different surface forms, different reasoning paths, at least one edge case — otherwise the model copies the exemplar's wording and structure (the over-copying problem 04.2 covers).
  • Wrap reasoning in consistent delimiters (A: for the answer, or explicit <thinking>/<answer> tags) so both the model and your parser know where working ends.
  • Examples work with reasoning models too — Anthropic's docs note worked examples "shape how Claude approaches similar problems in its own thinking blocks" — but they're usually unnecessary there.

2.3 Structured CoT: numbered steps, scratchpads, plan-then-solve#

Free-form "think step by step" produces free-form working. Three ways to impose structure:

Numbered steps. Ask for an explicit sequence. Providers' own guidance recommends numbered lists when order matters (Anthropic's best-practices page says exactly this). The benefit isn't cosmetic: numbered steps create natural checkpoints the model can verify against, and they parse cleanly.

text
Solve the problem in exactly these steps:
1. List the given quantities.
2. Write the relationship between them as an equation.
3. Solve the equation.
4. Check the answer against the original question.
5. Give the final answer on a line starting "Answer:".

Scratchpad tags. A named region for working, separate from the answer:

text
Work through the problem inside <scratchpad> tags.
Put only the final answer inside <answer> tags.

This is the simplest form of the tagged-CoT pattern in 7.1. It matters because the tags are your parsing contract: everything before <answer> is working (show it, hide it, log it — your choice), everything inside is the result your code consumes.

Plan-then-solve. Two-phase prompting: first produce a plan, then execute it. This is a lightweight version of decomposition (2.5) and maps onto what reasoning models do internally — but it works on non-reasoning models too:

text
First, write a short plan for solving this problem (3-5 bullet points).
Then solve it following your plan.
Then give the final answer.

Plan-and-Solve prompting (Wang et al., 2023, arXiv:2305.04091) formalized this for zero-shot use and reported gains over plain zero-shot CoT on arithmetic and commonsense benchmarks, mainly by reducing missing-step errors — the plan forces the model to enumerate the steps before it starts computing.

2.4 Self-consistency: sample several, vote#

Wang et al.'s self-consistency method: instead of one greedy CoT path, sample N independent reasoning paths (with temperature > 0 for diversity) and return the most common final answer.

flowchart LR
    Q["Question"] --> C1["Chain 1 → $50"]
    Q --> C2["Chain 2 → $50"]
    Q --> C3["Chain 3 → $45"]
    Q --> C4["Chain 4 → $50"]
    Q --> C5["Chain 5 → $50"]
    C1 & C2 & C3 & C4 & C5 --> V["Majority vote → $50"]

Why it works: a complex problem admits many reasoning paths to the same correct answer, while wrong answers scatter across many different wrong values. Voting cancels the scatter. 02.8, 11.1 shows the simulation: voting helps enormously when errors are varied, and actively hurts when the model has a systematic misconception (one popular wrong answer beats the right one — then the vote converges confidently on the wrong answer).

When to use it:

  • Answers you can compare exactly: numbers, categories, short strings, yes/no. It breaks down on open-ended prose (how do you "vote" on two different paragraphs?).
  • Tasks where single-sample accuracy is mediocre but errors are random-ish — maths word problems, classification with subtle rules, extraction.
  • Not as a default: it multiplies cost by N. 7.2 implements it properly with bounded parallelism.

Cost: N× the calls. But they parallelize — with bounded concurrency (03.9, Part 4), latency grows far less than cost. And on batch APIs (03.9) the same N samples can run at a fraction of the price for offline work.

Honest caveat: on reasoning models, diversity comes from the model's own sampling, not from your temperature knob (many reasoning models reject or ignore temperature — 02.5 Part 6). Self-consistency still works if you get any diversity — different reasoning paths happen naturally — but you can't always control it. Test whether your N samples actually differ before trusting the vote.

2.5 Decomposition: least-to-most and plan-and-solve#

Some problems are too hard for one CoT pass: the model must solve sub-problem B correctly given sub-problem A's answer, and errors compound. Decomposition splits the task:

Least-to-most (Zhou et al., 2022): decompose the problem into a sequence of sub-problems ordered from easiest to hardest, solve them in order, feeding each answer forward.

text
Problem: If a train travels 60 km/h for 2.5 hours, then 80 km/h for 1.5
hours, what is its average speed for the whole trip?

Decompose into sub-problems:
1. How far does the train go in the first part? (60 × 2.5)
2. How far does it go in the second part? (80 × 1.5)
3. What is the total distance?
4. What is the total time?
5. What is the average speed? (total distance ÷ total time)

Solve each in order, using previous answers.

The paper's striking result: on the SCAN benchmark (mapping natural language to action sequences), 14 exemplars with least-to-most reached ~99% accuracy on the hardest length split, versus ~16% for standard CoT — because each sub-problem stayed within the difficulty the exemplars demonstrated.

Plan-and-solve (2.3): the model writes the plan itself rather than you decomposing by hand. Easier to use, less control.

When decomposition beats one big CoT:

  • Problems with clear sequential dependencies (multi-leg journeys, multi-stage pipelines, "first X, then Y, then Z").
  • When you can check each sub-answer — you get N validation points instead of one. This is the real engineering win: decomposed outputs are individually verifiable, and a wrong sub-answer can be retried without redoing the whole chain.
  • Long documents: decompose by section ("summarize each section, then combine") — the map-reduce pattern 04.8 covers for summarization.

When it loses:

  • Latency: N sequential calls. If sub-problems are independent, parallelize them (03.9); if dependent, you can't.
  • Error propagation: a wrong sub-answer poisons everything downstream — same compounding problem as agents (02.10, 18). Mitigate by having each step output structured results you validate.
  • Overhead: for problems a single CoT handles, decomposition is ceremony.

2.6 Self-refine and critique-and-revise#

Self-Refine (Madaan et al., 2023): the same model generates an output, then critiques it, then revises — iterating without any training data or external feedback.

text
Call 1 (draft):   "Write a product description for a 500 ml insulated bottle."
Call 2 (critique): "Here is a draft: <draft>. List its specific weaknesses
                     against these criteria: accuracy, benefit-led, under 60
                     words, no jargon. Be harsh and specific."
Call 3 (revise):  "Revise the draft to fix every weakness you listed.
                     Output only the revised description."

Why it can work: generating a critique is an easier task than generating a good answer from scratch — the model can "see" problems in existing text it couldn't avoid when writing cold. Iterating gives it multiple chances.

The honest caveat — this is the most oversold CoT-family technique:

  • Self-Refine's reported gains (~20% average across 7 tasks) were measured mostly on tasks where the model could recognize its own errors — sentiment reversal, dialogue, code readability. On maths the gains were near zero, because the model usually judged its own wrong answer fine (the paper reports "everything looks good" feedback for 94% of ChatGPT's maths attempts).
  • Huang et al. (2023), "Large Language Models Cannot Self-Correct Reasoning Yet" showed that intrinsic self-correction — asking the model to check its own reasoning with no new information — can degrade performance: the model "corrects" correct answers into wrong ones. 02.10, 6.6 covers this.
  • The pattern that does work: self-refine with external grounding — the critique step is fed objective evidence (a failing test, a schema validation error, a contradicting source, a rubric with concrete criteria). Anthropic's own guidance reflects this: "Before you finish, verify your answer against [test criteria]" works because the criteria are external.

Engineering rule: self-refine is a loop, and loops need termination conditions. Cap iterations (2–3 is typical), define "good enough" explicitly, and always keep the best-scoring version — not just the last one.

2.7 Verification prompts#

Two distinct things get called "verification":

Ask the model to check its own work before answering. Append a verification step:

text
Solve the problem step by step.
Before giving the final answer, verify each step: recheck the arithmetic,
confirm each quantity was used correctly, and check the answer is in the
units asked for. Then give the final answer.

This catches execution errors (arithmetic slips, dropped constraints) reasonably well — it's the prompt-level version of what reasoning models do internally. Anthropic documents this as "ask Claude to self-check" with the caveat that on Claude Opus 5 it can cause over-verification (Part 3).

Verify with something that isn't the model. The stronger pattern: the model produces an answer and the evidence/checks, and your code or a tool verifies. "Let's Verify Step by Step" (Lightman et al., 2023) showed process-level verification beats outcome-level verification for training reward models — the same intuition applies at prompt level: checking each step catches errors that checking only the final answer misses.

text
For each step of your solution, state the claim and the check you ran
(e.g. "recomputed 17 × 24 = 408 by hand", "verified the constraint X ≤ 500").
If a check fails, fix the step before continuing.

The best version: ask the model to produce machine-checkable artifacts — the equation it solved, the SQL it wrote, the test it ran — and verify those in code. That's where structured output (03.4) and tools (Module 08A) take over from prompting.

2.8 Ordering: answer-first vs reasoning-first#

Which should come first in the output — the answer or the reasoning?

Reasoning-first (standard CoT) is the default and the safer choice for accuracy:

  • The answer is generated conditioned on the working, so errors in early steps propagate visibly rather than being hidden behind a committed guess.
  • Research on "preemptive answers" (ACL 2024 Findings) found that giving the model an answer before it reasons significantly degrades reasoning — up to ~62% performance loss — and if the preemptive answer is wrong, the reasoning tends to rationalize it. The paper's title says it plainly: preemptive answers are an attack surface. The planted answer can come from a malicious user or from injected content hiding inside the data being reasoned over — so this is also a prompt-injection vector (hygiene preview → Module 12).
  • "Order Matters in Hallucination" (2024) showed answer-first-then-explain produces post-hoc justifications: the model commits to an answer, then generates reasoning that supports it — the explanation becomes a rationalization, not a derivation.

Answer-first has legitimate uses:

  • Speed UX: the user sees the answer immediately; reasoning streams after as justification. Bad for accuracy on hard problems — the answer was guessed before the work.
  • Calibration: asking for the answer first, then asking the model to check it ("now verify your answer") can surface cases where reasoning contradicts the guess — but see the self-correction caveat in 2.6.
  • Classification/extraction: where the "reasoning" is trivial, answer-first avoids pointless deliberation.

In prompt form the two orderings are just different instruction shapes:

text
Reasoning-first (accuracy default):
  Solve the problem step by step inside <thinking> tags, then give ONLY
  the final answer inside <answer> tags.

Answer-first (UX speed, trivial tasks):
  Give the final answer on the first line. Then justify it in 2-3
  sentences — the justification comes after the answer, not before.

On a hard problem the answer-first version produces the visible answer before any working exists — the trailing justification then rationalizes a guess rather than deriving one, which is the failure the two papers above measured. On trivial tasks — extraction, classification — there is no real reasoning to protect, so answer-first is a pure UX win: the user sees the result immediately and the justification streams in after.

The engineering answer regardless of order: keep reasoning and answer in separate, parseable regions — tags, sections, or separate API fields — so your code never has to guess where one ends and the other begins. 7.1 shows the parser.

Part 3: CoT on reasoning models — the modern question#

This is the question that changed in 2024–2026: the models you're probably calling already reason. Do you still write "think step by step"?

3.1 What the providers document (verified November 2026)#

Provider What their docs say about prompting reasoning/thinking models
OpenAI (reasoning best practices, prompt engineering, reasoning guide) "Avoid chain-of-thought prompts" — "Since these models perform reasoning internally, prompting them to 'think step by step' or 'explain your reasoning' is unnecessary." Keep prompts simple and direct; give a clear goal, strong constraints and an explicit output contract "without prescribing every intermediate step"; try zero-shot first, then few-shot if needed (examples must align closely with instructions); be specific about the end goal and success criteria. Their analogy: a reasoning model is "a senior co-worker" you give a goal to; a GPT model is "a junior coworker" needing explicit instructions.
Anthropic (prompting best practices) "Prefer general instructions over prescriptive steps" — "a prompt such as 'think thoroughly' often produces better reasoning than a hand-written step-by-step plan. Claude's reasoning frequently exceeds what a human would prescribe." Manual CoT is documented as a fallback: "When thinking is off, you can still encourage step-by-step reasoning by asking Claude to think through the problem before it answers, and to put the final answer in <answer> tags so you can extract it." On Claude Fable 5.2/5.1/5, Opus 5.5/5 and Sonnet 5.5, asking for reasoning in <thinking> tags "might be declined" — use thinking at lower effort instead. They also document "ask Claude to self-check" (with an over-verification caveat on Opus 5).
Google (prompting strategies) "Gemini 2.5 and 3 series models automatically generate internal 'thinking' text to improve reasoning performance. As such, it's generally not necessary to have the model outline, plan, or detail reasoning steps in the returned response itself." For heavy reasoning, "simple requests like 'Think very hard before answering' can improve performance, though at the cost of extra thinking tokens." (Note: their Gemini 3 template still ends with "Remember to think step-by-step before answering" — the docs are not fully self-consistent here; the dedicated section is the clearer statement.)
OpenRouter (reasoning tokens docs) One reasoning parameter (effort, max_tokens, enabled, exclude) normalised across providers — a pointer to 02.8, 3.4, not a prompting guide.

The convergence is remarkable: all three major providers independently document the same advice — don't script the reasoning on models that reason; give goals, constraints and output contracts instead. This isn't a fad; it's the documented behaviour of the current model generation.

3.2 The effort/thinking controls — pointer to 02.8#

When the model reasons internally, the lever is no longer prompt wording — it's the API's reasoning controls. Lesson 02.8, Part 3 owns them completely: effort levels, thinking budgets, visibility (summaries vs hidden vs encrypted), usage accounting, and per-provider samples. The one-paragraph version:

Provider Amount control Off switch Visibility Billed as
OpenAI (Responses) reasoning.effort (none–max, model-dependent) effort: "none" where supported reasoning.summary output tokens
Anthropic (Messages) output_config.effort + thinking: {"type": "adaptive"} {"type": "disabled"} on some models only thinking.display: summarized/omitted output tokens
Gemini (generate_content) thinking_config.thinking_level (or thinking_budget on 2.5) thinking_budget=0 on some models include_thoughts=True output tokens
OpenRouter reasoning.effort / reasoning.max_tokens / enabled effort: "none" or enabled: false where not mandatory reasoning items returned by default; exclude: true hides them (Chat Completions only) output tokens

The rule: prompt wording controls whether the model writes reasoning into the visible answer; API settings control how much it thinks internally. Don't confuse them — they're independent dials, and you usually want the first off and the second tuned.

Two practical consequences, both from Anthropic's model-specific page for Claude Sonnet 5.5 (verified November 2026; other models may differ, so check the page for yours):

  • To get less thinking, lower the effort level. The page says that asking in the system prompt to think less "doesn't reliably reduce its thinking". A sentence in the prompt is a hint; the API setting is the control.
  • A JSON-only answer can starve a multi-step task of thinking. With structured outputs the response text holds only the JSON, so the model can work the problem out only in its thinking, and at low or medium effort it often skips that thinking on tasks such as totalling figures or applying a rule. The page's fixes are a closing system-prompt line, "Think the problem through before you answer.", or a higher effort level; if you ask for JSON in the prompt instead of using structured outputs, the model may reason in the response text first, so parse the last JSON value rather than assuming the whole response is JSON. A schema with a reasoning or evidence field before the answer field (03.4) is the provider-neutral version of the same idea: it gives the model somewhere to work. Whatever you choose, check the result on your own cases and treat a response cut off by max_tokens as a failure even when the JSON parses.

3.3 When explicit CoT still earns its keep#

Despite the provider guidance, prompt-level CoT is far from dead. It still earns its place in four situations:

  1. Non-reasoning models. Small/fast/cheap models, older models, distilled models without thinking, open-weight models run locally, and any model with reasoning explicitly off. Here "think step by step" is the only way to get working — and it works (the 2022–2024 results). This is the largest remaining use case: cost-sensitive high-volume routes.
  2. Reasoning-off configurations. A reasoning model with effort: "none" or thinking disabled behaves like a standard model — and Anthropic explicitly documents the manual-CoT fallback for exactly this case (3.1).
  3. Auditability and user-visible working. When you want the reasoning shown — for a user to inspect, for a compliance trail, for debugging — you must ask for it in the answer, because internal thinking is hidden/summarised (Part 4).
  4. Format control. Sometimes you want reasoning in a specific shape — numbered steps, a plan-then-solve structure, tagged regions your parser expects — that internal thinking won't give you. The visible answer can carry a structured justification even when thinking stays internal.

The test: if the model already thinks and you don't need to see the thinking, don't ask for it. If the model doesn't think (or you've turned it off), or you need the working visible, CoT prompting is your tool.

3.4 Outdated folklore — what to unlearn#

The 2023-era prompt-engineering canon is full of CoT advice that is now wrong or harmful on current models. Call them out explicitly:

Folklore Reality on current models
"Always add 'let's think step by step'" On reasoning models it's redundant (they think anyway) and can hurt — OpenAI says such prompting "can sometimes hinder" performance; Anthropic says asking for <thinking> tags "might be declined" on flagship models
"More reasoning words = better: 'think very carefully', 'take a deep breath'" Ritual phrases don't add computation; they add tokens. Google's "think very hard" is the documented exception — it does steer thinking depth, at the cost of thinking tokens — but it's a steering phrase, not a ritual
"Show your full reasoning so users trust the answer" The shown reasoning may be unfaithful (4.3); a confident wrong trace is worse than no trace
"Ask the model to explain why it's right, then trust the explanation" Explanations are generated text, not audit trails — 02.10, 6.5
"Chain-of-thought always improves accuracy" Sprague et al. (2024): mainly maths/symbolic; on general knowledge tasks direct answering is about as good (Part 6)
"Give the model step-by-step instructions for complex tasks" Reasoning models plan better than humans prescribe — "prefer general instructions over prescriptive steps" (Anthropic); hand-written procedures can constrain the model's better plan

Part 4: Reasoning users and auditors can see#

Deep-dive

4.1 Visible reasoning on hosted models#

When you want reasoning visible, there are two sources:

Internal thinking, surfaced by the API (reasoning models): OpenAI reasoning.summary, Anthropic thinking.display: "summarized", Gemini include_thoughts, OpenRouter's reasoning field — all covered in 02.8, Part 4. These give a readable summary of the model's actual thinking, billed at output rates, and — on hosted closed models — never the raw trace.

Prompted reasoning in the answer (any model): ask the model to write its working into the response, in tags your UI can render. This is the only option on non-reasoning models, and the only way to get your chosen structure on reasoning models.

text
Show your reasoning inside <thinking> tags, then give the final answer
inside <answer> tags. Keep the thinking concise: 3-6 short steps, no
restating the question.

The tags do double duty: your UI shows <thinking> in a collapsible "How I got this" panel, and your parser extracts <answer> for downstream use. 7.1 implements the parser.

4.2 Prompting for explanations on non-reasoning models#

On a standard model, "explain your reasoning" produces working that's part of the answer — no separation, no control. To get a usable explanation:

  • Ask for justification, not transcript. "Give a short justification of the answer" produces prose meant for humans; "show all your reasoning" produces a chain that may include dead ends and abandoned approaches. For users, the former is almost always what you want.
  • Constrain the shape. "2-4 sentences", "bullet the key factors", "cite the specific clause" — unbounded explanations ramble.
  • Separate concerns. If the answer is machine-consumed and the explanation is human-consumed, generate them as different fields (structured output, 03.4) or different sections — never ask code to parse prose out of an explanation.

4.3 Why shown reasoning may be unfaithful#

This is the most important honest point in the lesson, and 02.8, 4.3 owns the research detail. The summary:

  • The reasoning a model writes is not guaranteed to be the real reason for its answer. Turpin et al. (2023) showed models follow planted biases while writing plausible explanations that never mention them. Lanham et al. (Anthropic, 2023) showed editing a model's reasoning sometimes doesn't change its answer at all. Chen et al. (Anthropic, 2025) found reasoning models mentioned a planted hint in their reasoning only ~25–39% of the time — and unfaithful reasoning was longer, so length is no signal of honesty.
  • Summaries add another layer. What you see from a hosted API is a summary of the thinking, written by a separate summarizer — two steps removed from the computation.
  • On current Claude models, asking for the raw thinking in the answer can be refused (stop_reason: "refusal", category reasoning_extraction) — 02.8, 7.2.

What this means for using CoT as an explanation:

  • ✅ Fine for debugging and UX — a wrong turn in the trace is often a useful clue, and showing progress during a long wait helps.
  • ❌ Not an audit trail. Don't tell a user "the AI rejected your claim because X" based on the model's own reasoning — it may have decided first and rationalized after. If you need a justification, ask for one in the answer and verify it independently, or make the decision with rules and evidence you control.
  • ❌ Don't parse answers out of thinking blocks — read only the final answer; thinking format can change without notice.

4.4 What that means in practice#

The engineering posture:

  1. Default: hide the working. Show users the answer; keep reasoning for logs/debugging. Users don't need to see 800 tokens of scratch work, and showing it invites them to over-trust a fluent-but-wrong trace.
  2. Offer "show reasoning" as a progressive-disclosure feature, clearly labelled as the model's explanation — not a guarantee. Pair it with citations/evidence when the answer matters (Module 07 for grounded answers).
  3. For compliance/audit needs, don't rely on CoT at all — log inputs, outputs, model version, prompt version, and the decision; if a human must justify, that's a human or a rules engine, not a language model's self-report.

Part 5: Costs and latency#

5.1 Working tokens are output tokens#

Every token of reasoning is an output token: billed at the output rate (several times the input rate), counted in max_tokens/max_output_tokens alongside the answer, and — on reasoning models — whether you see it or not (02.8, 5.1). CoT prompting on a non-reasoning model is the same economics with a visible receipt: the working is right there in the response, priced as output.

The maths is simple and brutal: a task that needs 800 tokens of working + 200 of answer costs ~5× a task that answers directly. Whether that 5× buys accuracy is exactly what Part 10 exists to measure.

5.2 Time to first answer#

CoT delays the first answer token by the length of the working — but not the first visible token if you stream. Two different clocks:

  • Time to first token (any): starts immediately; the model begins writing reasoning right away.
  • Time to first answer token: delayed by however long the working takes — seconds to minutes on hard problems or reasoning models.

For UX, what matters is which the user sees. If reasoning streams visibly (or as a summary), the wait feels productive. If the user stares at a spinner for 30s, it feels broken. 02.8, 5.2 covers the reasoning-model version; the CoT-prompt version is identical in shape.

5.3 Streaming only the answer#

The tagged-CoT pattern (7.1) gives you a clean split that maps onto streaming (03.3):

flowchart LR
    M["Model stream"] --> T{"Inside<br/><answer> tag?"}
    T -- "no (thinking)" --> H["Buffer / show as<br/>'thinking…' progress"]
    T -- "yes" --> A["Stream to user<br/>immediately"]

Practically: accumulate deltas; until you see <answer>, hold them (or display a subdued "reasoning…" indicator); once <answer> opens, stream tokens straight to the UI. You get fast-feeling time-to-answer and a logged reasoning trace — the best of both. 03.3, 6.1 covers how providers structure this for internal reasoning; the tag approach gives you the same control on any model.


Part 6: Task suitability#

6.1 Where reasoning prompts pay off#

Task type Why CoT helps Evidence
Arithmetic & multi-step maths Each step is a separate prediction; working catches slips The original CoT results; Sprague et al. confirm maths is where gains concentrate
Multi-step logic & planning Decomposition makes dependencies explicit ToT, least-to-most results
Code reasoning & debugging Planning + self-checking catches edge cases Anthropic/OpenAI guidance for reasoning models; verify-with-tests pattern
Complex document analysis Cross-referencing, comparing sources OpenAI's documented reasoning-model use cases
Ambiguous classification Short CoT lets the model articulate the deciding factor before committing Test it — gains are real but modest
Constraint satisfaction Working through constraints explicitly Planning tasks

6.2 Where CoT hurts or is wasted#

Task type What goes wrong
Simple extraction (names, dates, fields→JSON) No reasoning needed; the model "thinks" about obvious answers, adds latency, and can break format
Simple classification (sentiment, topic, routing) Same — fast pattern recognition doesn't benefit; Sprague et al. found ~no gain on MMLU-style tasks
Format-sensitive output Long reasoning increases the chance the final format drifts — the model forgets the output contract after 800 tokens of working (9.4)
Factual Q&A Reasoning can't create missing knowledge; it can even talk itself out of a correct recalled fact
Latency-critical UX Autocomplete, voice, live suggestions — users can't wait
High-volume low-value Cost multiplies by volume

6.3 The decision table#

Your situation Do this
Reasoning model, hard multi-step task No CoT prompt. Set effort high/medium; give goal + constraints + output contract (02.8, Part 7)
Reasoning model, easy task No CoT prompt. Effort low/none; simple direct prompt
Non-reasoning model, multi-step task CoT prompt (zero-shot phrase or few-shot examples) + tagged output
Non-reasoning model, simple task Direct prompt. CoT is wasted cost
Need reasoning visible to user/auditor Tagged CoT in the answer (or reasoning summaries on reasoning models)
Need machine-parseable output CoT for the working, structured output for the answer (03.4) — or put reasoning in a separate field
Unsure Test it — Part 10

Part 7: Techniques at API level#

Deep-dive

7.1 Tagged CoT and a tolerant parser#

The workhorse pattern: ask for <thinking> and <answer> regions, then parse them apart. Here's the prompt (works on any chat model — non-reasoning models, reasoning models with thinking off, or reasoning models where you want visible working):

text
<instructions>
Solve the problem inside <thinking> tags: 3-8 short steps, showing the
arithmetic or logic explicitly. Then give ONLY the final answer inside
<answer> tags — no units unless asked, no explanation, one line.
If the problem is ambiguous, state your assumption inside <thinking>.
</instructions>

<problem>
{{QUESTION}}
</problem>

Sending it is a normal chat call — one OpenAI Responses example (the same shape works on Anthropic Messages, Gemini generate_content and OpenRouter Chat Completions; swap the client and message format per 03.2):

python
# cot_call.py — illustrative: needs OPENAI_API_KEY and the openai SDK
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

PROMPT = """<instructions>
Solve the problem inside <thinking> tags: 3-8 short steps, showing the
arithmetic or logic explicitly. Then give ONLY the final answer inside
<answer> tags — no units unless asked, no explanation, one line.
If the problem is ambiguous, state your assumption inside <thinking>.
</instructions>

<problem>
A jacket originally priced at $80 is on sale for 25% off, and then a
further 10% student discount applies at checkout. What is the final price?
</problem>"""

response = client.responses.create(
    model="gpt-6-luna",          # cheap default; use effort "none"/"low" for simple CoT tasks
    reasoning={"effort": "low"}, # reasoning models: keep effort low for tagged-CoT tasks
    input=PROMPT,
)
text = response.output_text
print(text)
Example output · illustrative6 lines
<thinking>
Step 1: 25% off $80 = $20 discount, so price is $80 - $20 = $60.
Step 2: 10% student discount on $60 = $6 discount.
Step 3: $60 - $6 = $54.
</thinking>
<answer>$54</answer>

Now the parser. Models don't always emit perfect tags — missing tags, prose around them, answer-before-thinking, unclosed tags all happen. This tolerant parser handles the common cases and degrades gracefully:

python
# cot_parse.py — pure Python, no dependencies. Run: python3 cot_parse.py
import re
from dataclasses import dataclass

_TAG = re.compile(r"</?(?:thinking|scratchpad|reasoning|answer)\s*>", re.IGNORECASE)
_ANSWER_BLOCK = re.compile(r"<answer\s*>(.*?)</answer\s*>", re.IGNORECASE | re.DOTALL)
_THINK_BLOCK = re.compile(
    r"<(thinking|scratchpad|reasoning)\s*>(.*?)</\1\s*>", re.IGNORECASE | re.DOTALL
)


@dataclass
class TaggedReply:
    reasoning: str      # the working, tags stripped; "" if none found
    answer: str         # the final answer region; whole reply if untagged
    had_answer_tag: bool


def parse_tagged_reply(text: str) -> TaggedReply:
    """Split a model reply into (reasoning, answer).

    Contract: <answer>...</answer> is the result; everything else is working.
    Tolerates missing tags, extra prose, answer-before-thinking, unclosed tags.
    """
    m = _ANSWER_BLOCK.search(text)
    if m:
        answer = _TAG.sub("", m.group(1)).strip()
        # Reasoning = everything outside the answer block, tags stripped
        outside = text[: m.start()] + " " + text[m.end() :]
        reasoning = _TAG.sub("", outside).strip()
        return TaggedReply(reasoning=reasoning, answer=answer, had_answer_tag=True)

    # No <answer> block: look for a thinking region; the rest is the answer
    t = _THINK_BLOCK.search(text)
    if t:
        reasoning = _TAG.sub("", t.group(2)).strip()
        answer = _TAG.sub("", text[: t.start()] + " " + text[t.end() :]).strip()
        return TaggedReply(reasoning=reasoning, answer=answer, had_answer_tag=False)

    # Fully untagged: treat the whole reply as the answer
    return TaggedReply(reasoning="", answer=text.strip(), had_answer_tag=False)


REPLIES = {
    "clean": "<thinking>\n25% off $80 = $20 off, so $60. Then 10% off $60 = $6 off, so $54.\n</thinking>\n<answer>$54</answer>",
    "no tags": "$54",
    "answer only": "<answer>42</answer>",
    "thinking only": "<thinking>hmm, let me see</thinking>probably 7",
    "answer first": "<answer>15</answer>\n<thinking>wait, recheck the division</thinking>",
    "unclosed answer": "<thinking>work work work</thinking><answer>99",
    "prose around": "Here you go! <thinking>3 × 4 = 12</thinking> <answer>12</answer> Hope that helps!",
}

for label, reply in REPLIES.items():
    r = parse_tagged_reply(reply)
    print(f"--- {label} ---")
    print(f"  reasoning: {r.reasoning!r}")
    print(f"  answer:    {r.answer!r}   (tagged={r.had_answer_tag})")
Output21 lines
--- clean ---
  reasoning: '25% off $80 = $20 off, so $60. Then 10% off $60 = $6 off, so $54.'
  answer:    '$54'   (tagged=True)
--- no tags ---
  reasoning: ''
  answer:    '$54'   (tagged=False)
--- answer only ---
  reasoning: ''
  answer:    '42'   (tagged=True)
--- thinking only ---
  reasoning: 'hmm, let me see'
  answer:    'probably 7'   (tagged=False)
--- answer first ---
  reasoning: 'wait, recheck the division'
  answer:    '15'   (tagged=True)
--- unclosed answer ---
  reasoning: 'work work work'
  answer:    '99'   (tagged=False)
--- prose around ---
  reasoning: 'Here you go! 3 × 4 = 12   Hope that helps!'
  answer:    '12'   (tagged=True)

Two honest observations from the output:

  • "unclosed answer" was rescued by accident. With no </answer> the first pattern missed, but the thinking-block fallback caught <thinking>...</thinking> and tag-stripping cleaned the leftover <answer> from the answer text — so it still produced the right split. That's luck, not design: a reply that is only an unclosed <answer>99 would fall through to the untagged path and return the tag as part of the answer. In production you'd add an explicit fallback (if <answer> opens but never closes, take everything after it). This parser is deliberately simple; 04.4 covers robust output parsing in depth.
  • "prose around" shows reasoning picking up surrounding prose — fine for logging, but if you display reasoning to users, trim it.

7.2 Self-consistency with parallel calls#

Self-consistency (2.4) needs N samples and a vote. The vote is pure Python; the calls are provider code. Here's the vote first — runnable:

python
# vote.py — pure Python, no dependencies. Run: python3 vote.py
import re
from collections import Counter


def normalize_answer(text: str) -> str:
    """Canonicalize an answer for voting: strip tags/prose, keep the payload."""
    text = re.sub(r"<[^>]+>", "", text)          # remove XML-ish tags
    text = re.sub(r"(?i)final answer\s*[:\-]?\s*", "", text)
    return " ".join(text.split()).strip().lower()


def majority_vote(answers: list[str]) -> tuple[str, dict]:
    """Return (winner, counts). Ties break to the first-seen answer."""
    counts: Counter[str] = Counter(normalize_answer(a) for a in answers)
    winner = counts.most_common(1)[0][0]
    return winner, dict(counts)


# Simulated replies from 5 parallel calls on the jacket problem
REPLIES = ["$54", "<answer>$54</answer>", "54 dollars", "$54.00", "$45"]
winner, counts = majority_vote(REPLIES)
print("counts:", counts)
print("winner:", winner)
Output2 lines
counts: {'$54': 2, '54 dollars': 1, '$54.00': 1, '$45': 1}
winner: $54

Notice the normalization matters: "$54", "54 dollars" and "$54.00" are the same answer but different strings. normalize_answer catches the easy cases; for real use you'll want task-specific normalization (strip currency symbols, round numbers, map to enum values) — voting on raw strings undercounts agreement.

Now the parallel runner — illustrative (needs a provider key):

python
# self_consistency.py — illustrative: needs OPENAI_API_KEY and the openai SDK
import asyncio
from dotenv import load_dotenv
from openai import AsyncOpenAI

load_dotenv()
client = AsyncOpenAI()

QUESTION = "A jacket originally priced at $80 is on sale for 25% off, then a further 10% student discount. Final price?"
PROMPT = f"""<instructions>
Solve inside <thinking> tags (3-8 short steps), then give ONLY the final
answer inside <answer> tags — one line, no explanation.
</instructions>
<problem>{QUESTION}</problem>"""

SEM = asyncio.Semaphore(5)   # bounded concurrency — see 03.9 Part 4


async def one_sample() -> str:
    async with SEM:
        r = await client.responses.create(
            model="gpt-6-luna",
            reasoning={"effort": "low"},
            input=PROMPT,
            # NOTE: sampling params are model-dependent. Reasoning models may
            # reject/ignore temperature — check 02.5 Part 6. Diversity here
            # comes from the model's own sampling; verify your N replies differ.
        )
        return r.output_text


async def main() -> None:
    replies = await asyncio.gather(*[one_sample() for _ in range(5)])
    for r in replies:
        print("---")
        print(r)
    # winner, counts = majority_vote(replies)   # from vote.py
    # print("winner:", winner, counts)


asyncio.run(main())
Example output · illustrative25 lines
---
<thinking>
25% off $80 = $60. 10% off $60 = $6. $60 - $6 = $54.
</thinking>
<answer>$54</answer>
---
<thinking>
$80 × 0.75 = $60. $60 × 0.90 = $54.
</thinking>
<answer>$54</answer>
---
<thinking>
Discounts: 25% then 10% = 1 - 0.75×0.90 = 1 - 0.675 = 0.325 off. $80 × 0.675 = $54.
</thinking>
<answer>$54</answer>
---
<thinking>
$80 - $20 = $60. $60 - $6 = $54.
</thinking>
<answer>$54</answer>
---
<thinking>
$80 × 0.75 = $60; $60 × 0.9 = $54.
</thinking>
<answer>$54</answer>

All five agree → high confidence. If they'd split 3-2, you'd escalate (higher effort, a verifier, or human review) rather than trust the majority — 02.8, 11.1 shows when voting helps vs hurts.

7.3 A self-refine loop#

Self-refine (2.6) is a loop: draft → critique → revise, with a stop condition. Here's the structure with a stub model so it runs locally — swap llm() for a real client:

python
# self_refine_demo.py — pure Python structure demo (stub LLM + stub scorer)
from dataclasses import dataclass


@dataclass
class Result:
    text: str
    score: float


def llm(prompt: str) -> str:
    """STUB: replace with a real model call. Returns canned text for the demo."""
    if "[[REVISE]]" in prompt:
        return "The bottle keeps drinks cold for up to 12 hours in typical use."
    if "[[DRAFT]]" in prompt:
        return "The bottle keeps drinks cold for 12 hours guaranteed."
    return "[[CRITIQUE]] 'guaranteed' is unverifiable and risky; no benefit-led language; over 60 words not checked."


def score(text: str) -> float:
    """STUB scorer: word cap plus a banned word. Replace with a real rubric or test."""
    s = 1.0 if len(text.split()) <= 60 else 0.0
    if "guaranteed" in text.lower():
        s -= 0.5
    return s


def self_refine(task: str, criteria: str, max_iters: int = 3) -> Result:
    draft = llm(f"[[DRAFT]] the answer for: {task}")
    best = Result(draft, score(draft))   # keep the BEST-scoring version, not the last
    for _ in range(max_iters):
        critique = llm(f"[[CRITIQUE]] this draft against criteria [{criteria}]:\n{draft}")
        if "no issues" in critique.lower():
            break
        revised = llm(f"[[REVISE]] this draft to fix the critique. Output only the revision.\nDraft: {draft}\nCritique: {critique}")
        draft = revised
        s = score(revised)
        if s > best.score:
            best = Result(revised, s)
    return best


out = self_refine(
    "Write a product description for a 500 ml insulated bottle.",
    "accuracy, benefit-led, under 60 words, no jargon",
)
print("final:", out.text, f"(score {out.score:.2f})")
Output1 line
final: The bottle keeps drinks cold for up to 12 hours in typical use. (score 1.00)

The demo is structural — it already implements the keep-the-best rule with a stub scorer; the real version feeds the critique real criteria and scores revisions with a rubric or test. The other engineering rules from 2.6 still apply: cap iterations and ground the critique in something objective when you can.

7.4 Reasoning controls across providers — the pointer table#

Already covered in 3.2: the per-provider reasoning/thinking controls live in 02.8, Part 3 with full samples. The lesson for this topic: prompt-level CoT and API-level reasoning are independent dials — set the API dial for how much the model thinks internally, set the prompt for whether working appears in the visible answer.

Part 8: Beyond the linear chain#

Deep-dive

Everything so far produces one reasoning path. The research frontier generalises the shape of the reasoning itself. These are previews — Module 08A owns agents and tool loops, 04.8 owns prompt chaining.

8.1 Tree-of-thought and graph-of-thought#

A chain is a path; a tree branches. Tree of Thoughts (Yao et al., 2023) lets the model generate several candidate next steps, evaluate them, and search — with backtracking when a branch dies. The headline result: on Game of 24, GPT-4 with plain CoT solved ~4% of puzzles; ToT solved ~74%. The catch: it's expensive and complex — each node is a model call, and you need a way to score partial solutions.

Graph of Thoughts (Besta et al., 2024) generalises further: thoughts are nodes in an arbitrary graph with dependency edges, allowing aggregation, refinement loops and merging. Reported ~62% quality gain over ToT on sorting tasks at >31% lower cost — but this is research code, not a prompt you paste into production.

Engineering verdict: ToT/GoT are powerful for search-shaped problems (puzzles, planning with many valid paths, creative generation where you want diverse candidates). For most production tasks they're overkill — a reasoning model's internal search plus self-consistency gets you most of the benefit at a fraction of the complexity. Reach for them when you have a problem that's genuinely a search and you've measured that simpler methods fail.

8.2 ReAct: reason and act#

ReAct (Yao et al., 2022) interleaves reasoning with actions — the model thinks, calls a tool or searches, observes the result, thinks again. This is the intellectual ancestor of every tool-using agent: the "reason" part is CoT, the "act" part is tool calling (03.5).

text
Thought: I need to find the capital of Australia.
Action: search("capital of Australia")
Observation: Canberra is the capital of Australia.
Thought: I have the answer.
Action: finish("Canberra")

ReAct's insight — that reasoning and acting bootstrap each other (actions ground the reasoning, reasoning guides the actions) — is why agents work. But the loop, error handling and state management are Module 08A's subject; here you just need to recognise the pattern when you see it.

8.3 Program-of-thought: let code compute#

Program-Aided Language models (PAL, Gao et al., 2022) split the problem differently: the model writes code as its reasoning, and an interpreter executes it. The model handles the semantic decomposition ("what to compute"); Python handles the arithmetic ("the actual numbers").

text
Problem: What is 17% of 240, plus the square root of 144?

The model generates the code:  result = 0.17 * 240 + math.sqrt(144)   # = 52.8

Interpreter runs it → 52.8. No arithmetic errors possible.

This is the strongest answer to "LLMs are bad at maths": don't ask the model to do arithmetic in its head — ask it to write code that does. 02.10, 5.3 covers the calculator-tool version; PAL generalises it to any computation. The limitation: you need a code-execution sandbox (security! Module 12) and the model must generate correct code — which is its own reasoning task. Provider code-execution tools (Module 08A) make this practical.

8.4 Prompt chaining: split the task#

The simplest "beyond the chain" technique: don't ask for reasoning and answer in one call — split them into sequential calls. Extract → reason → format, or draft → critique → revise (7.3 is already a 3-call chain). Each call is simpler, you can validate between steps, and you can use different models per step (cheap model for extraction, reasoning model for the hard part).

The trade-off: N sequential calls = N× latency (though each is faster), and errors propagate — a bad extraction poisons everything downstream. 04.8 owns prompt chaining properly; the preview here is that decomposition (2.5) and chaining are the same idea at different granularity — one prompt that internally decomposes vs multiple prompts that externally decompose.

A sibling trick applies the same plan-then-generate split to the answer rather than the reasoning: Skeleton-of-Thought (Ning et al., ICLR 2024) has the model first emit an outline — the skeleton — then expand each point into the full answer, in parallel where the API allows. It's primarily a latency optimisation for long-form output (and sometimes a quality one, since each point is written with the agreed outline as shared context), not a reasoning-accuracy technique — but it belongs in the same family: plan first, generate second.

8.5 Other named techniques (a quick tour)#

The reasoning-prompting literature produced dozens of named techniques; a handful still come up in provider docs, papers and blog posts often enough that you should recognise them — and know whether they earn their keep on current models. Quick verdicts, as of November 2026:

  • Step-back prompting (Zheng et al., ICLR 2024) asks the model to answer a more general question first — the principle or concept the specific question depends on — then reasons from that abstraction to the answer. The paper reported gains on knowledge-heavy QA (MMLU science, TimeQA, multi-hop MuSiQue) across its PaLM-2L, GPT-4 and Llama2-70B runs. Verdict: reasoning models often do this abstraction internally, but the pattern survives in retrieval pipelines — lesson 07.3, 4.4 uses step-back query rewriting for multi-hop questions. Don't confuse the two: this one abstracts the question for reasoning; that one abstracts the search.
  • Analogical prompting (Yasunaga et al., ICLR 2024) has the model self-generate structurally similar exemplars from a different domain, then solve the real problem by analogy — it beat 0-shot and manual few-shot CoT on GSM8K, MATH, Codeforces and BIG-Bench. Verdict: mostly superseded — frontier in-context learning does this implicitly, and a curated real example usually beats a generated one. Occasionally useful when you want diverse exemplars without labelling them.
  • Generated-knowledge prompting (Liu et al., ACL 2022) generates relevant facts first, then answers with them as extra input; it improved commonsense benchmarks on the GPT-3-era models it tested. Verdict: the pattern — produce context, then answer — is alive and well, but self-generated facts are a hallucination vector; where you can, ground the step in retrieved sources instead (Module 07).
  • Self-ask (Press et al., Findings of EMNLP 2023) makes the model explicitly ask and answer its own follow-up sub-questions before the main answer, narrowing the compositionality gap on multi-hop QA; the structured format let a search engine answer the follow-ups. Verdict: subsumed — least-to-most decomposition and built-in reasoning cover the mechanism. Its durable contribution is the explicit sub-question structure that made follow-ups pluggable to retrieval — an ancestor of the agent loops in Module 08A.

More named techniques, with mechanics, examples and runnable sketches (Auto-CoT, Active-Prompt, APE, ART, Directional Stimulus, Multimodal CoT, Reflexion, Meta Prompting, PAL variants), are in lesson 04.11.

The meta-lesson: named techniques are patches for the capability gaps of the models they were tested on. When a new model internalises the mechanism, the technique's name fades — but the underlying need (decomposition, grounding, verification) remains, usually better served by the model's own reasoning or by tools.


Part 9: Failure modes#

Deep-dive

CoT doesn't eliminate reasoning failures — it changes their shape. The failure modes specific to prompted reasoning:

9.1 Confident wrong reasoning and rationalization#

The model produces fluent, well-structured, wrong reasoning that reaches a wrong answer — and the structure makes it more persuasive, not more correct. 02.10, 6.1 shows examples. CoT can make this worse: a detailed wrong chain looks more authoritative than a bare wrong answer. Rationalization — reasoning that justifies a pre-committed answer rather than deriving it — is the same failure from the ordering side (2.8).

Defence: verify outcomes, not explanations; use checkers where possible; don't present reasoning as proof.

9.2 Reasoning leaking into the answer#

The model's working bleeds into the final answer — restating steps, hedging, "wait, let me reconsider" mid-answer, or the reasoning tags appearing in the parsed output. Causes: weak instruction-following, format drift after long reasoning, or the model treating the answer region as part of the thinking.

Defence: the tag contract + tolerant parser (7.1); "give ONLY the final answer inside "; structured output for machine-critical answers.

9.3 Truncated reasoning#

max_tokens/max_output_tokens caps reasoning and answer together. If the model spends the whole budget thinking, you get an empty or cut-off answer — and still pay for all the reasoning. 02.8, 5.3 covers detection per provider (status: "incomplete", stop_reason: "max_tokens", finish reason MAX_TOKENS/length).

Defence: size the cap for working + answer + margin; detect truncation and retry with a higher cap or lower effort; for tagged-CoT on non-reasoning models, the working is visible so you can see it was cut off.

9.4 Format loss after long reasoning#

After hundreds of tokens of free-form working, the model forgets the output contract — wrong format, missing fields, prose instead of JSON, the answer buried in the reasoning. This is instruction-decay (02.10, 8.1) applied to the post-reasoning region.

Defence: put the output format after the reasoning instruction (recency helps); repeat the format spec right before the answer tag; use structured output which constrains decoding regardless of what the model "intended"; keep reasoning concise ("3-6 short steps").


Part 10: The test loop#

Every CoT decision should be measured, not guessed. Here's the minimal honest loop — runnable without API keys by feeding it recorded replies:

python
# cot_eval.py — pure Python, no dependencies. Run: python3 cot_eval.py
"""Minimal CoT A/B test: compare direct vs CoT prompts on a small labelled set.

Feed it recorded model replies (from any provider, or your own notes) and it
scores exact-match accuracy per configuration. No API calls needed.
"""
import json
import re
from pathlib import Path

# A tiny labelled set: (question, expected_answer). Real use: 20-50 items.
PROBLEMS = [
    {"q": "A shop sells pens in packs of 3 for $2. How much do 12 pens cost?", "a": "8"},
    {"q": "A jacket is $80, 25% off, then 10% off. Final price?", "a": "54"},
    {"q": "What is 17 × 24 − 13 × 9?", "a": "291"},
    {"q": "A train goes 60 km/h for 2h then 80 km/h for 1h. Average speed?", "a": "66.67"},
    {"q": "If 5 workers build a wall in 12 days, how long for 3 workers?", "a": "20"},
]


def extract_answer(reply: str) -> str:
    """Pull the comparable answer out of a reply: last number, or the <answer> tag."""
    m = re.search(r"<answer>(.*?)</answer>", reply, re.IGNORECASE | re.DOTALL)
    if m:
        return m.group(1).strip()
    nums = re.findall(r"-?\d+\.?\d*", reply.replace(",", ""))
    return nums[-1] if nums else reply.strip()


def to_number(text: str) -> float | None:
    """Pull a number out of an answer string ('$54' -> 54.0), or None."""
    m = re.search(r"-?\d+\.?\d*", text.replace(",", ""))
    return float(m.group()) if m else None


def score(replies: list[str], expected: list[str]) -> tuple[int, int]:
    """Exact-match score: (correct, total). Compares numerically where possible."""
    correct = 0
    for reply, exp in zip(replies, expected):
        got_num, exp_num = to_number(extract_answer(reply)), to_number(exp)
        if got_num is not None and exp_num is not None:
            ok = abs(got_num - exp_num) < 0.01
        else:
            ok = extract_answer(reply).lower() == exp.lower()
        correct += ok
    return correct, len(expected)


# Recorded replies: {"direct": [...], "cot": [...]} — fill from real runs.
# For the demo, canned replies show the harness working.
RECORDED = {
    "direct": ["$8", "$54", "291", "about 70", "20 days"],
    "cot": ["<answer>$8</answer>", "<answer>$54</answer>", "<answer>291</answer>",
            "<answer>66.67</answer>", "<answer>20</answer>"],
}

EXPECTED = [p["a"] for p in PROBLEMS]

for config, replies in RECORDED.items():
    c, t = score(replies, EXPECTED)
    print(f"{config:8s}: {c}/{t} = {c/t:.0%}")

# Real usage: run the same problems through your model twice — once with a direct
# prompt, once with the CoT prompt — record the replies into RECORDED, rerun.
# The delta is whether CoT earns its tokens on YOUR task, YOUR model.
print("\nRecorded:", json.dumps({k: len(v) for k, v in RECORDED.items()}))
Output4 lines
direct  : 4/5 = 80%
cot     : 5/5 = 100%

Recorded: {"direct": 5, "cot": 5}

(The canned numbers are illustrative of the harness — the point is the shape: same problems, two prompts, exact-match score, one number to compare.)

10.1 Reading the results#

  • CoT wins on multi-step problems, loses on simple ones — expect the split Part 6 predicts. If CoT doesn't help your task, don't pay for it.
  • Watch the failure mode, not just accuracy. CoT can reduce errors while increasing cost and latency — a good trade on hard tasks, a bad one on easy ones. Measure all three.
  • Variance matters. One run of 5 problems is noise. 02.5 Part 7 covers non-determinism; run N times or use enough items to see a real difference. Module 10A owns proper eval design — this loop is the honest minimum.
  • The decision is per task, per model. A prompt that helps gpt-6-luna may be redundant on gpt-6.1-sol or harmful on a reasoning model with thinking on. Re-test when you change models.

Complete, reusable prompts. Adapt the {{...}} slots; each is self-contained.

1. Zero-shot CoT for a non-reasoning model (tagged output)

text
<instructions>
Solve the problem inside <thinking> tags: 3-8 short steps showing the
arithmetic or logic explicitly. Then give ONLY the final answer inside
<answer> tags — one line, no explanation. If ambiguous, state your
assumption inside <thinking>.
</instructions>
<problem>
{{QUESTION}}
</problem>

2. Few-shot CoT exemplars (2-3 worked examples before the question)

text
Q: A rope 60 m long is cut into 4 m pieces. How many pieces?
A: <thinking>60 ÷ 4 = 15 pieces.</thinking><answer>15</answer>

Q: Tom has 3 bags of 12 marbles. He gives away 10. How many left?
A: <thinking>3 × 12 = 36 marbles. 36 − 10 = 26 left.</thinking><answer>26</answer>

Q: {{QUESTION}}
A:

3. Plan-then-solve for a planning task

text
<task>
Plan and solve: {{TASK_DESCRIPTION}}
</task>
<instructions>
First write a plan of 3-5 bullet points inside <plan> tags.
Then execute it step by step inside <thinking> tags.
Then give the final answer inside <answer> tags.
Flag any step you're unsure about inside <thinking>.
</instructions>

4. Verification prompt (self-check before answering)

text
<instructions>
Solve the problem step by step inside <thinking> tags.
Before answering, verify: recheck each calculation, confirm every given
quantity was used, and check the answer matches what was asked (units,
format). If a check fails, fix the step.
Then give ONLY the final answer inside <answer> tags.
</instructions>
<problem>
{{QUESTION}}
</problem>

5. Self-refine chain (3 calls: draft, critique, revise)

text
<!-- Call 1: draft -->
{{TASK}}

<!-- Call 2: critique (feed the draft back) -->
Here is a draft answer:
{{DRAFT}}

List its specific weaknesses against these criteria: {{CRITERIA}}.
Be harsh and specific. If it's good, say "no issues".

<!-- Call 3: revise (feed draft + critique back) -->
Revise this draft to fix every weakness listed. Output only the
revised answer.

Draft: {{DRAFT}}
Critique: {{CRITIQUE}}

6. Reasoning-model prompt (no CoT instructions — for models that think)

text
<goal>
{{GOAL — what success looks like, not how to get there}}
</goal>
<constraints>
{{CONSTRAINTS — what must/must not happen, output format, length}}
</constraints>
<output_format>
{{EXACT output shape — sections, JSON schema, or "answer only"}}
</output_format>

7. Justification for users (non-reasoning model, human-readable explanation)

text
<instructions>
Answer the question, then give a brief justification a non-expert can
follow: 2-4 sentences naming the key factor or rule that decided it.
Don't show working, just the reasoning in plain language.
</instructions>
<question>
{{QUESTION}}
</question>

Common misconceptions#

Misconception Reality
"Chain-of-thought always improves accuracy" Mainly maths and symbolic reasoning (Sprague et al. 2024); on general knowledge tasks direct answering is about as good. Test on your task.
"'Think step by step' is still the best prompt for any hard problem" On reasoning models it's redundant or harmful — they think internally; the lever is effort/thinking settings, not prompt phrases.
"The reasoning the model shows is what it actually did" Often not — reasoning can be unfaithful (post-hoc rationalization). It's a clue, not an audit trail.
"More thinking always means a better answer" Overthinking exists: longer reasoning can hurt accuracy on easy problems and wastes tokens. Effort is a dial, not "max = best".
"Self-consistency always helps" Only when errors are varied, not systematic — and it multiplies cost by N. A wrong-but-popular answer wins the vote.
"Self-refine fixes anything the model got wrong" Intrinsic self-correction can degrade performance (Huang et al. 2023). It works when the critique is grounded in external evidence.
"Answer-first is fine — the reasoning will catch mistakes" Preemptive answers degrade reasoning (up to ~62% in the ACL study) and produce rationalization, not correction.
"You need fancy tree/graph search for hard problems" Reasoning models' internal search + self-consistency covers most cases; ToT/GoT are for genuinely search-shaped problems you've measured.
"CoT is dead now that models reason" Still essential for non-reasoning models, reasoning-off configs, visible working, and format-controlled reasoning.

Key takeaways#

  • CoT works because written steps are scratch paper — each token is a forward pass of computation, and intermediate results stay visible. It restructures computation the model already does, not new knowledge.
  • The toolkit: zero-shot phrase, few-shot worked examples, numbered steps, scratchpad/tags, plan-then-solve, self-consistency voting, least-to-most decomposition, self-refine, verification prompts, and answer-first vs reasoning-first ordering.
  • On reasoning models, don't script the thinking — OpenAI, Anthropic and Google all document: give goals, constraints and output contracts; control depth with effort/thinking settings, not prompt phrases. Explicit CoT still earns its keep for non-reasoning models, reasoning-off configs, visible working, and format control.
  • Shown reasoning may be unfaithful — it's a debugging/UX clue, not an audit trail. Don't parse answers from thinking; don't present reasoning as proof.
  • Costs are real: working tokens are output tokens (billed, capped, slow). Stream only the answer when you can; measure time-to-first-answer.
  • Task suitability is empirical: CoT pays off on multi-step symbolic tasks, is wasted on extraction/classification/simple Q&A. Test with and without on your own data.
  • Separate reasoning from answer with tags or structured fields so code can parse reliably; the tolerant parser in 7.1 is the starting point.
  • Beyond the chain (ToT, GoT, ReAct, PoT, chaining) is where agents live — previews here, Module 08A owns them. Part 8 closes with a tour of the other named techniques — step-back, analogical, generated-knowledge and self-ask — most subsumed by reasoning models but still met in provider docs and pipelines.

Terms introduced in this lesson#

Term One-line definition
Zero-shot CoT CoT elicited by an instruction phrase ("think step by step") with no examples
Few-shot CoT CoT elicited by worked examples showing question → reasoning → answer
Scratchpad / thinking tags A named region (<thinking>, <scratchpad>) for working, separate from the answer
Plan-then-solve Prompting the model to write a plan before executing it
Plan-and-Solve prompting Wang et al.'s zero-shot variant: plan generation + plan-guided answering (arXiv:2305.04091)
Self-consistency Sampling N reasoning paths and returning the majority answer (Wang et al. 2022)
Least-to-most prompting Decomposing a problem into easier sub-problems solved in sequence (Zhou et al. 2022)
Self-refine Iterative draft → self-critique → revise loop using one model (Madaan et al. 2023)
Verification prompt Asking the model to check its work against explicit criteria before answering
Process supervision Rewarding/verifying each reasoning step, not just the final answer (Lightman et al. 2023)
Answer-first prompting Asking for the answer before the reasoning (post-thinking); risks rationalization
Rationalization Reasoning that justifies a pre-committed answer rather than deriving it
Preemptive answer An answer obtained before reasoning begins; degrades subsequent reasoning
Tree-of-thought (ToT) Searching over branching reasoning paths with self-evaluation (Yao et al. 2023)
Graph-of-thought (GoT) Generalising thoughts to an arbitrary dependency graph (Besta et al. 2024)
ReAct Interleaving reasoning traces with actions/tool calls (Yao et al. 2022)
Program-of-thought / PAL Using generated code as the reasoning, executed by an interpreter (Gao et al. 2022)
Skeleton-of-thought (SoT) Emitting an answer outline first, then expanding each point — in parallel where possible (Ning et al., ICLR 2024)
Step-back prompting Answering a more general question first, then reasoning to the specific answer (Zheng et al., ICLR 2024)
Analogical prompting Self-generating structurally similar exemplars from a different domain, then solving by analogy (Yasunaga et al., ICLR 2024)
Generated-knowledge prompting Generating relevant facts first and answering with them as extra input (Liu et al., ACL 2022)
Self-ask Explicitly asking and answering follow-up sub-questions before the main answer (Press et al., 2023)
Reasoning separator Tags or fields separating working from the final answer for parsing
Overthinking Spending excessive reasoning on easy problems, wasting tokens and sometimes lowering accuracy

(Chain-of-thought prompting, chain-of-thought faithfulness, self-consistency, best-of-N, reasoning effort, reasoning model, overthinking and encrypted reasoning are already in the glossary — this lesson extends them rather than duplicating.)


Exercises#

  1. Tagged CoT parser (7.1): run cot_parse.py and add a case for a reply where <answer> opens but the model writes the answer before closing the thinking tag (e.g. <thinking>work <answer>42</answer> more work</thinking>). What does the parser return, and is it correct? Hint: run it. The <answer> pattern matches first, so the parser returns answer='42' and reasoning='work more work' (tags stripped, the gap left by the removed block). That is the right split here, but the reasoning text now has a hole in it, so don't display it to users unedited.
  2. Self-consistency vote (7.2): modify vote.py's normalize_answer to strip currency symbols and trailing .00. Re-run on ["$54", "54 dollars", "$54.00", "$54.0", "54"] — how does the count change? Hint: strip currency symbols with re.sub(r"[$€£]", "", text), drop the words dollar/dollars/USD, and turn 54.00 or 54.0 into 54 with re.sub(r"(\d)\.0+\b", r"\1", text). All five answers then normalise to 54 and the counter shows {'54': 5}, where the original function leaves them as five separate groups of one.
  3. Test loop (10): take the 5 problems in cot_eval.py, write direct and CoT replies yourself (or use a local model), and compute the scores. Does CoT help on your answers?
  4. Provider guidance: pick one provider's prompting doc (OpenAI reasoning best practices, Anthropic best practices, or Google prompting strategies) and find one piece of CoT advice that contradicts what you learned in Part 2. Which is right for your model?
  5. Failure modes: take a CoT prompt that produces a confident wrong answer. Identify which failure mode from Part 9 it is, and which defence would catch it.
  6. Cost estimate: a task needs ~800 reasoning tokens + 200 answer tokens. Using your provider's pricing page, compute the cost per 1,000 calls vs a direct prompt. At what accuracy improvement does CoT break even? Hint: ignore input tokens and compare output tokens, 1,000 against 200, so CoT costs about 5× per call. Measured as cost per correct answer (cost_per_call / accuracy, 04.2, 7.3), it only breaks even if accuracy rises 5×, which is possible only when the direct prompt is below 20% accurate. In practice the question is whether the errors CoT removes cost you more than the extra output tokens do, and that is a business number, not a benchmark.
  7. Self-refine: replace the stub score() in self_refine_demo.py with a real scorer — e.g. a word-count check for "under 60 words", a jargon ban-list, and an LLM-as-judge call for accuracy — then trace which revision self_refine returns and why. Hint: the loop keeps a revision only when its score is strictly greater than the best so far, so a later revision that merely ties the best is discarded; print each iteration's score to see it.

Check yourself#

  1. Why does writing intermediate steps help a language model solve multi-step problems?
  2. What's the difference between zero-shot CoT and few-shot CoT?
  3. Why does self-consistency voting sometimes make things worse?
  4. On a reasoning model that thinks by default, is "think step by step" still useful? Why or why not?
  5. What do OpenAI, Anthropic and Google all independently document about prompting reasoning models?
  6. Name three situations where explicit CoT prompting still earns its keep.
  7. Why might the reasoning a model shows you not be the real reason for its answer?
  8. What are the two clocks that matter for CoT latency, and which does the user experience?
  9. On which task types does CoT help most, and on which does it hurt?
  10. What's the difference between self-refine and verification prompting?
  11. Why is answer-first prompting risky for accuracy?
  12. What's the engineering reason to keep reasoning and answer in separate parseable regions?
  13. When would you choose tree-of-thought over a simple CoT prompt?
  14. What does "overthinking" mean, and how do you control it?
  15. What's the minimal honest test for whether CoT helps your task?

Further resources#


← 04.2 — Zero-Shot, Few-Shot and Examples | Module 04 overview | 04.4 — Structuring Prompts: XML, Markdown and Delimiters →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close