FDE Times dataFDE jobs open 928▲21 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 85Companies hiring 200Remote-friendly 24%Median US pay $200kTop hirer Databricks 107
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Few-shot order alone can move a model from guessing to near-SOTA

Client ticket labels are always skewed, so example sets need per-class sampling, deduplication and stability checks across many orderings, all with Python's standard library.

ShareLinkedInFacebookX

In brief

  • Skewed examples push the model toward the majority label, so sample per class.
  • Example order can move accuracy from chance level to near-SOTA, so test many orderings.
  • Beyond accuracy, compare the predicted label distribution with the real one and measure recall on the rare class.
Infographic in two parts. The top compares two ways of choosing examples: drawing 10 examples at random from 1,000 skewed tickets gives about 7 "info queries" on average, so the model leans towards the majority label and misfiles "cancellation" tickets. Class sampling gives 3 examples per class, but should still be compared with a set at true ratios. Below is a five-step process: run zero-shot as the baseline, sample by class, drop near-duplicates, shuffle the order across many seeds, then check the prediction distribution and recall on the rare class.
Draw at random from skewed data and the model skews too. Sample by class, run several orderings and report the spread between seeds.

In 2021 the authors of “Calibrate Before Use” reported an uncomfortable finding: merely changing the order of the examples in a prompt could move a model’s accuracy from near chance to near state-of-the-art. Same examples, same labels; only the arrangement differed.

On a client site you rarely get to choose examples under clean conditions. The data is real tickets, emails and meeting notes, and the labels are almost always skewed: one class dominates, while a few others are rare but important. Paste in a handful of examples picked at random and the model learns that skew too.

The workflow below runs on a laptop: measure the data, sample per class, remove duplicates, shuffle the order and check whether the model is leaning toward one label.

What you will build, and what you need

Take a hypothetical client, a telecom company that hands over 1,000 labeled tickets: 700 “inquiry”, 200 “complaint” and 100 “cancel service”. The job is to classify new tickets with an LLM. By the end you will have a script that selects a few-shot example set, generates several orderings and measures how stable the results are.

You need Python 3 and a file tickets.csv with two columns, text and label. The code uses only the standard library. The model-calling function is deliberately left empty, because every client uses a different provider. All the code is simplified to teach the process; it is not production code.

Step 1: run zero-shot first, before jumping to few-shot

Zero-shot means a prompt with no examples. The DAIR.AI guide advises adding examples only when zero-shot falls short. The zero-shot number is your baseline: if few-shot cannot beat it, the example set is doing harm rather than helping.

Before running anything, measure the data:

import csv
from collections import Counter

rows = list(csv.DictReader(open("tickets.csv", encoding="utf-8")))
print(Counter(r["label"] for r in rows))
# Counter({'inquiry': 700, 'complaint': 200, 'cancel_service': 100})

Check: the class totals must equal the number of rows, and there must be no stray labels caused by typos, such as “cancel service” mixed in with “cancel_service”. Client data often has this problem. No prompt can fix an error in the labels.

Step 2: sample per class, because random sampling copies the skew

With a 70/20/10 split, picking 10 examples at random will on average give you about 7 “inquiry” examples. Learn Prompting describes the consequence: when the example distribution leans toward one class, the model leans toward predicting that class too.

For the client, that means “cancel service” tickets, the ones that most urgently need a retention effort, get filed among the harmless ones.

The first debiasing method Learn Prompting offers is to balance the number of examples across classes:

import random

def sample_per_class(rows, k_per_class, seed=0):
    rng = random.Random(seed)
    by_label = {}
    for r in rows:
        by_label.setdefault(r["label"], []).append(r)
    picked = []
    for label, items in by_label.items():
        picked += rng.sample(items, min(k_per_class, len(items)))
    return picked

balanced = sample_per_class(rows, k_per_class=3)

Do not treat balance as the final answer, though. DAIR.AI also notes that in experiments with random labels, drawing labels from the true distribution worked better than drawing them uniformly. So build a second set that follows the real proportions for comparison, and let the numbers on the client’s test set decide.

Check: print the Counter of balanced; each class should have exactly 3 examples.

Step 3: examples should resemble real data without resembling each other

According to DAIR.AI, both the label space and the distribution of the input text in the examples affect few-shot results. Examples should therefore come from real tickets, keeping the end customers’ typos and abbreviations, rather than tidy sentences you wrote yourself.

Learn Prompting warns, however, that examples that are too similar can lead the model to overgeneralize, and the context window limits how many examples you can fit. The simplified version below removes near-duplicate pairs with difflib. In a real project you would replace it with embedding similarity:

from difflib import SequenceMatcher

def dedupe(examples, threshold=0.8):
    kept = []
    for ex in examples:
        if all(SequenceMatcher(None, ex["text"], k["text"]).ratio() < threshold
               for k in kept):
            kept.append(ex)
    return kept

If a class runs short after deduplication, sample more for that class. Learn Prompting also mentions two automated approaches worth studying once the data grows.

KNN picks the examples most similar to the input query. Vote-K picks diverse, representative examples from unlabeled data, which helps when the client only has raw logs.

Step 4: shuffle and measure, rather than trusting a single run

Learn Prompting suggests that random ordering of examples usually works better. There is one hypothesis to test on the client’s own data: if all three “cancel service” examples are pushed to the end of the prompt, does the model predict that label more often than when the examples are evenly shuffled?

Rather than guessing, add that deliberate ordering as a configuration to compare.

The results from Zhao and colleagues show that order-driven variance is large enough that order has to be treated as a variable to measure.

def build_prompt(examples, query):
    head = ("Classify the ticket as one of: inquiry, complaint, cancel_service.\n"
            "Judge each ticket independently, without favoring any label.\n\n")
    shots = "".join(f"Ticket: {e['text']}\nLabel: {e['label']}\n\n" for e in examples)
    return head + shots + f"Ticket: {query}\nLabel:"

def call_model(prompt):
    raise NotImplementedError  # call the API of the provider the client uses

for seed in range(5):
    order = balanced[:]
    random.Random(seed).shuffle(order)
    # run build_prompt + call_model on the test set, record results per seed

The second line of the prompt has a purpose of its own. Learn Prompting notes that you can explicitly ask the model to be unbiased with an instruction in the prompt.

The Ticket: ... / Label: ... format must also be identical in every example. DAIR.AI observes that format significantly affects performance, and Learn Prompting regards locking in the output structure as the biggest benefit of few-shot.

Check: print one complete prompt and read it. A single extra space or a missing blank line in one example is enough to break the consistency of the format.

Step 5: look at the prediction distribution, not just accuracy

“Calibrate Before Use” explains that this instability comes from the model’s bias toward certain answers, and that calibrating for the context improves accuracy.

The technique is called contextual calibration, and it is the term to search for next. Unlike the steps above, which adjust the example set, it targets the model’s bias toward particular answers directly, so it is worth trying when the example set is already balanced and the model still leans toward one label.

You do not need a full calibration implementation to spot the symptoms. For each seed, print three things: accuracy, how many times the model predicted each label, and recall on the rare class:

from collections import Counter

def report(seed, y_true, y_pred, rare="cancel_service"):
    acc = sum(t == p for t, p in zip(y_true, y_pred)) / len(y_true)
    hit = sum(t == p == rare for t, p in zip(y_true, y_pred))
    total = sum(t == rare for t in y_true)
    print(f"seed {seed}: acc={acc:.2f} pred={Counter(y_pred)} "
          f"recall_{rare}={hit}/{total}")

# Illustrative output, not real measurements:
# seed 0: acc=0.81 pred=Counter({'inquiry': 78, 'complaint': 18, 'cancel_service': 4}) ...
# seed 1: acc=0.74 pred=Counter({'inquiry': 86, 'complaint': 12, 'cancel_service': 2}) ...
# seed 2: acc=0.84 pred=Counter({'inquiry': 72, 'complaint': 19, 'cancel_service': 9}) ...

Read that illustrative output against an assumed test set of 100 tickets split 70/20/10. At seed 1 the model predicts “cancel service” only twice. Even if both are correct, at least 8 of the 10 customers who want to leave are missed, while an accuracy of 0.74 still looks passable because the majority class props it up.

That recall figure is what the client cares about. And the gap between the best and worst seed is what you must report, rather than only the best number.

The most common mistakes

Mistake Symptom Fix
Picking examples at random from skewed data The model piles predictions onto the majority class Sample per class, and compare against a set with the real proportions
Writing “clean” examples yourself Works well in the demo, poorly on real tickets Take examples from client data and keep the original writing style
Many near-duplicate examples The model overgeneralizes and context is wasted Deduplicate and favor diverse examples
Running only one ordering Results cannot be reproduced between attempts Run several seeds and report the variance as well

Keep expectations in check, too. DAIR.AI acknowledges that standard few-shot is not a perfect technique, especially for tasks that require reasoning. If the client’s labels depend on multi-step reasoning, even the most careful balancing of examples solves only part of the problem.

On a client site, the deliverable is a table as well as a prompt

The table states which example set was used, how many orderings were run, the range accuracy moved within, and how often the rare class was missed. When the client asks why the model worked well yesterday and badly today, that table is the answer.

When reading FDE job descriptions, look for phrases such as “evaluation”, “prompt reliability” or “working with customer data”. On a CV, do not write “experienced in prompt engineering”. Write that you measured label skew, fixed it, and showed the results stayed stable when the example order changed.

Anyone can write a prompt that works in a demo. FDEs are paid to prove that the prompt still works on the thousandth ticket, including the one the majority class does not represent.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
6 sources
Read next on the roadmap · Stage 3: Applied AIHow structuring calls took GPT-4 from 4% to 74% on one puzzleFor client decisions that cannot go wrong, four layers of self-checking show which are worth paying for and which only inflate the API bill.