TExcelTAD
Home › Generative AI & LLMs › Step-by-step Reasoning

Step-by-step Reasoning

An LLM produces its answer one token at a time, and each token gets roughly the same amount of computation. For a multi-step problem, jumping straight to the final answer means doing all the work "in one token". Letting the model write out intermediate steps first gives it room to compute: each step becomes part of the context for the next. This is called chain-of-thought (CoT) prompting.

A problem that needs steps

A café sells muffins for 3 € each. A box of 6 costs 15 €. Leo needs 14 muffins. What is the cheapest total price?

A rushed answer might say 14 × 3 = 42 € or 3 boxes = 45 €. Working it out step by step finds the better mix. Here is that reasoning written as code, so you can see what the steps are:

python · try it yourself
SINGLE, BOX_SIZE, BOX_PRICE = 3, 6, 15
needed = 14

options = []
for boxes in range(needed // BOX_SIZE + 2):
    singles = max(0, needed - boxes * BOX_SIZE)
    cost = boxes * BOX_PRICE + singles * SINGLE
    options.append((cost, boxes, singles))
    print(f"step: {boxes} box(es) + {singles:2} single(s) = {cost} €")

best = min(options)
print(f"answer: {best[1]} boxes + {best[2]} singles for {best[0]} €")
step: 0 box(es) + 14 single(s) = 42 €
step: 1 box(es) +  8 single(s) = 39 €
step: 2 box(es) +  2 single(s) = 36 €
step: 3 box(es) +  0 single(s) = 45 €
answer: 2 boxes + 2 singles for 36 €

A model prompted to "think step by step" writes a natural-language version of this table before giving the answer, and is much more likely to land on the correct 36 €.

How to ask for reasoning

Technique Prompt wording (example)
Plain CoT "Think through the problem step by step, then give the answer."
Structured CoT "First list the facts, then compute each option, then choose."
Separate scratchpad "Write your reasoning inside <thinking> tags and the final answer inside <answer> tags."
Built-in reasoning Many current models have an extended thinking / reasoning mode that you switch on with an API parameter instead of prompt wording

Separating reasoning from the answer matters in apps: users often want only the answer, and your code needs to find it reliably.

python · try it yourself
import re

# An illustrative model reply (hand-written, not from a real run)
reply = """<thinking>
14 muffins needed. Singles only: 14 x 3 = 42.
Two boxes give 12 muffins for 30, plus 2 singles = 6, total 36.
Three boxes give 18 muffins for 45, more than needed.
36 is cheapest.
</thinking>
<answer>36 €</answer>"""

def extract(tag, text):
    match = re.search(rf"<{tag}>(.*?)</{tag}>", text, re.DOTALL)
    return match.group(1).strip() if match else None

print("answer:", extract("answer", reply))
print("reasoning lines:", len(extract("thinking", reply).splitlines()))
answer: 36 €
reasoning lines: 4

Self-consistency: ask several times, vote

Because sampling is random, different runs may take different reasoning paths. Self-consistency samples several answers (with temperature > 0) and takes the majority vote of the final answers. Errors tend to scatter, while correct reasoning tends to converge.

python · try it yourself
from collections import Counter

# Final answers from 7 hypothetical sampled reasoning chains
sampled_answers = ["36 €", "36 €", "42 €", "36 €", "45 €", "36 €", "36 €"]

votes = Counter(sampled_answers)
answer, count = votes.most_common(1)[0]
print("votes:", dict(votes))
print(f"majority answer: {answer} ({count}/{len(sampled_answers)} = {count / len(sampled_answers):.0%})")
votes: {'36 €': 5, '42 €': 1, '45 €': 1}
majority answer: 36 € (5/7 = 71%)

The agreement rate is also a useful confidence signal: if the votes are split, flag the answer for review. The trade-off is cost — seven samples cost roughly seven times as many tokens.

Decompose big tasks

For larger jobs, split the work into separate prompts (prompt chaining): one call extracts facts, the next analyses them, the next writes the final text. Each step is simpler, easier to test and can use a cheaper model. You'll see this pattern again in Agents.

python · try it yourself
def step_extract(text):
    return [w.strip(".,") for w in text.split() if w.strip(".,").isdigit()]

def step_compute(numbers):
    return sum(int(n) for n in numbers)

def step_write(total):
    return f"The order contains {total} items in total."

note = "Order: 4 notebooks, 12 pens and 3 folders."
facts = step_extract(note)
total = step_compute(facts)
print("extracted:", facts)
print(step_write(total))
extracted: ['4', '12', '3']
The order contains 19 items in total.

In a real pipeline step_extract and step_write would be model calls and step_compute plain code — use code for arithmetic whenever you can.

When reasoning helps — and when it doesn't

  • Helps: maths word problems, logic puzzles, planning, multi-step analysis, debugging.
  • Little benefit: simple lookups, short classification, rewriting text.
  • Costs: more output tokens → more latency and cost.
  • Caveat: a written chain of thought is not guaranteed to be a faithful account of how the model actually reached its answer. Check the answer, not just the reasoning's tone.

Test yourself

Why can chain-of-thought prompting improve answers to multi-step problems?

  1. It makes the model bigger
  2. Intermediate steps become context the model can build on, giving it more computation before the answer
  3. It disables sampling
  4. It shortens the prompt

What does self-consistency do?

  1. Uses the same random seed every time
  2. Samples several reasoning paths and takes the majority final answer
  3. Checks the grammar of the answer
  4. Asks the user to confirm

Why ask the model to put its final answer inside <answer> tags?

  1. Tags make answers more accurate by themselves
  2. So your code can reliably separate the answer from the reasoning
  3. The API rejects untagged text
  4. To reduce token usage