Chain-of-Thought Prompting

Chain-of-Thought (CoT) prompting is a technique where a language model is guided — either by examples or by instruction — to produce explicit intermediate reasoning steps before arriving at a final answer. It matters because it dramatically improves LLM performance on multi-step reasoning tasks like math, logic, and commonsense inference without any additional training. The counterintuitive fact: simply appending the phrase "Let's think step by step" to a prompt can raise a model's accuracy on grade-school math problems by 40–50 percentage points.

The core insight

Language models generate text one token at a time, and each token is influenced by everything that came before it. When you force a model to "think out loud" by writing intermediate steps, those steps become context that steers subsequent tokens toward correct answers — the model is essentially using its own output as working memory. Without this scaffolding, the model is asked to compress an entire multi-step reasoning chain into a single forward pass with no scratch pad. The "aha moment" is realizing that prompting is not just about what you ask, but about the shape of the reasoning you invite the model to perform.

How It Works

At its core, CoT prompting modifies the prompt fed to the model so that the expected output includes a reasoning chain, not just a bare answer. There are two main flavors:

Few-Shot CoT — You provide several worked examples in the prompt, each showing question → reasoning steps → answer. The model pattern-matches to this structure.

Zero-Shot CoT — You add a trigger phrase like "Let's think step by step" and rely on the model having seen enough reasoning text during pretraining to self-generate steps. The probability the model assigns to the correct final answer AA given question QQ can be written as:

1
P(A∣Q)≈∑zP(A∣z,Q) P(z∣Q)\quad P(A \mid Q) \approx \sum_{z} P(A \mid z, Q)\, P(z \mid Q)

Explanation: The model's probability of the right answer improves when it first generates an intermediate reasoning chain zz, because conditioning on zz makes the final answer much easier to predict. Here, zz is the intermediate reasoning trace (the "chain of thought"), QQ is the question, and AA is the final answer. Without CoT, the model collapses this sum by going directly from QQ to AA, which is a much harder mapping. A practical self-consistency extension averages over multiple sampled reasoning chains:

2
A^=arg⁡max⁡A  ∑i=1k1[chaini→A]\quad \hat{A} = \arg\max_{A}\; \sum_{i=1}^{k} \mathbf{1}[\text{chain}_i \rightarrow A]

Explanation: Generate kk different reasoning chains, collect the answer each one produces, and pick the answer that appears most often — the majority vote across chains tends to be more reliable than any single chain. Here kk is the number of sampled chains (typically 10–40), and 1[⋅]\mathbf{1}[\cdot] is 1 if chain ii concludes with answer AA and 0 otherwise. Below is a minimal Python example showing both zero-shot and few-shot CoT using the OpenAI API: ```python import openai client = openai.OpenAI() # uses OPENAI_API_KEY env variable QUESTION = "A store sells apples for 0.50eachandorangesfor0.50 each and oranges for 0.75 each. " \ "If I buy 4 apples and 3 oranges, how much do I spend in total?"

# ── Zero-Shot CoT ───────────────────────────────────────────────────────────── zero_shot_prompt = QUESTION + "\n\nLet's think step by step." zero_shot = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": zero_shot_prompt}] ) print("=== Zero-Shot CoT ===") print(zero_shot.choices[0].message.content)

# ── Few-Shot CoT ────────────────────────────────────────────────────────────── few_shot_example = """ Q: A bakery makes 12 muffins per batch. They bake 3 batches in the morning and 2 batches in the afternoon. How many muffins did they make? A: Let's think step by step.

  • Morning: 3 batches × 12 muffins = 36 muffins
  • Afternoon: 2 batches × 12 muffins = 24 muffins
  • Total: 36 + 24 = 60 muffins

The answer is 60. Q: {question} A: Let's think step by step. """.format(question=QUESTION) few_shot = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": few_shot_example}] ) print("\n=== Few-Shot CoT ===") print(few_shot.choices[0].message.content) ``` ```python

# ── Self-Consistency: sample k chains, majority-vote the answer ─────────────── from collections import Counter import re def extract_final_number(text: str) -> str | None: """Pull out the last number mentioned in a CoT response.""" matches = re.findall(r"$?[\d,]+\.?\d*", text) return matches[-1].replace(",", "") if matches else None def self_consistent_answer(question: str, k: int = 5) -> str: prompt = question + "\n\nLet's think step by step." answers = [] for _ in range(k): resp = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": prompt}], temperature=0.7, # non-zero so chains vary ) ans = extract_final_number(resp.choices[0].message.content) if ans: answers.append(ans) majority, count = Counter(answers).most_common(1)[0] print(f"Votes: {dict(Counter(answers))}") print(f"Majority answer: {majority} (agreed by {count}/{len(answers)} chains)") return majority self_consistent_answer(QUESTION, k=5) ```

researcher · Jason Wei | b. 1997 | Inventor of Chain-of-Thought Prompting

Jason Wei is a researcher at Google Brain (later Google DeepMind) who co-authored the landmark 2022 paper "Chain-of-Thought Prompting Elicits Reasoning in Large Language Models" alongside colleagues including Xuezhi Wang and Denny Zhou. His work demonstrated for the first time that reasoning traces in prompts cause step-change improvements in LLM accuracy on arithmetic, symbolic, and commonsense benchmarks — a finding that reshaped how the field thinks about prompting. Surprisingly, Wei and co-authors initially struggled to reproduce the effect on smaller models, which led to the now-famous observation that CoT is an emergent ability that only appears in models above roughly 100 billion parameters.

Figure
Chain-of-Thought Prompting — Data Flow
Chain-of-Thought vs. Standard Prompting STANDARD PROMPT Q: 4×$0.50 + 3×$0.75 = how much? LLM (one hop) A: $3.25 ✗ (skipped steps) CHAIN-OF-THOUGHT PROMPT Q: 4×$0.50 + 3×$0.75 = how much? ↳ "Let's think step by step." LLM generates reasoning chain z Step 1: 4 × $0.50 = $2.00 Step 2: 3 × $0.75 = $2.25 Step 3: $2.00 + $2.25 = $4.25 A: $4.25 ✓
Figure
Self-Consistency Decoding
Self-Consistency: Sample k Chains, Majority Vote Question + "Think step by step" chain₁ (T=0.7) chain₂ (T=0.7) chain₃ (T=0.7) Step 1: 4×0.5=2.00 Step 2: 3×0.75=2.25 → $4.25 ✓ Apples cost 2 dollars Oranges cost 2.25 dollars → $4.25 ✓ 4 apples = $2, 3 oranges... wait, 3×0.75 = 2.00? → $4.00 ✗ Majority vote: $4.25 wins (2 of 3) ✓

Intuition

The Mental Model

Imagine you are asked to calculate a restaurant bill in your head with no pencil or paper. If someone demands the total in one second, you are likely to make an error by combining costs too fast. But if you are allowed to mutter the sub-totals aloud — "starter is 12,mainis12, main is 24, so that's 36,plus36, plus 8 dessert, that's $44" — you almost certainly get it right. The spoken sub-totals are not just communication; they are cognitive props that carry partial results forward so your working memory isn't overwhelmed. Chain-of-Thought does exactly this for language models: the intermediate tokens that appear on the "page" become new context the model can attend to, functioning as external scratch-pad memory. The model isn't smarter; it just has better tools in front of it.

Historical Development

Origins · 1 minhow this was discovered
History
2017
Transformer architecture introduced by Vaswani et al. in "Attention Is All You Need" — the foundation that makes token-by-token generation tractable at scale.
2020
GPT-3 (Brown et al., OpenAI) demonstrates that few-shot prompting with in-context examples can unlock emergent task-solving, hinting that prompt structure matters enormously.
2021
Nye et al. introduce "scratchpad" prompting in "Show Your Work: Scratchpads for Intermediate Computation", explicitly proposing that models generate intermediate steps before answers.
2022
Wei et al. publish "Chain-of-Thought Prompting Elicits Reasoning in Large Language Models" (Google Brain) — the canonical CoT paper showing dramatic accuracy gains on math and logic benchmarks.
2022
Kojima et al. (University of Tokyo / Microsoft) publish "Large Language Models are Zero-Shot Reasoners", introducing the "Let's think step by step" zero-shot trigger.
2022
Wang et al. introduce Self-Consistency in "Self-Consistency Improves Chain of Thought Reasoning in Language Models", sampling multiple chains and majority-voting to further improve reliability.
2022
Least-to-most prompting (Zhou et al.) extends CoT by first decomposing a problem into sub-problems and solving each in sequence — a form of hierarchical CoT.
2023
Tree of Thoughts (Yao et al., Princeton / Google DeepMind) generalises chains into branching search trees with backtracking, treating reasoning as deliberate heuristic search.
2024
OpenAI's o1 and o3 model family internalises extended CoT as a first-class training objective via reinforcement learning, blurring the line between prompting technique and model architecture.

Why It Matters

Real-World Impact
OpenAI o1 / o3These models were explicitly trained to produce long internal reasoning chains (visible as "thinking" tokens) before answering — a direct productisation of CoT, achieving state-of-the-art results on competition mathematics (AIME) and PhD-level science (GPQA).
Google Gemini UltraUses CoT-style prompting internally for multi-step reasoning tasks; Google's benchmarks show CoT accounts for a large fraction of Gemini's advantage on MATH and GSM8K datasets over vanilla prompting.
Microsoft Copilot for CodeWhen generating complex multi-function code, Copilot decomposes the problem into sub-tasks in comments before writing code — a practical application of least-to-most CoT.
Medical Diagnosis AssistantsResearch systems like Med-PaLM 2 use CoT prompting to have models articulate differential diagnoses step-by-step before recommending a conclusion, making outputs auditable by clinicians.
LangChain / LlamaIndex Agent PipelinesReAct (Reasoning + Acting) agents — widely deployed in production LLM pipelines — are a direct extension of CoT where reasoning steps are interleaved with tool calls (web search, code execution), enabling LLMs to solve problems requiring external information.
GSM8K Benchmark (Grade School Math)CoT prompting on PaLM 540B improved accuracy from 17% (standard prompting) to 58% — a 3× improvement on the same model with no weight updates, purely through prompt design.
Automated Scientific Literature ReviewTools like Elicit and Consensus use CoT-inspired prompting to have models extract claims, assess evidence quality, and synthesise conclusions step-by-step rather than hallucinating summaries.

Prerequisites

What This Leads To

See Also

Prompt Engineering · In-Context Learning · Emergent Abilities in LLMs · ReAct Prompting · Tree of Thoughts

Before this