◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

Chain-of-Thought and Reasoning Prompts

Language models get more multi-step problems right when they write out their reasoning before the answer. How to ask for it, how to sample several chains and vote, how to break problems apart, and when built-in reasoning models make all this unnecessary.

Level
●●●●● Easy
Reading
12 min
To learn it well
45 minutes to read, an afternoon to practise
↗ Plan a path here

Read first

Prompt Engineering

This leads to

AI AgentsReasoning Models and Test-Time Compute
The full path from zero — 4 concepts before this one
  1. What Is AI?
  2. How Machines Learn
  3. Large Language Models, Explained Simply
  4. Prompt Engineering
  5. Chain-of-Thought and Reasoning Prompts

Read them roughly in this order. See it on the concept map →

Why it matters

Ask a language model "A shop has 3 boxes of 12 eggs, 7 break, and the rest go into cartons of 6. How many full cartons?" and older models often blurt out a wrong number. Ask the same model to work through it step by step first, and it usually gets 4. Nothing about the model changed. Only the prompt did.

That trick is chain-of-thought prompting: getting the model to write intermediate reasoning steps before its final answer. It was one of the most important discoveries about large language models, because it turned them from fluent guessers into something that could do arithmetic, logic puzzles and multi-step planning. It is also the seed of today's Reasoning Models and Test-Time Compute, which are trained to produce long chains of thought by themselves.

If you build with LLMs you need to know three things: how to ask for reasoning when a model doesn't do it on its own, how to spend extra compute to make answers more reliable (self-consistency), and when to leave all this alone because the model already reasons internally. That last one is now the common case, so this chapter covers it too.

The intuition

Try multiplying 47 × 36 in your head, instantly, without any intermediate steps. Hard. Now do it on paper: 47 × 30 = 1,410, 47 × 6 = 282, total 1,692. Easy. The paper doesn't make you smarter. It gives you somewhere to put intermediate results so each step is small.

A language model generates text one token at a time, and each token gets the same fixed amount of computation: one pass through the network (see The Transformer). If the answer must come out as the very first token, the model gets one pass to solve the whole problem. If it first writes "36 eggs minus 7 is 29", then those tokens become part of the input, and every later token can look back at them through Attention. The written reasoning is the model's paper. More tokens means more computation, spent exactly where the problem needs it.

Question "3 boxes of 12 eggs, 7 break, the rest go into cartons of 6. How many full cartons?" Answer directly LLM one forward pass "5" wrong the whole problem must be solved in the computation for a single token Think step by step first LLM many forward passes 3 × 12 = 36 eggs 36 − 7 = 29 29 ÷ 6 = 4 rem 5 "4" right written steps = working memory every new token can attend to the steps already written, so each step stays small Reasoning costs tokens (time and money) but buys extra computation exactly where the problem needs it.
Fig. 1 The same word problem answered two ways. Asked for the answer directly, the model must jump to a number in one step and gets it wrong. Asked to reason first, it writes small steps, each building on the last, and reaches the right answer.

Key idea Reasoning text is working memory. Each written step is extra computation the next tokens can build on, so models solve multi-step problems far better when they think before answering.

How it works

Few-shot chain-of-thought

The original method, from Wei and colleagues at Google in 2022, used few-shot prompting where each example shows its reasoning, not just the answer:

Q: Roger has 5 tennis balls. He buys 2 cans of 3 balls each. How many does he have now?
A: Roger started with 5 balls. 2 cans of 3 balls is 6 balls. 5 + 6 = 11. The answer is 11.

Q: {new question}
A:

The model imitates the pattern and writes its own reasoning. With eight such worked examples, a 540-billion-parameter model reached state-of-the-art accuracy on GSM8K, a benchmark of grade-school maths word problems, beating a GPT-3 model that had been fine-tuned for the task and given a separate verifier. The paper also found the effect was emergent: small models wrote fluent but wrong reasoning, and the benefit appeared only in the largest models of the time.

Zero-shot chain-of-thought

A few months later Kojima and colleagues found that you don't even need examples. Simply ending the prompt with "Let's think step by step." raised the accuracy of OpenAI's text-davinci-002 model on the MultiArith benchmark from 17.7% to 78.7%, and on GSM8K from 10.4% to 40.7%. This is zero-shot chain-of-thought. It is the most famous sentence in prompt engineering.

Structured reasoning for applications

In an application you usually want the reasoning but not to show it, or at least to separate it from the answer your code reads. Ask for both, in tags:

Think through the problem inside <thinking> tags. Then give only the final
number inside <answer> tags.

Your code extracts <answer> and logs <thinking> for debugging. Anthropic's guide recommends this kind of structured thinking and notes the key rule: the model has to actually write the reasoning out. Telling it to "think carefully" without giving it room to write produces no extra computation at all.

You can also guide the steps: "First list the facts in the question. Then identify what is being asked. Then compute." This is useful when you know how an expert would approach the task, for example "Check the contract's termination clause before its payment terms."

Self-consistency: sample several chains and vote

A single chain of reasoning can go wrong at any step. Self-consistency (Wang et al., 2022) exploits the fact that there are many ways to reason to the right answer, but wrong chains tend to land on different wrong answers. So:

  1. Sample several independent reasoning chains for the same question, with randomness switched on so they differ.
  2. Extract each chain's final answer.
  3. Take the most common answer. This is majority voting.

Here is the arithmetic of why it works. Suppose each chain is right 60% of the time and the wrong chains scatter over four different wrong answers. Then among 5 samples you expect 3 right answers all saying "4", and the 2 wrong ones probably disagree with each other. The right answer wins the vote far more often than 60% of the time. The simulation in the code below gives about 61% accuracy with 1 sample, 83% with 5 and 99% with 15.

Question eggs → cartons 5 chains, sampled with randomness on 36 eggs, −7 = 29, ÷ 6 → 4 full 36 eggs, −7 = 29, round up → 5 29 left; 6 × 4 = 24 ≤ 29 → 4 forgot the cartons step → 29 12 × 3 − 7 = 29; ⌊29/6⌋ = 4 4 5 4 29 4 Majority vote 4: three votes 5: one · 29: one answer: 4 Simulated: a solver right 60% of the time scores 0.61 alone, 0.83 with a 5-way vote and 0.99 with 15. It works because wrong chains usually disagree with each other.
Fig. 2 Self-consistency. Five reasoning chains are sampled for the same question. Three reach 4, the others reach 5 and 29. The majority vote returns 4. Wrong chains rarely agree with each other, so voting filters them out.

The catch is cost: 15 samples cost 15 times as much. And voting needs answers that can be compared, such as numbers, labels or multiple-choice letters. For free-form text you can ask a model to pick the answer most consistent with the others instead.

Decomposition: split the problem first

Some problems are too big for one chain. Problem decomposition splits them into sub-questions:

  • Least-to-most prompting (Zhou et al., 2022) first asks the model to list the simpler sub-questions, then solves them in order, feeding each answer into the next.
  • Prompt chaining does the same with separate API calls, so your code can check each step.
  • Tree of Thoughts (Yao et al., 2023) goes further: the model proposes several possible next steps, rates them, and explores the promising branches, backtracking from dead ends like a search algorithm.

In applications, plain prompt chaining is by far the most used of these. The tree-search methods are expensive and mostly superseded by reasoning models.

Reasoning models: thinking built in

In September 2024 OpenAI released o1, a model trained with reinforcement learning to produce a long hidden chain of thought before answering. DeepSeek-R1 (January 2025) showed openly how such training works. Anthropic's Claude models gained "extended thinking" in 2025, and as of late 2026 the newest Claude models think adaptively by default, deciding for themselves how much to reason. See Reasoning Models and Test-Time Compute for how they are trained.

With these models the reasoning happens in separate thinking tokens: text the model generates before its visible answer. Three things change for you as a builder:

  • You no longer need "think step by step". The model already does. OpenAI's guide compares reasoning models to a senior colleague you can give a goal to, and chat models to a junior one who needs explicit steps. Give a reasoning model the goal, the constraints and the context, and let it plan.
  • You control depth with a setting, not a prompt. The reasoning effort parameter (effort on Claude, reasoning.effort on OpenAI) trades accuracy against time and cost. Low effort suits classification and chat. High effort suits hard coding, maths and analysis.
  • You pay for thinking. Thinking tokens are billed as output tokens, even when they are hidden or summarised. A hard question at high effort can use thousands of them. See Using LLM APIs for the cost arithmetic.

Prompted chain-of-thought is still useful with models or settings that don't reason internally (small, fast or local models, see Running Models Locally), when you want the reasoning in a specific structure, or when you want to read the reasoning in full, since several providers show only a summary of their models' thinking.

When it helps, and when it doesn't

Reasoning helps most on tasks with several dependent steps: arithmetic and word problems, logic, code, planning, comparing options against criteria, and questions that combine facts from different places in a long document.

It helps little or not at all on single-step tasks: looking up a fact, simple classification, translation, style rewriting. There it only adds cost and delay. Measure before paying for it: run your test set with and without reasoning, or at different effort levels, and compare accuracy, latency and cost.

In code

First, the plain-Python pieces: extracting an answer from a structured reply, and a simulation of self-consistency with a noisy "solver" that is right 60% of the time.

import re
from collections import Counter
import numpy as np

def extract_answer(reply):
    """Pull the final answer out of <answer> tags; ignore the reasoning."""
    m = re.search(r"<answer>\s*(.*?)\s*</answer>", reply, re.S)
    return m.group(1) if m else None

reply = """<thinking>
3 boxes of 12 eggs is 36 eggs. 7 broke, so 36 - 7 = 29.
29 eggs into cartons of 6: 29 // 6 = 4 full cartons, 5 left over.
</thinking>
<answer>4</answer>"""
print(extract_answer(reply))                       # 4

# Self-consistency: sample n reasoning chains, take a majority vote.
rng = np.random.default_rng(0)
def sample_chain(p_correct=0.6):
    # A noisy solver: right answer "4" with prob 0.6, else a scattered wrong one.
    return "4" if rng.random() < p_correct else str(rng.choice(["3", "5", "6", "29"]))

def self_consistency(n):
    votes = Counter(sample_chain() for _ in range(n))
    return votes.most_common(1)[0][0]

for n in [1, 5, 15, 41]:
    acc = np.mean([self_consistency(n) == "4" for _ in range(2000)])
    print(f"{n:2d} samples per question -> accuracy {acc:.2f}")
#  1 samples per question -> accuracy 0.61
#  5 samples per question -> accuracy 0.83
# 15 samples per question -> accuracy 0.99
# 41 samples per question -> accuracy 1.00

The gain depends on the wrong answers being scattered. If the model makes the same mistake most of the time, voting just confirms it.

With a reasoning model you set the effort and read the answer. This uses Anthropic's official SDK (pip install anthropic, key in ANTHROPIC_API_KEY). It needs a key, so its output isn't shown:

import anthropic

client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-sonnet-5-5",                    # current ids: see the models page
    max_tokens=16000,                             # thinking counts towards this
    thinking={"type": "adaptive", "display": "summarized"},  # show a summary
    output_config={"effort": "high"},             # low | medium | high | xhigh | max
    messages=[{"role": "user", "content":
               "A shop has 3 boxes of 12 eggs, 7 break, and the rest go into "
               "cartons of 6. How many full cartons?"}],
)
for block in response.content:
    if block.type == "thinking":
        print("THINKING:", block.thinking)        # a summary, not the raw chain
    elif block.type == "text":
        print("ANSWER:", block.text)
print(response.usage.output_tokens, "output tokens, thinking included")

OpenAI's equivalent is client.responses.create(model=..., reasoning={"effort": "high"}, input=...) with the answer in response.output_text.

Common pitfalls

  • Asking for reasoning but parsing the whole reply. If your code expects a bare label and gets three paragraphs of thinking first, it breaks. Put the answer in tags or use Structured Output and JSON, and extract it.
  • Adding "think step by step" to a reasoning model. It is usually redundant and can make answers longer without making them better. Use the effort setting instead.
  • Paying for reasoning on easy tasks. Reasoning multiplies output tokens and latency. On a simple classifier it may double the cost for no gain. Measure.
  • Reasoning on a tiny output budget. Thinking tokens count towards max_tokens. Set it too low and the model runs out mid-thought and returns no answer (stop_reason is max_tokens).
  • Voting on free text. Majority voting needs comparable answers. Normalise them first ("4", "four" and "4 cartons" are the same answer).

Watch out Written reasoning is not a faithful record of how the model reached its answer. Research such as Turpin et al. (2023), "Language Models Don't Always Say What They Think", found that models can give plausible explanations that leave out what actually drove the answer. This property is called faithfulness, and it is often weak. Use the reasoning to debug and to improve accuracy, but don't treat it as proof that the answer is right. Check the answer itself.

Where it leads

  • Reasoning Models and Test-Time Compute: how models are trained with reinforcement learning to think for a long time on their own.
  • AI Agents: reasoning interleaved with actions. The ReAct pattern alternates "thought" and "tool call" steps, building on chain-of-thought.
  • Tool Use and Function Calling: when a step needs exact computation, let the model call a calculator or run code instead of doing arithmetic in text.
  • Evaluating LLM Applications: measuring whether reasoning, voting or higher effort actually pays for itself on your task.
  • Hallucinations: reasoning reduces some errors but can also produce confident, well-argued wrong answers.

A bit of history

The idea that language models do better when they show their work appeared in several places around 2021, including "scratchpad" experiments that trained models to write intermediate computation. Wei et al.'s chain-of-thought paper (January 2022) made it a prompting technique and showed its striking effect at scale. Kojima et al. (May 2022) found the zero-shot version, "Let's think step by step." Self-consistency (Wang et al., 2022) and least-to-most prompting (Zhou et al., 2022) followed quickly, and Tree of Thoughts (Yao et al., 2023) turned reasoning into search.

The big shift came in September 2024 with OpenAI's o1, which was trained to reason rather than prompted to. DeepSeek-R1 (January 2025) published how reinforcement learning on verifiable problems produces long, self-correcting chains of thought. By 2025 every major provider offered reasoning models with adjustable effort, and prompting for chain-of-thought became something you do only when the model doesn't do it for you.

Try it

  1. In the simulation, change p_correct to 0.4 and re-run. Does voting still help? Now make the wrong answers always "5" instead of scattered. What happens with 41 samples, and why?
  2. Pick five multi-step word problems. Ask a small or fast model each one directly, then with "Think step by step inside <thinking> tags, then give the answer in <answer> tags." Count how many each gets right.
  3. With a reasoning model, run the same five problems at low and high effort. Record accuracy, output tokens and time. Which setting would you ship?

Hint for 1: voting picks the most common answer, not the correct one. If wrong answers agree with each other more often than right answers do, voting makes things worse.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Why does asking a model to write its reasoning before the answer improve accuracy on multi-step problems?

  2. Using self-consistency, five sampled chains answer 4, 4, 5, 4, 29. What is returned, and when would voting fail?

  3. You add "Let's think step by step" to every prompt sent to a modern reasoning model with effort set to high. What is the most likely effect?

  4. A reasoning model returns no answer and the stop reason is max_tokens. What went wrong?

  5. A model's written reasoning looks convincing and ends in the right answer. What does the faithfulness research warn about?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Large Language Models are Zero-Shot Reasoners

Kojima et al. · 2022 · Intermediate · Free

Showed that simply adding "Let's think step by step" to a prompt makes large models reason much better, with no examples at all.

Docs

Prompt engineering overview

Anthropic · Beginner · Free

Official, practical guidance on writing prompts that work, with many examples.

Article

Learning to Reason with LLMs

OpenAI · 2024 · Beginner · Free

OpenAI's announcement of o1, with its plots of accuracy rising with both training-time RL compute and test-time thinking compute.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/chain-of-thought.md