Sub topic 8
Asking for Step-by-Step Reasoning
This chapter assumes you have read the earlier chapters on clear instructions, few-shot examples, and output formats. You should be comfortable reading short Python snippets and basic JSON. Here you will learn when asking a model to show its work improves answers, how to ask for it, and how to keep the reasoning from breaking your output format.
Why reasoning prompts help
A language model produces its reply one token at a time. Each token is chosen based on the prompt plus all the tokens it has already written. The model has no hidden scratchpad that runs before the first word of the reply. If the answer to a question depends on several intermediate facts, and the model must write the answer first, it has to compute all of those facts "in one step" while choosing the first few tokens.
When the model writes intermediate steps, those steps become part of the context for everything that follows. The final answer can then depend on text that already exists on the page. This is the core idea behind step-by-step reasoning prompts, often called chain-of-thought prompting.
Consider this question:
A shop sells pens in packs of 12 for $3.60. A school needs 150 pens.
What is the cheapest way to buy at least 150 pens, and what does it cost?A model that answers immediately might write "$45.00" without checking. A model that first writes "150 / 12 = 12.5, so 13 packs are needed, and 13 × $3.60 = $46.80" is much more likely to reach a correct answer. The steps are not decoration. They are working memory.
What reasoning prompts do not do
- They do not make a model understand something it cannot do. They give it room to use abilities it already has.
- They do not guarantee that the written steps match what happens inside the model. A fluent explanation can still contain a wrong step, or can justify a conclusion that was reached some other way.
- They do not remove the need to check results. A wrong step usually leads to a confident, wrong answer.
Three ways to ask for reasoning
There are three common approaches. They differ in how much control you have.
Zero-shot reasoning instruction
Add a short instruction that asks the model to work through the problem before answering.
Work through the problem step by step, then give the final answer on a
last line that starts with "Answer:".
Problem:
"""
A shop sells pens in packs of 12 for $3.60. A school needs 150 pens.
What is the cheapest way to buy at least 150 pens, and what does it cost?
"""This is the cheapest option. It needs no examples. The weakness is that you do not control the style or depth of the steps.
Few-shot reasoning examples
Show one or two worked examples where the reasoning appears before the answer. The model copies the pattern. This gives you control over the shape of the reasoning, such as numbered steps or a fixed set of headings, at the cost of a longer prompt.
Named steps
When the task has a known procedure, spell the steps out yourself. This is closer to prompt decomposition, which a later chapter covers, but within a single prompt.
Review the contract clause below. Do these in order:
1. Quote the sentence that sets the payment deadline.
2. State the deadline as a number of days.
3. Say whether the deadline is shorter than 30 days.
4. Finish with "Answer: yes" or "Answer: no".
Clause:
"""
{clause_text}
"""Named steps work well because you decide what counts as a step. They also make failures easier to find, because you can see which step went wrong.
| Approach | Control over steps | Prompt length | Best when |
|---|---|---|---|
| Zero-shot instruction | Low | Short | Quick checks, general problems |
| Few-shot examples | Medium | Long | You need a consistent reasoning style |
| Named steps | High | Medium | The procedure is known in advance |
When reasoning helps and when it does not
Reasoning prompts help most on tasks with several dependent parts:
- Arithmetic and unit conversions.
- Multi-condition rules, such as eligibility or policy checks.
- Questions where the model must find facts in a document and then combine them.
- Logic puzzles and scheduling problems.
- Debugging, where the model must trace what code does.
They help little, and cost extra, on tasks like these:
- Simple lookups or rewrites, such as "translate this sentence".
- Tasks of style or taste, such as naming a product.
- Classification where the label is obvious from surface features.
Extra reasoning has real costs. It adds output tokens, which increases latency and price. It also adds more text that can contain errors. For a simple sentiment label, a direct answer is usually faster, cheaper, and just as accurate.
Some current models perform extended reasoning on their own before they reply, sometimes called "thinking" modes. With those models, a prompt that says "think step by step" may add little, and detailed instructions about how to reason can even get in the way. Check your model's documentation, and test both versions against your own cases, as described in the evaluation chapter.
Keeping reasoning separate from the answer
The main practical problem with reasoning prompts is that the reply now contains two things: the working and the answer. If your code needs only the answer, you must make the two easy to tell apart.
The simplest fix is a marker. Ask for a final line with a fixed prefix, then extract it.
import re
def extract_answer(reply):
"""Return the text after the last 'Answer:' line, or None."""
matches = re.findall(r"^Answer:\s*(.+)$", reply, flags=re.MULTILINE)
if not matches:
return None
return matches[-1].strip()
reply = """150 / 12 = 12.5, so we need 13 packs.
13 x 3.60 = 46.80
Answer: $46.80"""
print(extract_answer(reply))
print(extract_answer("I think it costs about forty-six dollars."))The function takes the last match, because the model may mention the word "Answer:" earlier in its working. It returns None when the marker is missing, so the caller can retry or flag the reply, just as with the JSON validation in the previous chapter.
Reasoning with structured output
If you want JSON, place the reasoning in its own field and put it before the answer field. Order matters. The model writes fields in sequence, so a reasoning field that comes first can influence the answer field that follows. If answer comes first, the model has to commit to a result before it has written any working.
import json
PROMPT = """Decide whether the order qualifies for free shipping.
Rules: free shipping applies to orders of $50 or more after discounts.
Reply with JSON only, using exactly these keys in this order:
"reasoning": a short explanation of the calculation
"free_shipping": true or false
Order:
\"\"\"
Items: $62.00. Discount code: 20% off.
\"\"\"
"""
def parse_shipping(reply):
try:
data = json.loads(reply)
except json.JSONDecodeError:
return None
if not isinstance(data, dict):
return None
if not isinstance(data.get("free_shipping"), bool):
return None
return data
good = '{"reasoning": "62.00 * 0.8 = 49.60, below 50.", "free_shipping": false}'
print(parse_shipping(good))
print(parse_shipping("The order does not qualify."))Note the rule in the prompt: "after discounts". A model that answers without working might see $62 and say yes. The reasoning field pushes it to apply the discount first, and the correct result is false.
Some APIs offer a structured-output feature that forces a reply to match a schema. Even then, keep a reasoning field in the schema if you want working before the answer, and keep the validation in your code.
Showing the reasoning to users
Should you show the working to the people using your product? Consider these points:
- Visible working helps users check the result and builds trust when it is correct.
- Visible working can be wrong while sounding convincing, which can make a bad answer look more reliable.
- Long working is noise when the user only needs a result.
A common pattern is to ask for reasoning, store it for debugging, and show users only the final answer, perhaps with a short justification. Decide this deliberately instead of by default.
Checking reasoning
Because written steps can be wrong, build in checks where the cost of an error is high.
- Ask for verification. Add a final step such as "Re-check each calculation, then state the answer." This catches some arithmetic slips, though not all, since the same model does the checking.
- Use code for exact work. For arithmetic, do not rely on the model at all. Ask it to extract the numbers, then compute in Python.
- Sample several times and compare. Run the same prompt a few times with a nonzero temperature. If the final answers disagree, treat the result as uncertain. Taking the most common answer is called self-consistency. It costs several calls per question, so reserve it for questions that matter.
- Ask for evidence. For document questions, require a quote for each claim, as in the named-steps example. Quotes can be checked mechanically by searching for them in the source text.
The sketch below shows the sampling check, using the same call_model convention as the evaluation chapter. It reuses extract_answer from above.
from collections import Counter
def majority_answer(call_model, prompt, runs=5):
"""Return (answer, agreement) from several runs of the same prompt."""
answers = []
for _ in range(runs):
answer = extract_answer(call_model(prompt))
if answer is not None:
answers.append(answer)
if not answers:
return None, 0.0
best, count = Counter(answers).most_common(1)[0]
return best, count / runsIf agreement is low, send the item for human review instead of trusting it.
Common errors
- Answer before reasoning. Prompts like "Give the answer, then explain" produce an answer with no working behind it, followed by a justification written afterward. Put the reasoning first.
- No stable marker. Without a fixed prefix such as
Answer:, your parser will fail on small wording changes. - Reasoning on trivial tasks. This adds cost without improving accuracy. Measure before adding it.
- Trusting fluent steps. A tidy list of steps is not proof. Check outputs against known cases.
- Leaking untrusted instructions. If the input text contains instructions, the model may follow them in its working. Keep delimiters around input, as covered earlier, and see the chapter on prompt injection.
- Very long reasoning on long inputs. The model may lose track of early details. Break the task into chained prompts, covered in the next chapter.
Putting it together
A reasoning prompt for a real task combines techniques from earlier chapters: a clear instruction, delimited input, a defined output format, and a marker or field for the final answer.
You are checking expense claims against company policy.
Policy:
"""
- Meals are reimbursed up to $40 per day.
- Receipts are required for any single item above $25.
"""
Claim:
"""
{claim_text}
"""
Steps:
1. List each expense with its amount and whether a receipt is attached.
2. Compare each expense to the policy rules.
3. If any rule is broken, name the rule.
End with one line: "Answer: approve" or "Answer: reject".Each step maps to a rule, so a wrong decision can be traced to a specific step. That traceability is often more valuable than the small accuracy gain alone.
Exercise
A prompt asks a model to reply with JSON in the form {"answer": "...", "reasoning": "..."} for a multi-step arithmetic question. Accuracy is lower than expected. What change would you try first, and how would you confirm it helped?
Show answer
Swap the key order so "reasoning" comes before "answer", because the model writes fields in sequence and the answer should be able to depend on the working. To confirm, run both prompt versions on the same labeled test cases with an accuracy function like the one in the evaluation chapter, and compare the scores. Also check that the output still parses with your validation code.
Exercise
You need an exact total from a list of 40 invoice lines. Reasoning in the prompt gives mostly correct but occasionally wrong sums. What is a more reliable design?
Show answer
Use the model only to extract the 40 amounts as structured data, validate them, and compute the sum in code. Models can make arithmetic slips even when they show their steps, while code gives an exact result. Step-by-step reasoning is better suited to judgments than to exact calculation.