@HamzaM to AI & LLMEnglish • 4 days ago

How do you use few-shot dynamic example selection based on input similarity to boost classification accuracy?

message-square
0
1
How do you use few-shot dynamic example selection based on input similarity to boost classification accuracy?
@HamzaM to AI & LLMEnglish • 4 days ago

Overview

Dynamic few-shot example selection picks the most relevant labeled examples for each new input using embedding similarity instead of sending a fixed prompt list. This keeps prompts compact while giving the classifier close boundary cases for tricky inputs.

  • Better boundary coverage: Nearest-neighbor examples show how ambiguous or edge-case inputs map to labels.
  • Lower token cost and latency: Retrieving only the top k examples avoids stuffing every label or long examples into every call.

Steps

  1. Embed labeled training examples once: Compute vector embeddings for each labeled sample and store them with its text and class label.
  2. Retrieve top-k similar examples at inference time: Embed the incoming query, compute cosine similarity against stored examples, and select the closest matches (optionally balanced across classes).
  3. Format examples cleanly into the classification prompt: Inject the retrieved examples right before the target input and enforce strict label output (such as JSON schema or enum).
  4. Evaluate and tune k and similarity thresholds: Benchmark against a fixed few-shot baseline and drop overly distant examples if they introduce noise.

Example

export interface LabeledExample {
  id: string;
  text: string;
  label: string;
  embedding: number[];
}

export interface ClassificationPrompt {
  systemInstruction: string;
  userPrompt: string;
  selectedExamples: Array<{ id: string; text: string; label: string; score: number }>;
}

export function cosineSimilarity(a: number[], b: number[]): number {
  if (a.length !== b.length || a.length === 0) {
    throw new Error("Embeddings must be non-empty arrays of equal length.");
  }

  let dot = 0;
  let normA = 0;
  let normB = 0;

  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }

  const denom = Math.sqrt(normA) * Math.sqrt(normB);
  return denom === 0 ? 0 : dot / denom;
}

export function selectTopKExamples(
  queryEmbedding: number[],
  examples: LabeledExample[],
  topK = 4,
  minSimilarity = 0.2
): Array<{ id: string; text: string; label: string; score: number }> {
  return examples
    .map((ex) => ({
      id: ex.id,
      text: ex.text,
      label: ex.label,
      score: cosineSimilarity(queryEmbedding, ex.embedding),
    }))
    .filter((item) => item.score >= minSimilarity)
    .sort((a, b) => b.score - a.score)
    .slice(0, topK);
}

export function buildDynamicClassificationPrompt(params: {
  inputText: string;
  queryEmbedding: number[];
  examples: LabeledExample[];
  allowedLabels: string[];
  topK?: number;
}): ClassificationPrompt {
  const selectedExamples = selectTopKExamples(
    params.queryEmbedding,
    params.examples,
    params.topK ?? 4
  );

  const systemInstruction = [
    "You are a precise text classifier.",
    `Choose strictly one label from: ${params.allowedLabels.join(", ")}.`, 'Respond only with valid JSON: {"label": "<chosen_label>", "confidence": <0_to_1>}.', ].join(" ");  const formattedShots = selectedExamples .map( (ex, idx) => `Example ${idx + 1}:\nInput: ${JSON.stringify(ex.text)}\nLabel:${JSON.stringify(ex.label)}`
    )
    .join("\n\n");

  const userPrompt = [
    formattedShots ? `Reference Examples:\n\${formattedShots}` : "No close examples found.",
    `Target Input:\n\${JSON.stringify(params.inputText)}`,
  ].join("\n\n");

  return {
    systemInstruction,
    userPrompt,
    selectedExamples,
  };
}

Tips

  • Include hard edge cases in your example pool: Add near-miss examples between closely related classes so similarity search surfaces them on ambiguous queries.
  • Keep the example pool clean and deduplicated: Badly labeled or duplicate training items will skew nearest-neighbor retrieval and hurt accuracy.
  • Pair similarity with class diversity when needed: If top-k returns only one label on borderline inputs, pick the top match per candidate class before filling remaining slots by highest score.