Dynamic Few-Shot Example Selection for Production LLM Apps in October 2026: Retrieve the Right Examples per Request Instead of Hardcoding Them

Few-shot prompting is one of the oldest tricks in working with language models: show the model a handful of solved examples, then ask it to solve a new one. Most teams start by pasting three or four examples straight into the system prompt and never touch them again. That works until the traffic gets varied. A support classifier that saw three billing examples does poorly on a shipping question. An extraction prompt tuned on clean invoices stumbles on a scanned receipt. The fix is not more hardcoded examples. It is choosing the examples per request, from a curated pool, based on what the current input actually looks like.

Flash cards for language learning
Image: bfishadow via Wikimedia Commons (CC BY 2.0)

This post walks through how to build dynamic few-shot selection for a production LLM app: what goes in the example pool, how to retrieve and filter candidates, how to keep the set diverse, where the examples go in the prompt so you do not wreck prompt caching, and how to tell whether any of it is helping.

When dynamic examples are worth it

Dynamic selection adds a retrieval step, an index to maintain, and a new way for prompts to vary between requests. It earns its keep in a few specific situations:

  • Inputs are diverse and the task is format-sensitive. Classification with many labels, structured extraction across different document types, or text-to-command translation where each sub-domain has its own conventions.
  • You have a growing set of corrected outputs. If reviewers already fix model mistakes, those fixes are exactly the examples the model needs next time a similar input shows up.
  • Fine-tuning is not an option yet. Dynamic examples let you steer behavior today, and the same curated pool becomes training data later if you move to distillation.

If your inputs are uniform, or a single well-written instruction already gets you where you need to be, static examples are simpler and cheaper. Measure before adding moving parts.

Step 1: Build a curated example pool

The pool is the most important part, and it is a data problem rather than a model problem. Each entry should contain:

  • The input, in the same shape your app sends at runtime.
  • The ideal output, in exactly the format you want back. If you require JSON, store valid JSON that passes your schema.
  • Metadata for filtering: label or category, document type, language, tenant if examples are customer-specific, source (hand-written, reviewer-corrected, production-approved), and a created date.
  • A stable ID, so you can log which examples were used for each request.

Good sources are reviewer corrections, outputs users explicitly approved, and hand-written examples for edge cases you know about. Avoid dumping raw production outputs into the pool without review. If the model was wrong and nobody noticed, you will teach it to be wrong more confidently.

Keep the pool small enough to audit. A few hundred well-chosen examples usually beat thousands of unreviewed ones, because every bad example in the pool will eventually get retrieved for someone.

Strip sensitive data before it goes in

Examples get injected into prompts for other users. An example pulled from one customer's ticket can show up in another customer's request. Run the same redaction you would run before any LLM call, and if examples are tenant-specific, store the tenant ID and filter on it strictly at retrieval time.

Catalog cards inside a library card catalog
Image: TBurmeister (WMF) via Wikimedia Commons (CC BY-SA 4.0)

Step 2: Retrieve candidates by similarity

The usual approach is to embed the input of every pool entry and index the vectors. At request time, embed the incoming input and pull the nearest neighbors. Embed only the input side of each example, not the output, because you are matching on "what does this request look like."

A simple retrieval flow looks like this:

  1. Apply hard filters first: tenant, language, task version, and anything else that must match exactly.
  2. Run a vector search for the top 20 to 50 candidates among what remains.
  3. Rerank or diversify down to the 3 to 8 examples you will actually include.

Pure embedding similarity is not always what you want. For text-to-SQL or code tasks, two inputs can read very differently but need the same output structure. In those cases, add a keyword or structural signal, such as which tables or entities are mentioned, alongside the vector score. Hybrid scoring tends to be more robust than either signal alone.

Step 3: Diversify so the examples are not all the same

Nearest-neighbor search has a failure mode: it returns five near-duplicates. If all five examples share the same label, the model is nudged toward that label regardless of the input. Two practical fixes:

  • Maximal marginal relevance (MMR). Pick examples one at a time, scoring each candidate by its similarity to the query minus its similarity to examples already chosen. A weight between the two terms controls how much diversity you want.
  • Label balancing. For classification, cap how many examples any single label can contribute, and make sure at least one example from a plausible competing label is included. This shows the model the boundary, not just one side of it.

Here is a compact MMR selection in Python, assuming normalized embedding vectors:

import numpy as np

def mmr_select(query_vec, cand_vecs, k=5, lam=0.7):
    sims_to_query = cand_vecs @ query_vec
    chosen = []
    remaining = list(range(len(cand_vecs)))
    while remaining and len(chosen) < k:
        if not chosen:
            best = max(remaining, key=lambda i: sims_to_query[i])
        else:
            chosen_vecs = cand_vecs[chosen]
            def score(i):
                redundancy = float(np.max(chosen_vecs @ cand_vecs[i]))
                return lam * sims_to_query[i] - (1 - lam) * redundancy
            best = max(remaining, key=score)
        chosen.append(best)
        remaining.remove(best)
    return chosen

Start with a lambda around 0.6 to 0.8 and tune it against your evaluation set rather than guessing.

Step 4: Place examples where they will not break caching

Many providers and self-hosted servers cache the shared prefix of prompts, which cuts cost and latency when consecutive requests start the same way. Dynamic examples are, by definition, different per request. If you put them at the top of the prompt, every request gets a unique prefix and caching stops working.

Order the prompt from most stable to least stable:

  1. System instructions, policy, and output schema (identical across requests).
  2. Any static examples you always want present, such as one canonical edge case.
  3. The dynamic examples for this request.
  4. The actual user input.

This keeps the long, stable part cacheable and confines the variation to the tail.

Format examples consistently

Use the same delimiters every time, and make the boundary between examples and the real input obvious. Many teams render examples as alternating user and assistant turns in the message list, which matches how chat models are trained. Others wrap them in tagged blocks inside a single message. Either works. What matters is that the format is identical across examples, and that the real input is clearly marked as the one to answer.

Order can matter

Models can be sensitive to the order in which examples appear, and the example nearest the end of the prompt often has an outsized influence. A reasonable default is to put the most similar example last, closest to the real input. Treat that as a starting point and test it, since the effect varies by model and task.

Step 5: Guard the token budget

Examples can be long. A single extraction example with a full document can use thousands of tokens. Set a token budget for the example section and enforce it after selection:

  • Count tokens with the target model's tokenizer, not a character estimate.
  • Drop the least relevant examples first until you fit.
  • For long inputs, store a trimmed version of the example input that keeps the parts that matter for the output.
  • If even one example does not fit, fall back to your static examples rather than failing the request.

Step 6: Log, evaluate, and maintain the pool

Dynamic selection makes prompts vary, which makes debugging harder unless you log carefully. For every request, record the IDs of the examples included and their similarity scores. When an output is wrong, you can check whether a misleading example was retrieved, which is often the actual cause.

Evaluate with a fixed test set that the pool does not contain. If test inputs are also in the pool, retrieval will find the exact answer and your scores will look far better than reality. Compare at least three configurations:

  • Zero-shot, instructions only.
  • Static examples, your current baseline.
  • Dynamic examples, with and without diversification.

Track task accuracy, output format validity, and token cost per request. Dynamic examples sometimes improve accuracy while raising cost; you need both numbers to decide.

For ongoing maintenance:

  • Version the pool. When you change examples, tie the change to an evaluation run, the same way you would treat a prompt change.
  • Re-embed the pool whenever you change embedding models, and keep the query and pool embeddings from the same model version.
  • Review the most frequently retrieved examples periodically. An example that gets pulled into a large share of requests has a large effect, so make sure it is correct.
  • Retire examples tied to outdated output formats or deprecated product behavior.

A practical starting configuration

If you want something to ship this week, this is a sensible baseline:

  • A reviewed pool of a few hundred examples with tenant and label metadata.
  • Hard filters on tenant and language, then top 30 by embedding similarity.
  • MMR down to 4 examples, with a cap of 2 per label for classification tasks.
  • Examples placed after the static system prompt and before the user input, most similar last.
  • A fixed token budget for examples, with fallback to static examples.
  • Example IDs logged per request, and a held-out evaluation set run on every pool change.

Bottom line

Hardcoded few-shot examples are a reasonable first draft, but they quietly assume every input looks like the three you picked. Selecting examples per request from a curated, reviewed pool lets the model see cases that resemble the one in front of it, including the corrections your reviewers already made. Keep the pool clean, diversify what you retrieve, put the variable part at the end of the prompt, and measure against a held-out set. Done that way, dynamic few-shot selection is one of the cheaper ways to improve output quality without changing models or fine-tuning.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)

Tencent Hy4 Preview: Open 770B MoE Built for Real Work