Sub topic 10
Showing reasoning in examples
This chapter assumes you can read short Python, know what system, user, and assistant roles are in a chat prompt, and have read the earlier chapters on example anatomy and format consistency. It covers how to put reasoning steps into few-shot examples and how to read the answer back out reliably.
Why reasoning in examples helps
In a plain few-shot prompt, each example maps an input straight to a label. The model learns to produce a label immediately after the input. For simple tasks that is enough. For tasks where the answer depends on several facts, such as mixed reviews, multi-step arithmetic, or policy rules with exceptions, jumping straight to the label gives the model no room to work.
A model generates text one token at a time, and each token can only depend on the tokens before it. If the examples show a short chain of reasoning before the answer, the model tends to write its own reasoning first. That reasoning becomes part of the context for the final answer. This technique is usually called chain-of-thought prompting. When the chain is demonstrated through examples, it is few-shot chain-of-thought.
The technique has three effects:
- The model spends tokens on intermediate steps, so the final answer can use them.
- The reasoning is visible, so you can see why an answer was wrong.
- The examples teach a method as well as a format. The model copies how you break the problem down.
The cost is more output tokens, more latency, and a second format to keep consistent.
What a reasoning example looks like
Each example now has three parts: the input, the reasoning, and the final answer. The reasoning must come before the answer. If you put the label first and the explanation after, the model commits to a label with no working, and the explanation becomes a justification of a guess.
Here is the sentiment task from earlier chapters, changed to use reasoning. The reviews are chosen because they are hard to label in one step.
Classify the sentiment of each review as positive, negative, or neutral.
Think step by step in one or two sentences, then give the label on a final line.
Review: The screen is gorgeous, but it died after two days.
Reasoning: The screen praise is positive, but the device failing after two days is a serious defect that outweighs it.
Sentiment: negative
Review: Delivery was on Tuesday and the box was the expected size.
Reasoning: The review states facts about delivery and size with no praise or complaint.
Sentiment: neutral
Review: I expected little, and it still managed to disappoint me less than my last phone.
Reasoning: The wording is lukewarm, but the comparison to the previous phone is favorable, so the overall feeling is mildly positive.
Sentiment: positive
Review: The speakers are weak, though the camera is excellent and the battery lasts two days.
Reasoning:Three details matter here.
- The reasoning line has a fixed label (
Reasoning:) and the answer has a fixed label (Sentiment:). The model learns both slots. - The reasoning is short and of similar length in every example. Long, uneven reasoning in examples produces long, uneven reasoning in outputs.
- The reasoning names the evidence from the input. It does not just restate the label.
Building the prompt in code
The structure from earlier chapters extends with one more field per example. The builder below produces a single text prompt. It ends with the Reasoning: label so the model starts by thinking, not by answering.
import re
INSTRUCTION = (
"Classify the sentiment of each review as positive, negative, or neutral.\n"
"Think step by step in one or two sentences, then give the label on a final line."
)
examples = [
(
"The screen is gorgeous, but it died after two days.",
"The screen praise is positive, but the device failing after two days is a serious defect that outweighs it.",
"negative",
),
(
"Delivery was on Tuesday and the box was the expected size.",
"The review states facts about delivery and size with no praise or complaint.",
"neutral",
),
(
"I expected little, and it still managed to disappoint me less than my last phone.",
"The wording is lukewarm, but the comparison to the previous phone is favorable, so the overall feeling is mildly positive.",
"positive",
),
]
def build_prompt(examples, query):
parts = [INSTRUCTION]
for text, reasoning, label in examples:
parts.append(
f"Review: {text}\nReasoning: {reasoning}\nSentiment: {label}"
)
parts.append(f"Review: {query}\nReasoning:")
return "\n\n".join(parts)
def extract_label(completion):
matches = re.findall(r"Sentiment:\s*(positive|negative|neutral)", completion, re.IGNORECASE)
return matches[-1].lower() if matches else None
if __name__ == "__main__":
prompt = build_prompt(
examples,
"The speakers are weak, though the camera is excellent and the battery lasts two days.",
)
print(prompt.splitlines()[-2:])
fake_completion = (
" Two strong positives outweigh one weakness.\n"
"Sentiment: positive"
)
print(extract_label(fake_completion))The extraction function matters as much as the prompt. With a plain label, you can compare the whole completion to the expected string. With reasoning, the completion contains extra text, and the reasoning itself may mention words like "positive" or "negative". Matching on the Sentiment: marker and taking the last match avoids reading a label out of the middle of the reasoning. If nothing matches, the function returns None, which you should count as a failure and not guess around.
Using chat messages
In a chat format, the assistant turn in each example holds both the reasoning and the final line. Do not split them across separate turns. The model should see one assistant message with the whole pattern.
SYSTEM = (
"Classify the sentiment of each review as positive, negative, or neutral. "
"Write one or two sentences of reasoning on a line starting with 'Reasoning:', "
"then the answer on a final line starting with 'Sentiment:'."
)
def build_messages(examples, query):
messages = [{"role": "system", "content": SYSTEM}]
for text, reasoning, label in examples:
messages.append({"role": "user", "content": text})
messages.append(
{
"role": "assistant",
"content": f"Reasoning: {reasoning}\nSentiment: {label}",
}
)
messages.append({"role": "user", "content": query})
return messagesThe same extract_label function works on the reply.
Choosing and writing reasoning
Pick examples where reasoning changes the outcome. A review like "I love it" needs no reasoning, and showing reasoning for it teaches nothing. Good candidates are:
- Mixed signals, where positives and negatives compete.
- Cases that look like one label but belong to another, such as sarcasm.
- Edge cases from the earlier chapter, such as out-of-scope input, where the reasoning explains why the input is out of scope.
When you write reasoning, follow these rules:
- Write the reasoning you want the model to imitate, not a post-hoc excuse. Check that each reasoning line actually leads to its label.
- Keep the steps short and concrete. Cite the words or numbers in the input.
- Use the same voice and structure in every example. If one example lists steps and another writes a paragraph, outputs will vary.
- Do not put a wrong step in an example, even by accident. The model copies errors as readily as good steps.
For arithmetic or rule-based tasks, spell out each calculation or rule in order. For judgment tasks like sentiment, one or two sentences of evidence is enough.
Costs and failure modes
| Problem | What you see | What to do |
|---|---|---|
| Longer outputs | Higher token cost and latency per query | Keep reasoning to one or two sentences, and compare the accuracy gain with the cost |
| Reasoning and answer disagree | The reasoning says "mildly positive" but the label is "neutral" | Fix examples so the reasoning clearly entails the label, and score only the final line |
| Unparseable output | `extract_label` returns `None` | Use fixed labels, end the prompt with `Reasoning:`, and count `None` as wrong |
| Copied reasoning | The model repeats phrases from an example | Vary the wording across examples and use varied inputs |
| Reasoning that doesn't help | Accuracy is equal to or lower than direct labels | Drop it. Not every task benefits |
Reasoning does not guarantee a correct answer. A model can write fluent, plausible steps that lead to a wrong conclusion. Treat the reasoning as a debugging aid and a nudge, not as proof.
Testing whether reasoning helps
Do not assume reasoning improves results. Compare two prompt variants on the same held-out labeled data, one with direct labels and one with reasoning, using the accuracy function from the evaluation chapter. Because the reasoning variant returns extra text, wrap it so that predict returns only the extracted label:
def accuracy(predict, labeled):
correct = 0
for text, label in labeled:
if predict(text).strip().lower() == label:
correct += 1
return correct / len(labeled)
def make_cot_predict(call_model, examples):
def predict(text):
completion = call_model(build_prompt(examples, text))
return extract_label(completion) or ""
return predictHere call_model is any function that takes a prompt string and returns the completion text. An empty string never equals a real label, so unparseable outputs count as wrong.
Look at the cases where the two variants disagree. If reasoning fixes mixed-signal reviews but breaks simple ones, you may want to keep reasoning examples only for hard cases or route inputs to different prompts. Also record token usage, since a small accuracy gain may not justify several times the output length.
Exercise
A few-shot prompt for classifying support tickets uses this example format: "Ticket: ... / Category: billing / Why: the customer mentions an incorrect charge." The model often outputs the category correctly but a different wrong category in the reasoning of other tickets, and your parser reads the first line containing "billing". Name two changes that make the output more reliable.
Show answer
First, put the reasoning before the answer (Why: before Category:) so the answer follows from the steps, and end the prompt with the reasoning label. Second, parse only the final labeled line (for example, the last match of "Category:\s*(\w+)") instead of the first mention of a category word, and treat no match as a failure. Keeping reasoning short and uniform across examples also helps.
Exercise
You compare a direct-label prompt (82% accuracy, about 5 output tokens per query) with a reasoning prompt (85% accuracy, about 60 output tokens per query) on 200 held-out reviews. What else should you check before choosing the reasoning prompt?
Show answer
Check which cases improved or got worse (the disagreements), whether the 3-point gain is meaningful on 200 items (it is about 6 reviews, so it may be noise), the unparseable-output rate, and whether the roughly twelvefold increase in output tokens, with its cost and latency, is acceptable for your application.