Examples, Reasoning Instructions and Voting
Know when zero-shot is enough, how to choose few-shot examples that help rather than mislead, when to ask for step-by-step reasoning, and what self-consistency voting buys for its extra calls.
Contentsand lesson path
On this page
- Why it matters
- Zero-shot, one-shot and few-shot
- Choosing and ordering examples
- Asking for step-by-step reasoning
- Self-consistency: sample several answers and vote
- Check your understanding
- Apply it
- Review prompt
Lessons of Prompt Basics
- What a Model Needs from a Prompt Concept · 15 min
- Rewriting a Vague Prompt Worked example · 15 min
- Examples, Reasoning Instructions and Voting Concept · 20 min
- Lab: Compare Two Prompts on 20 Inputs Lab · 25 min
- Lab: Validated JSON from a Prompt Lab · 20 min
- Check: Diagnose Prompt Failures Knowledge check · 8 questions
What you will learn
- Apply zero-shot and few-shot prompting, step-by-step reasoning instructions and self-consistency voting, and explain when each helps or hurts.
01. Why it matters
The previous lessons made the instructions clear. Three further techniques change what the model does with them: showing examples, asking for reasoning before the answer, and asking several times and taking a vote. Each can raise accuracy, and each has a price in tokens, latency or new ways to fail, so none is worth adding "just in case". This lesson explains when each one helps and when it hurts, so that you know what to try and what to measure in the lab that follows.
02. Zero-shot, one-shot and few-shot
A zero-shot prompt describes the task and gives no examples; every prompt so far was zero-shot. A one-shot prompt adds one worked example, and a few-shot prompt adds several, typically three to five. The examples sit in the prompt and change no model weights. They work because the model continues patterns it sees in its context.
Zero-shot is the right starting point when the task is common and the instructions pin it down, as with sorting tickets into well-defined categories. Examples earn their tokens in three situations:
- Format or style that is easier to show than to describe, such as a house style for ticket summaries.
- Fuzzy boundaries between labels. One example of "our admin left, how do we take over the workspace?" labelled
accountsettles a case that a paragraph of definitions might not. - Conventions the model would not guess, such as internal labels or codes.
Examples cost something too. They add tokens to every request, and the model copies more from them than you intend: their length, tone, language and even single words become signals. If every example is a short, polite English ticket, a long, angry ticket in German resembles none of them. With a single example, all of its incidental features look like rules.
03. Choosing and ordering examples
Choose examples the way you would choose test cases:
- Representative: taken from or modelled on real traffic, not textbook cases.
- Balanced: the same number per label. If three of four examples are billing, the model leans towards billing on unclear tickets.
- Near the boundaries: for each label, include a ticket that could pass for another label, because that is where the model hesitates.
- Varied on the surface: mix length, tone and language so that none of them becomes a cue.
- Separate from your test set: an example that also appears among the tickets you measure on inflates the score.
Order matters a little. Models tend to give extra weight to what comes last, so do not put all the examples of one label at the end. Shuffle once with a fixed seed and keep that order: reshuffling on every request changes the prompt each time, which makes results harder to compare and prevents the provider from caching the prompt. The helper below refuses an unbalanced set and builds the tagged block.
import random
import re
from collections import Counter
LABELS = ("billing", "bug", "account", "other")
EXAMPLES = [
("Billed for 12 seats but we only have 9 people.", "billing"),
("Can we pay by bank transfer instead of card?", "billing"),
("Uploading an attachment spins forever, then the page goes blank.", "bug"),
("Since Monday the search box returns nothing for any query.", "bug"),
("Our admin left. How do we transfer ownership of the workspace?", "account"),
("I never received the code to confirm my new email address.", "account"),
("A dark mode would be great. Is it planned?", "other"),
("How do I export a board as a spreadsheet?", "other"),
]
def examples_block(examples: list[tuple[str, str]], seed: int = 3) -> str:
counts = Counter(label for _, label in examples)
if set(counts) != set(LABELS) or len(set(counts.values())) > 1:
raise ValueError(f"unbalanced or missing labels: {dict(counts)}")
shuffled = examples[:]
random.Random(seed).shuffle(shuffled) # fixed seed: same order on every run
parts = [
f"<example>\n<ticket>{text}</ticket>\n<label>{label}</label>\n</example>"
for text, label in shuffled
]
return "<examples>\n" + "\n".join(parts) + "\n</examples>"
if __name__ == "__main__":
block = examples_block(EXAMPLES)
print(re.findall(r"<label>(\w+)</label>", block))
try:
examples_block(EXAMPLES[:5])
except ValueError as err:
print(err)python examples.py['billing', 'account', 'other', 'bug', 'billing', 'other', 'account', 'bug']
unbalanced or missing labels: {'billing': 2, 'bug': 2, 'account': 1}The fixed shuffle interleaves the labels, and the first five examples, which have no other example and only one for account, are refused before they reach a model. Every example uses the same <ticket> and <label> tags, so the model can tell examples apart from instructions and from the ticket it has to classify.
04. Asking for step-by-step reasoning
Some questions need intermediate steps: a prorated charge, a refund rule with three conditions, a comparison of two documents. A model that answers straight away has to squeeze those steps into the first words of its reply, and it often slips. Asking it to work through the steps first, known as chain-of-thought prompting, gives it room to get the intermediate results right. Wei et al. (2022) reported large gains on arithmetic, commonsense and symbolic reasoning benchmarks, but only for large models; small models gained little or nothing.
With a model that does not reason on its own, ask for the reasoning and the answer in separate tags, so that code can pick out the answer and ignore the rest:
<instructions>
Work out the extra charge. First, inside <reasoning> tags, count the days that
are charged, find the price of one seat for one day, then multiply. After that,
give only the amount in euros, with two decimals, inside <answer> tags.
</instructions>Three cautions apply:
- It costs tokens and time. Reasoning is billed as output and slows every reply. On simple lookups, such as sorting a clear ticket, it adds cost without adding accuracy.
- Reasoning models already think. Current models from the major providers can reason internally before they answer, and you control how much through a setting such as effort or a thinking budget rather than through the prompt. Asking such a model to write out its steps in the visible reply is redundant, and some providers advise against it: current Claude models may decline prompts that ask them to expose their reasoning. Ask only for the answer format, such as the
<answer>tags, and tune the reasoning setting instead. - Measure it. Whether reasoning helps your task with your model is an empirical question. Run the prompt with and without the instruction, or at two effort levels, on the same inputs, and compare accuracy, cost and latency.
05. Self-consistency: sample several answers and vote
A model samples each token, so the same question can get different answers on different runs. When the answer is a single value, you can turn that variation into a check: ask several times, extract each final answer and keep the one that most samples agree on. Wang et al. (2022) called this self-consistency and showed that the majority answer beats a single, greedily chosen answer on arithmetic and commonsense reasoning benchmarks.
The samples must differ, or the vote means nothing. Where an API exposes temperature, sample above 0. Some current models do not expose it: from API version 2026-10-21, which the anthropic 2.x SDKs send, Claude no longer accepts temperature, top_p or top_k at all, even at their default values. Its default sampling already varies from call to call, so you simply call it several times.
The code below uses a FAKE model so that it runs offline and prints the same output every time. Its answer to a billing question is wrong four times in ten, with the day count off by one in either direction, as sampled reasoning sometimes is. The right answer is 3 seats × 12 euros × 15 days / 30 days = 18.00 euros.
import random
import re
from collections import Counter
QUESTION = (
"The Team plan costs 12 euros per seat for a 30-day month. A customer adds"
" 3 seats on day 16 and pays for days 16 to 30. What is the extra charge?"
)
def fake_sample(question: str, rng: random.Random) -> str:
"""FAKE model call for offline practice. Like a sampled reply, its day
count is sometimes off by one: right 6 times in 10, wrong 4 times."""
days = rng.choices([15, 14, 16], weights=[6, 2, 2])[0]
charge = 3 * 12 * days / 30
return f"Days 16 to 30 are {days} days, so ...\n<answer>{charge:.2f}</answer>"
def extract_answer(reply: str) -> str | None:
match = re.search(r"<answer>\s*(.*?)\s*</answer>", reply, re.S)
return match.group(1) if match else None
def vote(answers: list[str | None], min_share: float = 0.6) -> str | None:
"""The majority answer, or None on a tie or when too few samples agree."""
counts = Counter(answer for answer in answers if answer is not None)
if not counts:
return None
(best, votes), *others = counts.most_common()
if others and others[0][1] == votes:
return None
return best if votes / len(answers) >= min_share else Noneimport random
from collections import Counter
from vote import QUESTION, extract_answer, fake_sample, vote
rng = random.Random(6)
answers = [extract_answer(fake_sample(QUESTION, rng)) for _ in range(5)]
print("one question:", answers, "->", vote(answers))
trials = 2000
tally = Counter()
for _ in range(trials):
answers = [extract_answer(fake_sample(QUESTION, rng)) for _ in range(5)]
voted = vote(answers)
tally["first sample right"] += answers[0] == "18.00"
tally["first sample wrong"] += answers[0] != "18.00"
tally["vote right"] += voted == "18.00"
tally["vote wrong"] += voted not in (None, "18.00")
tally["no clear majority"] += voted is None
for outcome, count in tally.items():
print(f"{outcome:>18}: {count / trials:.0%}")python simulate.pyone question: ['16.80', '19.20', '18.00', '18.00', '18.00'] -> 18.00
first sample right: 60%
first sample wrong: 40%
vote right: 68%
vote wrong: 12%
no clear majority: 20%Read the result in three parts. A single answer is wrong 40% of the time. A vote of five is wrong only 12% of the time, because wrong answers rarely agree on the same wrong value. And for 20% of questions no answer reaches three votes, so vote() returns None. Treat that as "unsure" and fall back, for example to a person: the share of samples that agree is a useful confidence signal in its own right.
The price is five calls per question, so five times the tokens, and more waiting unless you send the calls in parallel. Voting suits short answers that can be compared exactly, such as a label, a number or yes and no. It does not work for free text, where no two samples match. With a real model, the sampling function becomes an API call:
import os
import anthropic
from vote import QUESTION, extract_answer, vote
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
SYSTEM = "Put only the final amount in euros, with two decimals, in <answer> tags."
def claude_sample(question: str) -> str:
# No temperature argument: from API version 2026-10-21 Claude rejects
# temperature, top_p and top_k at any value; its sampling varies per call.
response = client.messages.create(
model=os.environ["ANTHROPIC_MODEL"], # for example claude-sonnet-5-5
max_tokens=4096, # leave room for the model's own thinking
system=SYSTEM,
messages=[{"role": "user", "content": question}],
)
return "".join(block.text for block in response.content if block.type == "text")
answers = [extract_answer(claude_sample(QUESTION)) for _ in range(5)] # 5 calls
print(answers, "->", vote(answers))['18.00', '18.00', '18.00', '18.00', '18.00'] -> 18.00A strong model may agree with itself every time on a question this simple, and then the four extra calls bought nothing. That is the general lesson of this page: each technique is a hypothesis about your task, and only a measurement on your own inputs tells you whether it pays.
06. Check your understanding
07. Apply it
Build the improved version of your classifier prompt:
- Label 20 tickets that you will measure on in the lab, five or so per category, and set them aside. None of them may appear as an example.
- From other tickets, choose one example per category, preferring boundary cases, and vary their length, tone and language.
- Build the examples block with a balance check and a fixed order, and add it to a copy of your v1 prompt as
prompts/triage/v2.txt. Change nothing else, so that the comparison tests one idea. - Write down which tickets you expect v2 to fix and which it might break. The lab tests your prediction.
08. Review prompt
Without looking back:
- When is a zero-shot prompt enough, and in which three situations do examples earn their tokens?
- Name four properties of a good example set and the reason for each.
- Why can asking a reasoning model to show its steps be redundant, and what do you adjust instead?
- What does self-consistency need from its samples, what does it cost, and what should code do when no answer has a clear majority?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.