Sub topic 13
Pitfalls: Copying, Bias, Leakage, and Token Cost
This chapter assumes you can read short Python and know how a few-shot prompt is built, including as chat messages. It also assumes you have scored a prompt on held-out labeled data. The chapter covers four ways a working few-shot prompt can quietly go wrong, and how to detect and reduce each one.
The four pitfalls at a glance
Few-shot examples are strong evidence for the model. Anything accidental in them, such as a repeated label, a quirky phrase, or a test item, can shape the output as much as the task does.
| Pitfall | What you see | Main cause | First fix |
|---|---|---|---|
| Example copying | Output reuses wording or content from an example | Examples are too similar to the query or too distinctive | Vary examples, add a clarifying instruction |
| Label bias | One label is over-predicted | Skewed labels, recency, or a common label token | Balance labels, reorder, recheck on held-out data |
| Leakage | Scores look great, production results are worse | Test items appear in the prompt, or examples overlap the test set | Split data first, run a duplicate check |
| Token cost | Latency and bills grow | Every call resends all examples | Trim, select dynamically, cache the shared prefix |
Example copying
Models continue patterns. If your examples contain a distinctive phrase, an entity name, or a fixed length, the model may reproduce it where it does not belong. Typical cases:
- An extraction task where every example output mentions "Acme Corp". The model starts inventing "Acme Corp" for unrelated inputs.
- A rewriting task where all example outputs are exactly two sentences. The model forces every answer into two sentences.
- A query that is nearly identical to one example. The model returns that example's output, even when a small difference should change the answer.
The third case is the hardest to spot, because the answer looks plausible. Copying is most likely when the query is very close to an example and the instruction is vague about what may differ.
You can check for it automatically. The function below flags any output that contains a run of consecutive words taken from an example input. Use it on tasks where outputs should be new text, such as summaries or rewrites. It is not suited to classification, where the output is a short label.
def ngrams(text, n):
words = text.lower().split()
return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)}
def copies_example(output, examples, n=5):
out_grams = ngrams(output, n)
for text, _ in examples:
if out_grams & ngrams(text, n):
return True
return False
examples = [
("The Acme Corp quarterly report shows record growth in Europe.", "Growth rose."),
]
print(copies_example("Acme Corp quarterly report shows record growth.", examples)) # True
print(copies_example("Sales climbed last quarter.", examples)) # FalseTo reduce copying:
- Make example inputs differ from each other in length, topic, and phrasing. Keep the same format.
- Replace distinctive names and numbers with varied or neutral ones.
- State the rule in the instruction ("Use the examples only to learn the format. Do not reuse their content.").
- When selecting examples dynamically, exclude any pool item that is almost identical to the query, or deliberately accept it if you want lookup behavior.
Label bias
Label bias means the model's predictions lean toward some labels regardless of the input. Three sources are common:
- Majority label bias. If 5 of 6 examples are "positive", the model learns that "positive" is likely.
- Recency bias. The label of the last example gets extra weight, because it is closest to the query.
- Common token bias. Labels that are frequent words in training text, such as "yes" or "positive", are favored over rarer ones, such as "neutral" or "mixed".
Run a quick audit before you test anything. This helper reports label shares and the length of the run of identical labels at the end of the example list:
from collections import Counter
def label_shares(examples):
counts = Counter(label for _, label in examples)
total = sum(counts.values())
return {label: round(n / total, 2) for label, n in counts.items()}
def trailing_run(examples):
run = 0
last = examples[-1][1]
for _, label in reversed(examples):
if label != last:
break
run += 1
return run
examples = [
("Great phone.", "positive"),
("Broke fast.", "negative"),
("Arrived Tuesday.", "neutral"),
("Love it.", "positive"),
("Superb screen.", "positive"),
]
print(label_shares(examples)) # {'positive': 0.6, 'negative': 0.2, 'neutral': 0.2}
print(trailing_run(examples)) # 2The output shows two problems. "positive" has 60 percent of the examples, and the prompt ends with two "positive" examples in a row.
Fixes, in order of effort:
- Balance labels, or match them to the real distribution if you want the model to learn the base rate. Choose this on purpose.
- Shuffle the order and avoid ending on a run of one label.
- Compare several orderings on held-out data. If accuracy moves by several points when you only reorder examples, the prompt is order-sensitive and you should not trust a single run.
- Check the confusion matrix, not only overall accuracy. A model that over-predicts one label can still score well if that label is common in your test data.
Leakage
Leakage means information from your evaluation data reaches the prompt. Your measured accuracy then overstates real performance. Few-shot prompts leak in three ways:
- Direct leakage. A test item is also used as an in-prompt example. The model can copy its label.
- Near-duplicate leakage. The data contains paraphrases or repeated items, so a prompt example is almost the same as a test item.
- Tuning leakage. You edit the prompt many times, watching the same test set. The prompt gradually fits that set, even though no single item is in it.
Split your data before you choose any examples, and never reuse a test item as an example. Then check for near duplicates with a similarity threshold. The word-overlap measure from earlier chapters works as a first pass.
def overlap(a, b):
wa, wb = set(a.lower().split()), set(b.lower().split())
union = wa | wb
return len(wa & wb) / len(union) if union else 0.0
def find_leaks(prompt_examples, test_items, threshold=0.7):
leaks = []
for ex_text, _ in prompt_examples:
for test_text, _ in test_items:
score = overlap(ex_text, test_text)
if score >= threshold:
leaks.append((ex_text, test_text, round(score, 2)))
return leaks
prompt_examples = [("It stopped working after a week.", "negative")]
test_items = [
("It stopped working after a week", "negative"),
("The screen is bright but the speakers are weak.", "neutral"),
]
for leak in find_leaks(prompt_examples, test_items):
print(leak)The first test item differs from the example only in a final period, so it prints with a score of 1.0. Word overlap misses paraphrases such as "quit working within seven days". For stricter checks, compare embeddings, or review the closest pairs by hand.
The third kind of leakage is handled by keeping three sets. Use a development set for iterating on the prompt, and a separate test set that you score only once at the end. Keep the example pool apart from both.
Token cost
Few-shot examples are sent with every request, and you pay for input tokens each time. A prompt with 8 examples of 60 tokens each adds about 480 tokens per call. At 100,000 calls per day, that is 48 million extra input tokens per day. Longer prompts also increase latency, and they use up context that the query or retrieved documents may need.
You can estimate the cost before you ship. The function below uses the rough rule of 4 characters per token for English. Use your provider's tokenizer for exact counts.
def estimate_tokens(text):
return max(1, len(text) // 4)
def prompt_cost(system, examples, query, calls, price_per_million):
parts = [system, query] + [t + l for t, l in examples]
tokens_per_call = sum(estimate_tokens(p) for p in parts)
total_tokens = tokens_per_call * calls
return tokens_per_call, total_tokens / 1_000_000 * price_per_million
examples = [("The battery lasts all day.", "positive")] * 8
per_call, dollars = prompt_cost(
"Classify the sentiment as positive, negative, or neutral.",
examples,
"The screen is bright but the speakers are weak.",
calls=100_000,
price_per_million=1.0,
)
print(per_call, round(dollars, 2))The price here is a placeholder. Substitute your model's real input rate.
Ways to cut cost without losing accuracy:
- Measure the marginal value of each example. Remove one example at a time and rescore. If accuracy does not change, drop it.
- Shorten examples. Trim long inputs to the part that carries the signal.
- Select dynamically. Send 3 relevant examples chosen per query instead of 10 fixed ones.
- Cache the shared prefix. If your provider supports prompt caching, keep the instruction and fixed examples at the start and put the query at the end. Anything that changes per request should come after the cached part.
- Consider alternatives. If you need dozens of examples on a high-volume task, fine-tuning may cost less in total.
Diagnosing which pitfall you have
Symptoms overlap, so check them in an order that rules out the cheap explanations first.
Always start with leakage. If your measurements are inflated, every other conclusion is unreliable.
A short pre-release checklist
- Data is split into pool, development, and test sets before any example is chosen.
- No example appears in the test set, and a near-duplicate check passes.
- Label shares are intentional, and the last examples do not form a long run of one label.
- Accuracy is stable across at least three example orderings.
- Outputs are spot-checked for reused names, phrases, and lengths.
- Tokens per call are measured, and each example earns its place.
Exercises
Exercise
A teammate reports 97 percent accuracy for a sentiment prompt. You find that 6 of the 40 test reviews are also used as examples in the prompt. What should you do, and why?
Show answer
Remove those 6 items from the test set, or replace the in-prompt examples with items from the pool, then rescore on the cleaned test set. The model can copy the labels of items it has seen in the prompt, so the 97 percent is inflated. Also run a near-duplicate check to catch paraphrases of the same items.
Exercise
Your prompt has 4 examples labeled positive, negative, neutral, positive, and the model predicts "positive" for 70 percent of held-out items, where only 35 percent are truly positive. Name two likely causes and one test for each.
Show answer
One cause is label and recency bias: positive is the most common example label and also the last one. Test by reordering so the last example is neutral or negative and rescoring, and check whether the share of positive predictions changes. A second cause is common token bias, where "positive" is favored because it is a frequent word. Test by renaming the labels, for example to "pos", "neg", "neu", or by balancing the examples, and compare the confusion matrices.
Exercise
A prompt has 10 fixed examples of 80 tokens each and serves 50,000 calls per day. Dynamic selection of 3 examples gives equal accuracy on held-out data. How many input tokens per day does this save from the examples alone?
Show answer
The fixed prompt sends 10 x 80 = 800 example tokens per call, and the dynamic prompt sends 3 x 80 = 240. The saving is 560 tokens per call, so 560 x 50,000 = 28,000,000 tokens per day.