Skip to content
Visual explainer 2h to learn 3 steps

Few-shot examples & step-by-step reasoning

Improve accuracy on a task with well-chosen examples and reasoning steps.

By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.

Topic 10 of 33

In short

Few-shot prompting shows the model a handful of input and output examples so it copies the pattern. Asking for step-by-step reasoning can improve accuracy on multi-step problems.

Explained simply

Sometimes it is easier to show than to explain. Few-shot prompting means putting a few examples in the prompt: here is an input, here is the answer I want. The model picks up the pattern and applies it to the new input.

Examples are very good at teaching format, tone and length, and at showing how to handle tricky cases. They are so powerful that the model will copy them closely, including mistakes and quirks. So choose them with care.

For problems with several steps, such as maths or logic, asking the model to work through the steps before giving the answer often improves accuracy. This is called step-by-step or chain-of-thought reasoning.

Both techniques cost something: examples add input tokens to every call, and reasoning adds output tokens and waiting time. The only way to know if they help your task is to measure accuracy with and without them on a set of test cases.

Press Play on a diagram to walk through it one step at a time.

CompareThree prompting styles
Zero-shot
  • Instructions only
  • Shortest and cheapest
  • Fine for clear tasks
Few-shot
  • Adds 2 to 5 examples
  • Teaches format and edge cases
  • Costs more input tokens
Step-by-step
  • Asks to reason first
  • Helps math and logic
  • Longer, slower output
SequenceFew-shot examples as chat turns
User turns
Assistant turns
  1. 1Example input: charged twice
    User turns to Assistant turns: Example input: charged twice
  2. 2Example output: billing
    Assistant turns to User turns: Example output: billing
  3. 3Example input: app crashes on upload
    User turns to Assistant turns: Example input: app crashes on upload
  4. 4Example output: bug
    Assistant turns to User turns: Example output: bug
  5. 5Real input: the new ticket
    User turns to Assistant turns: Real input: the new ticket
  6. 6Real output, same format
    Assistant turns to User turns: Real output, same format

In depth

Why examples work, and what the model copies

Models learn patterns from the prompt itself, without any retraining. This is called in-context learning. From a few examples, the model works out the label set, the output format, the length, the tone and how edge cases are handled.

It copies everything, though, not just what you meant. If all your examples are one sentence long, answers get short. If three of four examples are labelled positive, the model leans positive. If the examples use a slightly different format from your instructions, the examples usually win.

So examples and instructions must agree. Use examples to show what is hard to describe, such as the right level of detail or how to treat a mixed case, and use instructions for rules that must always apply.

  • Examples beat instructions on format
  • The model copies length and wording
  • Label balance in examples shifts the output
  • Examples and instructions must not conflict

Choosing good examples

Start with 2 to 5 examples. Cover every label or output type at least once, and spend your examples on the cases the model gets wrong without them: mixed sentiment, a ticket that fits two categories, an input with missing data. Easy cases teach little.

Vary the surface: short and long inputs, formal and casual writing, so the model learns the rule rather than a style. Keep the formatting of every example identical. Order matters a little too: models tend to be pulled toward the most recent examples, so do not put all examples of one label at the end.

When you have many labelled cases, use dynamic few-shot: embed the new input, find the most similar labelled examples, and insert those. Each request then gets the examples most relevant to it. Never reuse eval items as examples, or your scores will be falsely high.

FlowDynamic few-shot selection
  1. 1
    New input arrives

    e.g. a support ticket

  2. 2
    Embed it

    Same model as the example pool

  3. 3
    Find similar examples

    Top 3 from a labelled pool

  4. 4
    Build the prompt

    Instructions, examples, new input

  5. 5
    Model answers

    Following the closest patterns

Formatting examples: inline or as chat turns

There are two common layouts. Inline: put the examples in the prompt text, each wrapped in labelled tags or with clear Input and Output markers, followed by the real input. Chat turns: add each example as a pair of messages, a user message with the example input and an assistant message with the ideal output, then the real input as the final user message.

Chat turns make the format very clear, because the model sees itself having answered exactly that way before. Inline examples are easier to keep in one template file and mix with explanations, such as why an example got its label.

Either way, keep examples short. A few hundred tokens of examples on every call adds up across thousands of calls, so remove any example that your measurements show does not help.

Step-by-step reasoning: when it helps and how to use it

Asking the model to reason first gives it room to work through intermediate steps in text before committing to an answer. It helps most on multi-step problems: calculations, logic, comparing several conditions, or applying a policy with exceptions. For simple lookups and clear classifications it adds cost and time with little gain.

When you use it, separate the reasoning from the answer. Ask for the reasoning inside one pair of tags and the final answer inside another, or use a structured output with a reasoning field followed by an answer field. Your code then reads only the answer.

Many current models have a built-in thinking or reasoning mode. With those, you usually do not need to write think step by step; describe the goal and constraints clearly instead, and check the provider's guidance. Reasoning tokens are billed as output either way, so measure the cost.

  • Helps: maths, logic, multi-rule policies
  • Little gain: lookups, simple labels
  • Keep the final answer in its own tag or field
  • Reasoning tokens cost money and time

Measuring whether it actually helped

Intuition is a poor guide here; an example that looks helpful can lower accuracy. Build an eval set of 50 to 200 labelled inputs that reflects real traffic, including hard cases, and keep it separate from your examples.

Run each variant on the same set: zero-shot, few-shot, and few-shot with reasoning. Record accuracy, plus average input and output tokens and latency, because a 1 point gain may not be worth twice the cost. Use a low temperature so differences come from the prompt, not chance, and run more than once if the scores are close.

Then read the errors, not just the score. If few-shot fixed mixed cases but broke another label, you have learned which example to change next.

FlowA fair prompt comparison
  1. 1
    Hold out an eval set

    Never used as examples

  2. 2
    Run variant A

    e.g. zero-shot

  3. 3
    Run variant B

    e.g. 4 examples

  4. 4
    Compare numbers

    Accuracy, tokens, latency

  5. 5
    Read the errors

    Which cases changed and why

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Pick representative few-shot examples~40m
  2. 2
    Ask for step-by-step reasoning~40m
  3. 3
    Compare accuracy with and without examples~40m

Key points

  • Pick diverse examples that cover tricky cases, not just easy ones.
  • Examples strongly shape format and length, so make them match what you want.
  • Measure accuracy with and without examples on an eval set.
  • When reasoning is shown, put the final answer in a separate, parseable field.

Key terms

Tap a card to flip it. 0/4 known

Examples

text
Classify the sentiment as positive, negative or mixed.

Review: The app is fast and looks great.
Sentiment: positive

Review: Crashes every time I upload a file.
Sentiment: negative

Review: Love the design, but sync is unreliable.
Sentiment: mixed

Review: {review}
Sentiment:

Three examples, including the tricky mixed case.

Fixing inconsistent labels with examples

A zero-shot ticket router returns labels like Billing issue and billing problem instead of billing, and splits tickets with two problems at random. Step 1: list the exact labels in the system prompt. Step 2: add one example per label as chat turns. Step 3: add one tricky example that shows the rule for mixed tickets (billing wins). Step 4: run your eval set with and without the examples and compare accuracy and token cost.

python
SYSTEM = ("Classify the support ticket. Reply with exactly one label: "
          "billing, bug, feature_request, how_to. If billing is involved, use billing.")
EXAMPLES = [
    ("I was charged twice this month", "billing"),
    ("The app crashes when I upload a PDF", "bug"),
    ("Please add a dark mode", "feature_request"),
    ("How do I change my email address?", "how_to"),
    ("Charged twice and now the invoice page crashes", "billing"),
]

def build_messages(ticket: str) -> list[dict[str, str]]:
    msgs = []
    for text, label in EXAMPLES:
        msgs += [{"role": "user", "content": text}, {"role": "assistant", "content": label}]
    return msgs + [{"role": "user", "content": ticket}]

Reasoning first, then a parseable answer

A billing assistant must compute a prorated charge, and direct answers are often off. Step 1: ask the model to reason inside thinking tags and put only the final number inside answer tags. Step 2: in code, extract just the answer with a regular expression. Step 3: if the tag is missing, treat it as a failure rather than guessing from the reasoning. Here: 3 seats at 12 dollars is 36, plus 2 seats for half a month is 12, so 48.

python
import re

PROMPT = """A customer pays $12 per seat per month. They had 3 seats all month
and added 2 more seats for the second half of the month.
Work it out step by step inside <thinking> tags, then give only the
final amount in dollars inside <answer> tags."""

reply = ("<thinking>3 x 12 = 36. 2 seats x 12 x 0.5 = 12. 36 + 12 = 48.</thinking>"
         "<answer>48</answer>")  # what a model might return

match = re.search(r"<answer>\s*([\d.]+)\s*</answer>", reply)
amount = float(match.group(1)) if match else None
print(amount)  # 48.0

Quick reference

  • Start with 2 to 5 examples covering every label and the hardest cases
  • Keep example formatting identical and matching your instructions
  • Balance labels in examples; the model leans toward what it sees most
  • Never use eval items as few-shot examples
  • Ask for reasoning only on multi-step tasks; read the answer from its own tag or field
  • Reasoning-mode models need goals and constraints, not think step by step
  • Compare zero-shot vs few-shot on accuracy, tokens and latency

Common mistakes

  • Using examples that all share one label, biasing the output.
  • Adding examples without checking whether accuracy actually improved.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your 4 examples include 3 positive reviews and 1 negative. What is a likely side effect?

Question 2

2Which task benefits most from step-by-step reasoning?

Question 3

3Why must eval items never be used as few-shot examples?

Question 4

4What is dynamic few-shot prompting?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a few-shot prompt that turns product names into URL slugs (lowercase, hyphens, no symbols). Include one tricky example with symbols and extra spaces.

  2. Exercise 2medium

    Take a classification task with at least 40 labelled items. Measure accuracy zero-shot and with 4 examples, and record the extra input tokens per call.

  3. Exercise 3hard

    Implement dynamic few-shot: keep a pool of 100 labelled examples with embeddings, and for each new input insert the 3 most similar examples into the prompt. Compare accuracy against 3 fixed examples.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How many examples should a few-shot prompt have?
Start with 2 to 5 and measure. More examples help less after a point, while every one adds tokens to every call.
Does chain of thought always improve answers?
No. It helps on multi-step problems, but on simple tasks it mainly adds cost and latency, and models with built-in reasoning often do not need it spelled out.
Is few-shot prompting the same as fine-tuning?
No. Few-shot examples live in the prompt and affect only that request. Fine-tuning changes the model's weights using many examples, which costs more upfront but can shorten prompts later.

Go deeper

ShareXLinkedInWhatsApp