Sub topic 11
Selecting Examples Dynamically for Each Query
Earlier chapters used a fixed set of examples that appear in every prompt. This chapter replaces that set with one chosen per query from a larger pool. It assumes you can read short Python, know the system, user, and assistant roles in chat prompts, and have read the chapters on choosing representative examples and on evaluating a few-shot prompt.
Why a fixed set stops being enough
A fixed set of three to six examples works when the task is narrow. It struggles when inputs vary a lot. Suppose you classify support tickets across billing, shipping, account access, and product defects. Six fixed examples cannot cover every category, phrasing style, and edge case. Raising the count costs tokens on every call, and most of those examples are irrelevant to any single query.
Dynamic selection keeps a pool of labeled examples, perhaps dozens or thousands, and picks the few that fit the current input. The prompt stays short, and the examples shown are the ones most likely to help.
| Approach | Prompt size | Coverage of rare cases | Moving parts |
|---|---|---|---|
| Fixed examples | Constant | Low | None |
| Dynamic selection | Constant (k examples) | High, if the pool has them | Pool, similarity measure, selector |
How the pipeline works
For each incoming query, you score every pool example against it, keep the top k, order them, and format them into the prompt. The model sees a normal few-shot prompt. Only the construction step changes.
A simple similarity selector
Production systems usually compare embeddings, which are numeric vectors that capture meaning. The pipeline does not depend on that choice, so this chapter starts with word overlap, which needs no libraries. The score is the Jaccard overlap: shared words divided by all distinct words in both texts.
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 select_examples(pool, query, k=3):
ranked = sorted(pool, key=lambda ex: overlap(ex[0], query), reverse=True)
return ranked[:k]Each pool item is a (text, label) tuple. sorted is stable, so ties keep their pool order, and the result is deterministic.
Word overlap misses synonyms ("broken" and "stopped working" share no words). It also rewards shared filler words such as "the" and "is". Embeddings fix both problems. To switch, replace overlap with cosine similarity between the embedding vectors of the two texts. Nothing else in the pipeline changes.
Using the selection in chat messages
Selected examples go into the same chat structure you already built: one user turn and one assistant turn per example.
SYSTEM = "Classify the sentiment of each review as positive, negative, or neutral. Answer with one word."
def build_messages(examples, query):
messages = [{"role": "system", "content": SYSTEM}]
for text, label in examples:
messages.append({"role": "user", "content": text})
messages.append({"role": "assistant", "content": label})
messages.append({"role": "user", "content": query})
return messagesCombine the two pieces with build_messages(select_examples(pool, query, k=3), query).
Relevance is not enough
Top-k by similarity has three failure modes, and each one needs a guard.
- Label skew. If the query resembles four "negative" pool items, all k examples may be negative. The model then leans toward "negative" regardless of the input. This is the label bias covered in the chapter on order and balance.
- Near-duplicates. Ten copies of one complaint add tokens and no information. Similar examples are often almost identical.
- Order effects. Models often weight the examples closest to the query most heavily. A common convention is to place the most similar example last.
The next function takes the best example per label first, then fills the remaining slots by similarity, and finally orders the result so the most similar example comes last.
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 select_balanced(pool, query, k=3):
ranked = sorted(pool, key=lambda ex: overlap(ex[0], query), reverse=True)
chosen, seen_labels = [], set()
for ex in ranked:
if ex[1] not in seen_labels:
chosen.append(ex)
seen_labels.add(ex[1])
if len(chosen) == k:
break
for ex in ranked:
if len(chosen) == k:
break
if ex not in chosen:
chosen.append(ex)
chosen.sort(key=lambda ex: overlap(ex[0], query)) # most similar last
return chosen
pool = [
("The battery lasts all day and charging is fast.", "positive"),
("Great screen and the battery is excellent.", "positive"),
("It stopped working after a week.", "negative"),
("The speakers are weak and the battery drains fast.", "negative"),
("The package arrived on Tuesday.", "neutral"),
("The box contains a charger and a manual.", "neutral"),
]
query = "The screen is bright but the speakers are weak."
for text, label in select_balanced(pool, query, k=3):
print(label, "|", text)This guard forces one example per label only while k is at least the number of labels. With k=2 and three labels, some label is left out. Decide deliberately whether that is acceptable, or raise k.
Diversity among the selected examples
To avoid near-duplicates, penalize candidates that resemble examples you already picked. This is the idea behind maximal marginal relevance (MMR). Pick the most relevant example first. Then, for each following slot, choose the candidate with the best score of relevance - penalty * similarity to chosen set. A penalty around 0.3 to 0.5 is a reasonable starting point to tune. Too high a penalty pushes the selector toward irrelevant examples, which defeats the purpose of dynamic selection.
Keeping the pool healthy
The pool is data you maintain, so it can go bad.
- Label quality. One wrong label in the pool becomes a wrong demonstration every time that example is retrieved. Review labels, especially for examples that are retrieved often.
- Coverage. Log queries where the best similarity score is low. These are inputs your pool does not cover, and they tell you which examples to add.
- Edge cases and refusals. Dynamic selection can bring in your refusal or out-of-scope examples only when the query resembles them. Make sure such examples have enough similar wording to be retrieved, or keep one or two always-on examples for them.
- Staleness. If your task definition changes, such as a new category or a revised label policy, old examples contradict the new rules. Version the pool and remove outdated items.
Testing without leakage
Dynamic selection creates a new way to fool yourself. If a test item is also in the pool, the selector retrieves it as its own best match, and the model copies the label. Accuracy looks excellent and means nothing.
Split your labeled data first. Build the pool from the training portion only and evaluate on the held-out portion.
def accuracy(predict, labeled):
correct = 0
for text, label in labeled:
if predict(text).strip().lower() == label:
correct += 1
return correct / len(labeled)
def make_predict(call_model, pool, k, selector):
def predict(text):
examples = selector(pool, text, k)
return call_model(build_messages(examples, text))
return predictcall_model is any function that takes a message list and returns a string, so you can plug in your provider's client. To test the harness without a model, pass a stub such as lambda messages: "neutral".
Compare at least three variants on the same held-out set: a fixed set of k examples, top-k by similarity, and balanced or diverse top-k. If dynamic selection does not beat the fixed set by more than the noise in your test set, the extra machinery is not worth it. With a small held-out set, a difference of a few items is within noise.
Cost and latency
Dynamic selection changes cost in three ways.
- The prompt length is similar to a fixed prompt of the same k, but it varies with example length. Cap the length of each example or skip very long ones.
- With embeddings, you embed each query at request time and, for large pools, need a vector index. Embed the pool once and store the vectors.
- Providers that cache a repeated prompt prefix cannot cache examples that change per query. A fixed prompt can get cheaper through caching, while a dynamic one cannot. Put the unchanging system instructions first so at least that part can be cached.
When dynamic selection is the wrong choice
Skip it when the task is narrow and a fixed set already scores well, when your pool has fewer than about 20 labeled items (there is little to choose from), or when you need fully reproducible prompts for auditing. Dynamic prompts differ per input, so log which examples were used for every call. If you have thousands of labeled examples and the task is stable, fine-tuning may serve you better, as discussed in the final chapter.
Exercise
Your few-shot classifier scores 98% on a test set, but only 81% on fresh production tickets. It uses dynamic selection by similarity. Name the most likely cause and the fix.
Show answer
The test tickets were probably also in the example pool, so the selector retrieved each test item as its own nearest example and the model copied its label. This is leakage. Remove the test items from the pool, build the pool from the training split only, and re-run the evaluation on the held-out split.
Exercise
For the query "The screen is bright but the speakers are weak.", the top 3 pool items by similarity are all labeled negative. Which two changes in this chapter reduce the risk of a biased answer, and what does each do?
Show answer
Label balancing takes the best example for each label first, so the prompt shows positive, negative, and neutral cases. A diversity penalty such as MMR lowers the score of candidates that resemble examples already chosen, so near-duplicates do not fill the slots. Both should be validated against held-out accuracy.