Sub topic 11
Selecting Examples Dynamically for Each Query
This chapter assumes you can read short Python, know the system, user, and assistant roles in chat prompts, and have built a fixed few-shot prompt before. A fixed prompt shows the same examples for every input. Dynamic selection instead picks the examples that fit each query from a larger pool.
Why a fixed set falls short
Three examples cannot cover every kind of input. A review about shipping speed gets little help from examples about battery life. If you keep a pool of 50 or 500 labeled examples, you can choose the most relevant few for each query. The prompt stays short, and the examples sit close to the task at hand.
Scoring similarity
The selector needs a score for how close each pool example is to the query. The function below uses word overlap (Jaccard similarity), which is simple and runs without any services. In production you would usually compare embeddings, which are number vectors that capture meaning. The rest of the pipeline stays the same.
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 entry is a pair of (text, label). Only the text is compared to the query. The function returns the k best pairs.
Connecting selection to the prompt
Pass the selected pairs to the chat builder from the earlier chapter. Nothing else changes.
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 messages
pool = [
("The battery lasts all day and charging is fast.", "positive"),
("It stopped working after a week.", "negative"),
("The package arrived on Tuesday.", "neutral"),
("Shipping was slow but the box was intact.", "neutral"),
("The screen cracked on the first day.", "negative"),
]
query = "The screen is bright but the speakers are weak."
chosen = select_examples(pool, query, k=3)
messages = build_messages(chosen, query)For this query, "The screen cracked on the first day." ranks high because it shares the words "the" and "screen". That shows a weakness of word overlap: common words like "the" count as much as meaningful ones. Embeddings handle this better.
Common errors
- Near-duplicate selection. The top
kby similarity can be almost identical sentences. That hurts diversity. Skip candidates that are too close to ones you already picked, or choose a few by similarity and a few at random. - Label imbalance. If the nearest neighbors all share one label, the model may lean toward that label. Check the label mix of the chosen set.
- Leakage during testing. If the query itself is in the pool, the selector returns it with its label, and your accuracy looks perfect. Remove the query from the pool when you evaluate.
- Unstable ordering. Ties in the score can reorder examples between runs. Sort by score, then by a stable key, so results are repeatable.
- Extra cost. With embeddings, you must embed the query on every call. Embed the pool once and store the vectors.
Checking that it helps
Dynamic selection adds code, so confirm it beats a fixed prompt. Use held-out labeled data that is not in the pool, and score both prompt variants.
def accuracy(predict, labeled):
correct = 0
for text, label in labeled:
if predict(text).strip().lower() == label:
correct += 1
return correct / len(labeled)Write one predict function that uses fixed examples and one that calls select_examples. Compare the two accuracy numbers. If the gain is small, the fixed prompt is cheaper and easier to maintain.
Exercise
You evaluate a dynamic selector by running every pool example as a query and get 100% accuracy. What is wrong, and how do you fix it?
Show answer
Each query finds itself in the pool as its own nearest neighbor and copies its own label. This is leakage. Evaluate on held-out data that is not in the pool, or remove the query from the pool before selecting.
Exercise
Name two ways to stop the top k examples from being near-duplicates.
Show answer
Skip candidates that are too similar to ones already chosen, or pick some examples by similarity and the rest at random from the pool.