Skip to main content

AI and machine learning · Intermediate · 22 min

Improve LLM answers with few-shot examples and measure the difference

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Ollama 0.40.18 · qwen3:0.6b · Python 3.15 · ollama (Python) 0.6.3

You will score a small local model on 40 labelled customer messages with zero, three and eight examples in the prompt, and end with a table that shows what the examples changed.

On this page

A few-shot prompt shows the model some solved examples before it sees the real input. It is the cheapest change you can make to an LLM feature: no training, no new model, a few lines of text. It is also easy to get wrong. Examples that all look alike teach the model one pattern, examples formatted differently from each other confuse it, and a model can latch on to an example's wording instead of its meaning.

The only way to know whether examples help your feature is to measure. In this tutorial you build a small intent classifier for an online shop's support inbox. It sorts each message into one of five intents: billing, delivery, returns, account or product. You score it on 40 labelled messages three times: with no examples, with three and with eight. Five of the 40 messages are traps that share words with an example but belong to a different intent, so you can see when the model copies wording.

The model is qwen3:0.6b, a 0.6-billion-parameter model that runs on a laptop CPU through Ollama. Every run uses temperature 0 and a fixed seed, so on the same machine and Ollama version the same prompt gives the same answer, and the difference between runs comes from the examples, not from chance. A small model makes mistakes you can see. A larger model will score higher and your numbers will differ, but the method is the same.

Some test messages are in Nigerian Pidgin and Swahili, because real inboxes in Lagos or Nairobi mix languages. A local model also means each run costs nothing in API fees or mobile data once the model is downloaded, which matters if you pay for data by the gigabyte.

Step 1 · Pull the model and create the project

Check that Ollama is running, then download the model. It is about 523 MB, so on a metered connection start it while you are on Wi-Fi:

Bash
ollama --version
ollama pull qwen3:0.6b

Create a project folder with Python 3.15 and the official Ollama client library. The exact pin keeps a new release from changing the client under you:

Bash
mkdir -p ~/fewshot-demo/data
cd ~/fewshot-demo
uv init --no-package --python 3.15
uv add "ollama==0.6.3"

Check it worked

Bash
ollama list
uv run python -c "import ollama, sys; print(sys.version.split()[0]); print(ollama.list().models[0].model)"

ollama --version printed something like ollama version is 0.40.18. ollama list shows qwen3:0.6b with a size of about 523 MB. The Python line prints a 3.15 version number and then a model name, which proves the library can reach the Ollama server on 127.0.0.1:11434.

Step 2 · Write the labelled test set

The test set is the ruler you measure with, so write it before you touch the prompt. Each line is one JSON object with the message, the correct intent, and trap: true for the five messages built to share wording with an example:

Bash
cat > data/messages.jsonl <<'JSONL'
{"message": "My card was declined at checkout but the bank says the money left my account.", "intent": "billing"}
{"message": "Why does my invoice show a delivery fee when the promo said free shipping?", "intent": "billing"}
{"message": "Can I pay with M-Pesa or only by card?", "intent": "billing"}
{"message": "The 10% promo code says it has expired but the email said it runs until Friday.", "intent": "billing"}
{"message": "I need a VAT invoice with my company name for order 5120.", "intent": "billing"}
{"message": "You took 18,500 naira twice. Please reverse the second charge.", "intent": "billing"}
{"message": "Payment failed three times on my phone. Is something wrong with your checkout?", "intent": "billing"}
{"message": "Wahala o, una debit me but the app still dey show payment pending.", "intent": "billing"}
{"message": "When will order 3302 reach Ibadan?", "intent": "delivery"}
{"message": "The courier called but I was at work. Can he come back tomorrow?", "intent": "delivery"}
{"message": "I typed the wrong street on my order. Can you change the delivery address?", "intent": "delivery"}
{"message": "Do you deliver to Kisumu, and how many days does it take?", "intent": "delivery"}
{"message": "Tracking says delivered, but nothing came to my house.", "intent": "delivery"}
{"message": "My parcel has been stuck at the Accra hub for five days.", "intent": "delivery"}
{"message": "Order 4471 is paid but it still has not shipped after a week.", "intent": "delivery", "trap": true}
{"message": "Can I collect my order from your Yaba store instead of waiting for the courier?", "intent": "delivery"}
{"message": "The blender I received is the wrong colour. How do I swap it?", "intent": "returns"}
{"message": "How many days do I have to return a dress I have not worn?", "intent": "returns"}
{"message": "The screen on the tablet was cracked when I opened the box.", "intent": "returns"}
{"message": "I sent the jacket back two weeks ago. When will the refund for the return come through?", "intent": "returns"}
{"message": "You sent me two left shoes.", "intent": "returns"}
{"message": "Do I have to pay the courier when I return something?", "intent": "returns"}
{"message": "I want to exchange the headphones for the black ones.", "intent": "returns"}
{"message": "The kettle stopped working after three days and I want to send it back.", "intent": "returns"}
{"message": "How do I change the email address on my account?", "intent": "account"}
{"message": "I want to delete my account and all my data.", "intent": "account"}
{"message": "Someone signed in to my account from another country.", "intent": "account"}
{"message": "The app logs me out every time I close it.", "intent": "account"}
{"message": "I made two accounts by mistake. Can you merge them?", "intent": "account"}
{"message": "I left my old phone with the security guard at my estate gate. How do I sign out of my account on it?", "intent": "account", "trap": true}
{"message": "The tracking page asks me to sign in and my password no longer works.", "intent": "account", "trap": true}
{"message": "Siwezi kuingia kwenye akaunti yangu.", "intent": "account"}
{"message": "Is the 32-inch TV a smart TV or do I need a separate box?", "intent": "product"}
{"message": "Does this phone case fit a 6.7-inch phone?", "intent": "product"}
{"message": "What is the warranty on the solar lantern?", "intent": "product"}
{"message": "Is there a bigger size of these shoes in stock?", "intent": "product", "trap": true}
{"message": "What is the reset button on the power bank for?", "intent": "product", "trap": true}
{"message": "Will the rice cooker work on 220 volts?", "intent": "product"}
{"message": "Is the school bag waterproof or only water resistant?", "intent": "product"}
{"message": "When will the blue version of the kettle be back in stock?", "intent": "product"}
JSONL

The Swahili line means "I can't sign in to my account". The Pidgin line says the customer was debited but the app still shows the payment as pending.

Some messages sit near a boundary, such as a refund. The rule this shop uses is: a refund for a wrong or double charge is billing, a refund for an item sent back is returns. Boundaries like this belong in the instructions, which you write in the next step.

Check it worked

Bash
uv run python - <<'PY'
import json
from collections import Counter
rows = [json.loads(line) for line in open("data/messages.jsonl", encoding="utf-8")]
print(len(rows), "messages")
print(dict(Counter(r["intent"] for r in rows)))
print(sum(r.get("trap", False) for r in rows), "traps")
assert len(rows) == 40 and set(Counter(r["intent"] for r in rows).values()) == {8}
PY

The output is 40 messages, eight for each of the five intents, and 5 traps. Because the set is balanced, a model that answers billing to everything scores only 20%, so a high score has to be earned.

Step 3 · Write a pool of examples

Examples live in their own file and must never appear in the test set. If they did, the model would be marked on questions it had already been shown the answers to. Write ten, two per intent, and vary them on purpose: short and long, a question and a complaint, English and Pidgin, a specific order number and none:

Bash
cat > data/examples.jsonl <<'JSONL'
{"message": "I was charged twice for order 4471. Please refund one of the payments.", "intent": "billing"}
{"message": "Abeg, money don comot from my account but my order still dey show unpaid.", "intent": "billing"}
{"message": "The tracking page for my parcel has said in transit since Monday.", "intent": "delivery"}
{"message": "These shoes are too small. How do I send them back for a bigger size?", "intent": "returns"}
{"message": "Can the courier leave the box with the security guard at my estate gate?", "intent": "delivery"}
{"message": "The reset code for my password never arrives on my phone.", "intent": "account"}
{"message": "The mixer arrived with a broken lid and I want my money back.", "intent": "returns"}
{"message": "Does the 20,000 mAh power bank charge a laptop over USB-C?", "intent": "product"}
{"message": "How do I turn off marketing emails in my account settings?", "intent": "account"}
{"message": "Is the steam iron's water tank removable?", "intent": "product"}
JSONL

Look at the first three lines: two are billing. If your code took the first three examples from the file, the model would see two billing examples, one delivery example, and nothing about returns, accounts or products. The next step picks examples so that each intent gets a turn before any intent gets a second one.

Check it worked

Bash
uv run python - <<'PY'
import json
tests = {json.loads(l)["message"] for l in open("data/messages.jsonl", encoding="utf-8")}
pool = [json.loads(l) for l in open("data/examples.jsonl", encoding="utf-8")]
print(len(pool), "examples;", len({e["message"] for e in pool} & tests), "also in the test set")
print("first three labels in the file:", [e["intent"] for e in pool[:3]])
PY

The output is 10 examples; 0 also in the test set and then ['billing', 'billing', 'delivery'].

Step 4 · Build the classifier and the scorer

Create classify.py. It does five things:

  • select_examples takes examples in turn from each intent, so three examples cover three intents and eight cover all five, mixed rather than grouped.
  • format_example writes every example in exactly the same shape inside <example> tags, and build_system wraps them in one <examples> block after the instructions. The tags let the model tell your instructions, your examples and the customer's message apart.
  • classify sends one message to the model with temperature 0, seed 42, a cap of 16 output tokens and think=False, which asks Qwen3 to answer without a reasoning section first.
  • parse accepts only one of the five intent names. Anything else counts as invalid, because the code that would route a ticket cannot use it.
  • main scores all 40 messages and saves the results.
Bash
cat > classify.py <<'PY'
import argparse
import json
import re
from collections import Counter
from pathlib import Path

import ollama

MODEL = "qwen3:0.6b"
LABELS = ["billing", "delivery", "returns", "account", "product"]
OPTIONS = {"temperature": 0, "seed": 42, "num_predict": 16}

INSTRUCTIONS = """You sort customer messages for an online shop into exactly one intent.

Intents:
- billing: payments, charges, invoices, promo codes, and refunds of a wrong or double charge
- delivery: where an order is, delivery dates, couriers, delivery addresses, collection
- returns: sending an item back, exchanges, damaged, faulty or wrong items, refunds for returned items
- account: signing in, passwords, profile details, account security, deleting an account
- product: what a product does, sizes, stock, specifications and warranty

Messages may be in English, Nigerian Pidgin, Swahili or a mix.
Reply with the intent name only, in lower case, with no other words."""


def load(path):
    lines = Path(path).read_text(encoding="utf-8").splitlines()
    return [json.loads(line) for line in lines if line.strip()]


def select_examples(pool, n):
    queues = {label: [e for e in pool if e["intent"] == label] for label in LABELS}
    chosen = []
    while len(chosen) < n:
        took = False
        for label in LABELS:
            if queues[label] and len(chosen) < n:
                chosen.append(queues[label].pop(0))
                took = True
        if not took:
            raise SystemExit(f"the pool only has {len(chosen)} examples")
    return chosen


def format_example(example):
    return (
        "<example>\n"
        f"<message>{example['message']}</message>\n"
        f"<intent>{example['intent']}</intent>\n"
        "</example>"
    )


def build_system(examples):
    if not examples:
        return INSTRUCTIONS
    blocks = "\n".join(format_example(e) for e in examples)
    return (
        f"{INSTRUCTIONS}\n\n"
        "These labelled examples show the task. Learn the intents from them, not the wording.\n"
        f"<examples>\n{blocks}\n</examples>"
    )


def parse(raw):
    text = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL)
    text = re.sub(r"<[^>]+>", "", text)
    text = text.strip().strip(".:'\" ").lower()
    return text if text in LABELS else "invalid"


def classify(system, message):
    response = ollama.chat(
        model=MODEL,
        messages=[
            {"role": "system", "content": system},
            {"role": "user", "content": f"<message>\n{message}\n</message>"},
        ],
        think=False,
        options=OPTIONS,
    )
    return response.message.content or ""


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--shots", type=int, default=0)
    parser.add_argument("--show-prompt", action="store_true")
    args = parser.parse_args()

    tests = load("data/messages.jsonl")
    pool = load("data/examples.jsonl")
    leaked = {e["message"] for e in pool} & {t["message"] for t in tests}
    if leaked:
        raise SystemExit(f"these examples are also in the test set: {sorted(leaked)}")

    examples = select_examples(pool, args.shots)
    system = build_system(examples)
    if args.show_prompt:
        print(system)
        return

    rows = []
    for test in tests:
        raw = classify(system, test["message"])
        rows.append({**test, "raw": raw, "predicted": parse(raw)})

    traps = [r for r in rows if r.get("trap")]
    summary = {
        "shots": args.shots,
        "correct": sum(r["predicted"] == r["intent"] for r in rows),
        "total": len(rows),
        "invalid": sum(r["predicted"] == "invalid" for r in rows),
        "bare": sum(r["raw"].strip() in LABELS for r in rows),
        "traps_correct": sum(r["predicted"] == r["intent"] for r in traps),
        "traps": len(traps),
        "predicted": dict(Counter(r["predicted"] for r in rows)),
    }
    Path("results").mkdir(exist_ok=True)
    out = Path(f"results/shots-{args.shots}.json")
    out.write_text(
        json.dumps(
            {"summary": summary, "examples": examples, "rows": rows},
            indent=2,
            ensure_ascii=False,
        ),
        encoding="utf-8",
    )

    s = summary
    print(f"shots={s['shots']}  accuracy {s['correct']}/{s['total']} "
          f"({s['correct'] / s['total']:.0%})  invalid {s['invalid']}  "
          f"bare replies {s['bare']}/{s['total']}  traps {s['traps_correct']}/{s['traps']}")
    print("predicted:", s["predicted"])
    for r in rows:
        if r["predicted"] != r["intent"]:
            print(f"  wrong: expected {r['intent']:<8} got {r['predicted']:<8} "
                  f"raw={r['raw'].strip()[:30]!r}  {r['message'][:50]}")
    print(f"saved {out}")


if __name__ == "__main__":
    main()
PY

Before you spend model time, check the two pieces of logic that do not need the model:

Bash
uv run python - <<'PY'
from classify import load, parse, select_examples
pool = load("data/examples.jsonl")
print("3 examples:", [e["intent"] for e in select_examples(pool, 3)])
print("8 examples:", [e["intent"] for e in select_examples(pool, 8)])
for raw in ["billing", " Delivery.", "<intent>returns</intent>", "It is about billing", "refund"]:
    print(repr(raw), "->", parse(raw))
assert [e["intent"] for e in select_examples(pool, 3)] == ["billing", "delivery", "returns"]
assert parse("It is about billing") == "invalid"
PY

Check it worked

Three examples are billing, delivery and returns, one each. Eight examples cover all five intents in an interleaved order, ending with a second billing, delivery and returns. The parser turns " Delivery." into delivery and strips a stray <intent> tag, but returns invalid for a sentence or for refund, which is not one of the intents.

Step 5 · Score the model with no examples

Run the baseline. With 40 messages on a laptop CPU this takes somewhere between a few seconds and a couple of minutes:

Bash
uv run python classify.py --shots 0

Check it worked

Bash
uv run python - <<'PY'
import json
s = json.load(open("results/shots-0.json", encoding="utf-8"))["summary"]
print(s)
assert s["total"] == 40 and s["traps"] == 5
PY

The first line of the output reads like shots=0 accuracy 30/40 (75%) invalid 1 bare replies 39/40 traps 4/5, with your own numbers. Below it are the predicted counts and one line for each wrong answer. Write the accuracy down; it is the number to beat.

Read the wrong answers before you add examples. Each one is either a format failure (invalid, the model replied with something other than an intent name) or a meaning failure (a real intent, the wrong one). Examples mostly fix the first kind. For the second kind, a clearer definition in INSTRUCTIONS may help more than any example.

Step 6 · Read the prompt the model sees

Print the system prompt with three examples, without calling the model:

Bash
uv run python classify.py --shots 3 --show-prompt

Then count the tags, to prove every example has the same shape:

Bash
uv run python classify.py --shots 8 --show-prompt > prompt-8.txt
grep -c '^<example>$' prompt-8.txt
grep -c '^<intent>' prompt-8.txt

Check it worked

The three-example prompt ends with an <examples> block holding three <example> blocks. Each has one <message> line and one <intent> line, in the same order, with no extra blank lines or labels. For eight examples both counts print 8.

Identical formatting matters more for a small model than a large one. If one example used Intent: billing and another used <intent>billing</intent>, the model would have two patterns to imitate and would sometimes invent a third.

Step 7 · Score with three and eight examples and compare

Run both few-shot versions:

Bash
uv run python classify.py --shots 3
uv run python classify.py --shots 8

Now put the three runs side by side. Create compare.py:

Bash
cat > compare.py <<'PY'
import json
from pathlib import Path

runs = sorted(
    (json.loads(p.read_text(encoding="utf-8")) for p in Path("results").glob("shots-*.json")),
    key=lambda run: run["summary"]["shots"],
)
labels = ["billing", "delivery", "returns", "account", "product"]
print(f"{'shots':>5} {'accuracy':>9} {'invalid':>8} {'traps':>6}  " + " ".join(f"{l[:7]:>7}" for l in labels))
for run in runs:
    s = run["summary"]
    recall = []
    for label in labels:
        rows = [r for r in run["rows"] if r["intent"] == label]
        recall.append(f"{sum(r['predicted'] == label for r in rows)}/{len(rows)}")
    print(f"{s['shots']:>5} {s['correct'] / s['total']:>9.0%} {s['invalid']:>8} "
          f"{s['traps_correct']:>3}/{s['traps']} " + " ".join(f"{x:>7}" for x in recall))
PY
uv run python compare.py

Check it worked

Bash
uv run python compare.py | tee comparison.txt
test "$(grep -cE '^ +(0|3|8) ' comparison.txt)" -eq 3

You see a table with one row for 0, 3 and 8 shots. The columns are overall accuracy, invalid replies, traps answered correctly, and for each intent how many of its eight messages the model got right.

Read it column by column rather than looking only at accuracy:

  • Invalid. If this drops with examples, the examples taught the reply format.
  • Per-intent counts at 3 shots. The three-example prompt shows no account or product example. If those two columns are weaker at 3 shots than at 8, the model is leaning on the intents it was shown.
  • Accuracy at 8 versus 3. More examples make every request longer and slower. If eight examples do not beat three on your set, keep three.

The figures come from one small model and 40 messages, so one message is 2.5 percentage points. A difference of one or two messages is noise; do not rewrite a prompt over it. Run a bigger golden set before you trust a small gain.

Step 8 · Check whether the model copies the examples

The traps test copying. Each one shares words with an example from a different intent: "Order 4471" and "paid" with a billing example, "bigger size of these shoes" with a returns example, "tracking page" with a delivery example, "security guard" and "estate gate" with a delivery example, and "reset" with an account example. A model that matches on wording gives the example's intent instead of the right one.

List the trap answers for every run:

Bash
uv run python - <<'PY'
import json
for shots in (0, 3, 8):
    rows = json.load(open(f"results/shots-{shots}.json", encoding="utf-8"))["rows"]
    print(f"shots={shots}")
    for r in rows:
        if r.get("trap"):
            mark = "ok   " if r["predicted"] == r["intent"] else "WRONG"
            print(f"  {mark} expected {r['intent']:<8} got {r['predicted']:<8} {r['message'][:55]}")
PY

Check it worked

You see five lines per run, marked ok or WRONG. Look for a trap that is right at 0 shots and wrong once examples are added, especially one answered with the intent of the example it resembles (billing for the "Order 4471" message, returns for the shoe-size question). That is the model copying wording.

When you find one, do not delete the trap from the test set. Fix the examples instead:

  • Add a contrasting pair: an example with the same surface words and a different intent, such as "Order 4471 has not arrived yet" labelled delivery next to the double-charge example.
  • Remove example details that are too specific, such as order numbers, so they cannot become a cue.
  • Keep the sentence telling the model to learn intents, not wording, but do not rely on it alone.

After any change to the examples, run all three scores again and compare the new table with the old one. A change that fixes a trap and breaks two other messages is not an improvement. Keep comparison.txt from each round, so you can show a reviewer what changed and why.

Next steps

You have a repeatable way to decide whether examples earn their place in a prompt. The same scorer works for any prompt change: a new instruction, a different model, a longer definition.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.