Sub topic 1
Step-by-step reasoning in language models
This chapter covers chain-of-thought prompting, the technique that reasoning models later built into the model itself. You will see why writing out intermediate steps improves answers, which variants exist, and where the technique fails. The later chapters on reasoning tokens, effort levels and budgets assume you understand this one.
Prerequisites
This chapter assumes you have:
- Called an LLM API from code at least once and can read Python.
- A working idea of what a token is, and of the context window and the maximum output length.
- Written basic prompts, including a system message and a user message.
You do not need to know how transformers work internally. The short explanation below is enough.
What step-by-step reasoning means
A language model produces its answer one token at a time. With chain-of-thought (CoT) prompting, the model writes the intermediate steps of a problem before it states the final answer. The steps are ordinary output tokens, so the model can read them as it continues.
Compare two replies to the same question.
Question: a cafe sells coffee for $3.50 and muffins for $2.25. Maya buys 3 coffees and 2 muffins and pays with a $20 bill. How much change does she get?
Direct reply:
$5.00Chain-of-thought reply:
Coffees: 3 x 3.50 = 10.50.
Muffins: 2 x 2.25 = 4.50.
Total: 10.50 + 4.50 = 15.00.
Change: 20.00 - 15.00 = 5.00.
Answer: $5.00Both replies can be right. The direct reply has to produce the result in one step, and on harder problems that is where errors appear. The CoT reply splits the problem into pieces that are each easy.
Why writing steps out helps
A transformer does a fixed amount of computation for each token it generates. A problem that needs ten dependent operations cannot always be solved in the single pass that produces the first token of the answer. Every generated token adds another pass, and the earlier tokens remain in the context, so the model can build on them.
You can treat the written steps as a scratchpad. Three effects follow:
- More computation per problem. A longer reply means more forward passes before the answer is committed.
- Working memory. Partial results such as "10.50" are stored in the text instead of having to be held internally.
- Decomposition. A hard question becomes a series of small questions the model has often seen before.
The next chapter, on spending compute at inference time, develops the first effect further. For now, remember that reasoning improves results because it lets the model compute more before it answers. It is not a different kind of intelligence.
The main techniques
Researchers found several ways to elicit step-by-step output. All of them predate dedicated reasoning models.
| Technique | How it works | Cost | Typical use |
|---|---|---|---|
| Few-shot CoT | The prompt includes worked examples that show the steps. | Longer prompt | A fixed format or domain method that the model should copy |
| Zero-shot CoT | The prompt adds an instruction such as "Think step by step." | One extra line | A quick improvement on a multi-step question |
| Self-consistency | Sample several CoT answers at a nonzero temperature and take the most common final answer. | N times the output tokens | Questions with a short, checkable answer |
| Decomposition prompts | Ask the model to list sub-questions, then answer each in turn. | More calls or longer output | Long, multi-part tasks |
Few-shot CoT comes from Wei et al. (2022), and zero-shot CoT from Kojima et al. (2022). Self-consistency comes from Wang et al. (2022). The idea behind self-consistency is that wrong reasoning paths tend to disagree with each other, while correct paths tend to end at the same answer.
Running it in code
The script below compares a direct prompt with a CoT prompt, then applies self-consistency. It uses a standard (non-reasoning) chat model, because that is where prompting for steps still matters. It needs the openai package and an OPENAI_API_KEY environment variable.
import re
from collections import Counter
from openai import OpenAI
client = OpenAI()
MODEL = "gpt-4o-mini"
QUESTION = (
"A cafe sells coffee for $3.50 and muffins for $2.25. "
"Maya buys 3 coffees and 2 muffins and pays with a $20 bill. "
"How much change does she get?"
)
DIRECT = QUESTION + "\nReply with only the final amount, in the form 'Answer: $X.XX'."
COT = (
QUESTION
+ "\nThink step by step, then finish with one last line in the form 'Answer: $X.XX'."
)
def extract_answer(text):
"""Return the text after the last 'Answer:' marker, or None if it is missing."""
matches = re.findall(r"Answer:\s*(.+)", text)
return matches[-1].strip() if matches else None
def ask(prompt, n=1, temperature=0.0):
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
n=n,
temperature=temperature,
)
return [choice.message.content for choice in response.choices]
def majority_vote(answers):
"""Most common non-empty answer, or None if there are no answers."""
cleaned = [a for a in answers if a]
return Counter(cleaned).most_common(1)[0][0] if cleaned else None
direct_reply = ask(DIRECT)[0]
cot_reply = ask(COT)[0]
print("direct:", extract_answer(direct_reply))
print("cot: ", extract_answer(cot_reply))
samples = ask(COT, n=5, temperature=0.8)
votes = [extract_answer(s) for s in samples]
print("votes: ", votes)
print("self-consistent answer:", majority_vote(votes))Three details in this script matter in real work:
- The prompt fixes a final-line format, so a parser can find the answer without reading the steps.
extract_answertakes the last match. A model sometimes writes "Answer:" earlier in its reasoning while it drafts.- Self-consistency needs a nonzero temperature. At temperature 0 the five samples would be nearly identical and the vote would add nothing.
On an easy question like this one, a modern model will usually answer correctly in both modes. The gap shows up on problems with more dependent steps, so test on your own harder cases.
Common errors and gotchas
The reasoning is not always the real cause of the answer
The written steps look like an explanation, but studies have found cases where they do not reflect what drove the answer. A model can state a tidy justification for an answer it was nudged toward by a hint in the prompt. Treat the steps as useful for accuracy and for debugging, not as proof of how the model decided.
Errors propagate
An early arithmetic slip is carried into every later step, and the model usually does not go back to fix it. A fluent chain with a wrong first line produces a confident wrong answer. Checking intermediate values, for example by running the arithmetic in code, catches these.
Answer first, reasoning second
If your format asks for the answer before the explanation, the model commits to the answer in the first tokens and the "reasoning" that follows only defends it. Put the reasoning first and the answer last.
Parsing breaks silently
If the answer line is missing or phrased differently, extract_answer returns None. Count the None results in your tests. A model that sometimes forgets the format will look less accurate than it really is.
Extra tokens cost money and time
Steps are output tokens, billed at the output rate, and the user waits while they are generated. A CoT reply to a simple lookup question is pure overhead. Self-consistency with five samples costs about five times as much.
CoT does not help every task
Gains are largest on multi-step arithmetic, logic, planning and code reasoning. For classification of obvious cases, simple extraction, or retrieving a fact, written steps often add length without adding accuracy. They can also add chances to go wrong. Smaller models may write steps that look plausible but are wrong, and these can score worse than a direct answer.
From prompting to reasoning models
Chain-of-thought prompting asks the model to reason as part of its visible reply. That has practical limits. The steps take up the reply you intended to show to the user, you have to parse them out, and the quality of the reasoning depends on how you phrased the prompt.
Reasoning models change this arrangement. They are trained, usually with reinforcement learning on problems whose answers can be checked, to produce a long chain of thought before the final answer. The API then treats that thinking as a separate, controllable part of the response. The following chapters cover what that means for tokens, cost, output limits, visibility and the settings you control.
The prompting habits from this chapter carry over only in part. For a reasoning model, an instruction such as "think step by step" is usually redundant, and a later chapter explains how to prompt these models instead.
Summary of the working model
- A model computes a fixed amount per token, so longer reasoning means more computation before the answer.
- Intermediate steps work as a scratchpad that later tokens can read.
- Put the steps before the answer, and fix an answer format you can parse.
- Use self-consistency only for short, comparable answers, and sample at a nonzero temperature.
- Expect extra cost and latency, and measure whether accuracy improves on your own task.
Exercise
A teammate's prompt says: "Give the final answer on the first line, then explain your reasoning below." Accuracy on multi-step word problems is no better than with no reasoning at all. What is the likely cause, and what change would you make?
Show answer
The answer tokens are generated before any reasoning exists, so the explanation that follows cannot influence the answer. Move the reasoning first and put the answer on a final line in a fixed format such as "Answer: ...", then parse that last line.
Exercise
You run self-consistency with 5 samples at temperature 0, and all 5 answers are identical. Why, and how do you fix it? Also, roughly how much more does the output cost compared with a single CoT sample?
Show answer
At temperature 0 the model picks the most likely token each time, so the samples are nearly the same and a vote adds no information. Use a nonzero temperature such as 0.7 to 1.0 so the reasoning paths differ. Output cost is about five times a single sample, because five full reasoning replies are generated and billed.
Exercise
Your parser uses the first "Answer:" match in the reply, and some results look wrong even though the final line is correct. What is going on, and what should the parser do?
Show answer
The model sometimes writes "Answer:" while drafting, so the first match can be an intermediate or tentative value. Use the last match, as in the extract_answer function in this chapter, and count None results to catch replies that miss the format.