Inferensys

Prompt

Query Variant Scoring and Selection Prompt for Retrieval Pipelines

A practical prompt playbook for using Query Variant Scoring and Selection Prompt for Retrieval Pipelines in production AI workflows.
Developer working on RAG retrieval system, document chunks visible on screen, technical workspace with code editor.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for scoring and selecting query variants in a retrieval pipeline.

This prompt is for infrastructure teams that have already generated multiple candidate query variants—from dense vector rewrites, sparse keyword expansions, graph traversals, or other backends—and now need to decide which subset to execute. The job-to-be-done is scoring and selection: given a set of candidate queries, a retrieval objective, and backend constraints, the prompt evaluates each variant, assigns a score, and produces a ranked, justified selection set. The ideal user is a retrieval pipeline engineer or RAG architect who understands their backend capabilities and can define what 'good' looks like for their system. Required context includes the original user question, the list of candidate query variants, the available retrieval backends and their strengths, and the evaluation criteria (e.g., recall priority, precision priority, latency budget, or cost constraints).

Do not use this prompt when you need to generate query variants—that belongs upstream in the pipeline with dedicated expansion, decomposition, or backend-specific rewriting prompts. This prompt assumes candidates already exist. It is also not a replacement for retrieval result evaluation; it scores queries before execution, not after. Avoid using it when the selection criteria are purely deterministic (e.g., 'always run all variants' or 'pick the first three')—a simple rule in application code is cheaper and more reliable. The prompt adds value when selection requires semantic judgment: weighing trade-offs between recall and precision, detecting redundant variants, or justifying why a particular formulation is better suited to a specific backend.

Before wiring this into production, define your evaluation rubric explicitly. The prompt needs concrete scoring dimensions—such as semantic alignment with user intent, backend suitability, term specificity, and variant diversity—not vague instructions like 'pick the best ones.' Build a small golden dataset of query variant sets with expected selections and use it for regression testing whenever the prompt or scoring criteria change. If the selection decision gates expensive retrieval calls or affects downstream answer quality, add a human review step for low-confidence selections or flag cases where score distributions are flat (indicating no clear winner). The next section provides the copy-ready template you can adapt with your own scoring dimensions and backend descriptions.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if query variant scoring is the right tool for your retrieval pipeline stage.

01

Good Fit: Multi-Backend Retrieval Pipelines

Use when: You have generated 5–20 query variants from different rewriters (dense, sparse, graph) and need to select the top-k for execution. Guardrail: The prompt assumes variants already exist. Do not use it to generate variants from scratch; pair it with a multi-backend generation prompt.

02

Bad Fit: Single-Query, Single-Backend Systems

Avoid when: Your pipeline produces only one query variant for one backend. Risk: The scoring overhead adds latency without benefit when there is no selection decision to make. Guardrail: Use a direct query rewriting prompt instead of a scoring-and-selection layer.

03

Required Inputs: Variants, Objectives, and Backend Profiles

What to watch: The prompt needs a list of candidate query strings, explicit retrieval objectives (recall, precision, latency), and backend capability descriptions. Guardrail: Missing objective definitions cause the model to guess, producing inconsistent selections. Always include a structured [RETRIEVAL_OBJECTIVES] block.

04

Operational Risk: Scoring Instability Across Runs

What to watch: LLM-based scoring can produce different selections for the same input across calls, especially with temperature > 0. Guardrail: Run the scoring prompt at temperature 0, cache results for identical variant sets, and log selection decisions with justification for audit. Add a deterministic tiebreaker rule in post-processing.

05

Operational Risk: Latency Budget Blowout

What to watch: Scoring 20 variants with detailed justification can add 2–5 seconds of LLM latency before retrieval even starts. Guardrail: Set a hard variant count cap (e.g., max 10 candidates), use a smaller/faster model for scoring, and consider a two-stage approach: fast filtering then detailed scoring on the top 5.

06

Bad Fit: Real-Time User-Facing Search

Avoid when: The retrieval pipeline must return results in under 200ms. Risk: LLM scoring latency is incompatible with real-time search UX. Guardrail: Reserve this prompt for async or batch retrieval pipelines, offline index building, or evaluation harnesses where latency tolerance is higher.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for scoring and selecting query variants against retrieval objectives before execution.

This prompt template evaluates a set of generated query variants against your defined retrieval objectives and selects the optimal subset for execution. It is designed to sit between query generation and retrieval dispatch in a multi-stage pipeline, ensuring that only high-quality, complementary variants are sent to backends. The template requires you to supply the original user query, the candidate variants, and your retrieval objectives. It returns a scored, ranked, and justified selection list that your application can parse and act on.

text
You are a retrieval pipeline quality controller. Your task is to score and select query variants for execution against a set of retrieval objectives.

## INPUT
- Original User Query: [ORIGINAL_QUERY]
- Candidate Query Variants: [CANDIDATE_VARIANTS]
- Retrieval Objectives: [RETRIEVAL_OBJECTIVES]
- Backend Constraints: [BACKEND_CONSTRAINTS]
- Selection Budget: [MAX_VARIANTS]

## OUTPUT SCHEMA
Return a JSON object with this exact structure:
{
  "selected_variants": [
    {
      "variant": "string",
      "score": number,
      "justification": "string",
      "backend_assignment": "string"
    }
  ],
  "rejected_variants": [
    {
      "variant": "string",
      "rejection_reason": "string"
    }
  ],
  "selection_summary": "string"
}

## SCORING RULES
1. Score each variant from 0.0 to 1.0 against EVERY retrieval objective.
2. A variant's final score is the weighted average across objectives.
3. Penalize variants that are near-duplicates of higher-scored variants (cosine similarity > 0.85).
4. Prefer variants that cover different retrieval strategies (dense, sparse, graph) when objectives require diversity.
5. Reject variants that violate backend constraints or are semantically contradictory to the original query.

## CONSTRAINTS
- Do not select more than [MAX_VARIANTS] variants.
- Every selected variant must have a backend assignment matching [BACKEND_CONSTRAINTS].
- Justifications must reference specific retrieval objectives.
- If no variant scores above 0.3, select none and explain why in the summary.

## EVALUATION CHECK
Before returning, verify:
- Scores are consistent with the stated objectives.
- No duplicate or near-duplicate variants are selected.
- The selection summary accurately reflects the trade-offs made.

To adapt this template, replace each square-bracket placeholder with concrete values from your pipeline. [ORIGINAL_QUERY] should be the raw user input. [CANDIDATE_VARIANTS] is the list of query strings produced by your upstream generation step. [RETRIEVAL_OBJECTIVES] should enumerate what matters for your use case—such as recall, precision, latency, diversity, or backend-specific constraints. [BACKEND_CONSTRAINTS] specifies which backends are available and their requirements. [MAX_VARIANTS] caps the number of variants sent downstream to control cost and latency. If your pipeline does not use weighted objectives, simplify the scoring rules to a single criterion. If you need deterministic selection, add a tie-breaking rule such as preferring the shortest variant or the one with the highest individual objective score.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Query Variant Scoring and Selection Prompt. Each placeholder must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of scoring inconsistency.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The original user question that triggered retrieval

What are the latency requirements for the payment API?

Non-empty string; must be the raw user input before any rewriting

[QUERY_VARIANTS]

Array of candidate query objects generated by upstream rewriters, each with a variant ID and backend target

[{"variant_id":"v1","query_text":"payment API latency SLA","target_backend":"sparse"}]

Must be valid JSON array with at least 2 variants; each object requires variant_id, query_text, and target_backend fields

[RETRIEVAL_OBJECTIVES]

Ordered list of objectives the retrieval pipeline must satisfy, such as recall, precision, latency, or diversity

["maximize_recall","minimize_latency","prefer_recent_sources"]

Must contain 1-5 objectives from the allowed enum; unknown objectives cause the model to hallucinate weights

[BACKEND_CAPABILITIES]

Map of each available backend to its strengths, weaknesses, and schema constraints

{"dense":{"strength":"semantic_similarity"},"sparse":{"strength":"exact_term_match"}}

Must be valid JSON object with at least one backend; missing capability descriptions lead to uninformed scoring

[MAX_VARIANTS_TO_SELECT]

Upper bound on how many query variants the model may include in the final set

5

Integer between 1 and 20; values above 20 risk diluting retrieval precision across too many queries

[SCORING_CRITERIA]

Weighted criteria the model must use when assigning scores to each variant

{"objective_alignment":0.5,"backend_fit":0.3,"diversity_contribution":0.2}

Weights must sum to 1.0; criteria names must match the scoring dimensions referenced in the prompt instructions

[OUTPUT_SCHEMA]

Expected JSON structure for the scored and selected variants response

{"selected_variants":[],"excluded_variants":[],"scoring_rationale":""}

Must be a valid JSON Schema or example object; the model will use this to structure its output

[FALLBACK_BEHAVIOR]

Instruction for what to do when no variant scores above the minimum threshold

select_top_2_regardless_of_score

Must be one of: select_top_n, return_empty, escalate_to_human, or use_raw_user_query

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Query Variant Scoring and Selection prompt into a production retrieval pipeline with validation, retries, and observability.

This prompt operates as a scoring and selection gate between query variant generation and retrieval execution. It receives a batch of candidate query variants—typically produced by upstream rewriters, expanders, or decomposition prompts—and must return a ranked, justified selection of which variants to execute against which backends. The harness should treat this as a deterministic step in a retrieval DAG: the prompt's output directly controls which indexes receive traffic, so validation failures must halt execution rather than silently falling through to retrieval with unvetted queries.

Integration pattern: Place this prompt after all variant generation steps and before any retrieval dispatch. The input payload should include the original user query, the generated variants with their source metadata (which rewriter produced each, intended backend type, confidence scores if available), and the retrieval objectives (e.g., maximize recall, balance precision, optimize for dense-only). The output schema must be strictly validated before proceeding: check that every selected variant has a non-empty justification, that the selected boolean field is present, and that at least one variant is selected unless the prompt explicitly returns an empty selection with a documented reason. Use a JSON Schema validator in your application layer—do not rely on the model to always produce valid JSON. On validation failure, retry once with the error message injected into the prompt context. If the retry also fails, log the full payload and escalate to a human review queue rather than silently proceeding.

Model choice and latency budget: This is a classification-and-ranking task with structured output requirements. Use a model with strong instruction-following and JSON mode support (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set temperature=0 to maximize scoring consistency across calls. Expect 200-800ms latency for typical variant batches of 5-15 candidates. If your retrieval pipeline has a sub-200ms total budget, consider pre-computing variant selections for common query templates or caching selections keyed by query embedding clusters. Logging and observability: Log the full prompt input, output, validation status, and selected variant IDs to your tracing system. Tag spans with prompt_id, variant_count, selection_count, and validation_passed. This data is critical for debugging retrieval quality regressions—when recall drops, you need to know whether the scoring prompt excluded a variant that would have retrieved the answer. Failure modes to monitor: (1) The prompt selects all variants with weak justifications, indicating it's not actually discriminating; (2) it consistently rejects variants from a specific rewriter, suggesting a bias in the scoring criteria; (3) justifications contradict the stated retrieval objectives; (4) the output omits the justification field entirely. Set up eval assertions that spot-check justification quality against human judgments on a golden set of 50 query-variant pairs.

Next steps after implementation: Once the harness is in place, run a shadow evaluation where you execute all variants regardless of the scoring prompt's selection, then compare retrieval quality between the selected subset and the full set. This measures the prompt's selection precision—you want high recall with fewer queries. If the selected subset underperforms, adjust the scoring criteria in the prompt template or add few-shot examples showing correct selection behavior for your domain. Avoid the temptation to bypass this prompt when retrieval results look acceptable; the selection step exists to reduce wasted compute and prevent noisy results from poorly-matched variants, and its value compounds as your variant generation surface grows.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the JSON object returned by the Query Variant Scoring and Selection Prompt. Use this contract to parse and validate the model's output before passing it to the retrieval execution layer.

Field or ElementType or FormatRequiredValidation Rule

selected_queries

Array of objects

Array length must be >= 1. Each object must match the selected_query_object schema.

selected_queries[].query_string

String

Non-empty string. Must match one of the candidate query strings provided in [CANDIDATE_QUERIES].

selected_queries[].backend_target

String

Must be one of the values listed in [AVAILABLE_BACKENDS]. Enum check required.

selected_queries[].score

Number

Must be a float between 0.0 and 1.0 inclusive. Higher values indicate stronger alignment with retrieval objectives.

selected_queries[].justification

String

Non-empty string. Must contain a concise reason for inclusion, referencing specific evaluation criteria from [SCORING_CRITERIA].

rejected_queries

Array of objects

If present, each object must match the rejected_query_object schema. An empty array is acceptable.

rejected_queries[].query_string

String

Non-empty string. Must match one of the candidate query strings provided in [CANDIDATE_QUERIES].

rejected_queries[].rejection_reason

String

Non-empty string. Must explain why the query was excluded, referencing redundancy, low relevance, or conflict with [SCORING_CRITERIA].

PRACTICAL GUARDRAILS

Common Failure Modes

When scoring and selecting query variants in a retrieval pipeline, these failures degrade result quality, increase latency, or waste compute. Each card identifies a specific failure and the guardrail that prevents it.

01

Scoring Collapse: All Variants Get Similar Scores

What to watch: The scoring prompt assigns nearly identical scores to all query variants, making selection arbitrary. This happens when the scoring criteria are too vague, the variants are too similar, or the model defaults to a safe middle score. Guardrail: Require forced distribution in the prompt—instruct the model to assign at least one high, one medium, and one low score per batch. Validate score variance programmatically and trigger re-scoring if standard deviation falls below a threshold.

02

Selection Without Justification

What to watch: The model selects query variants but provides no reasoning, or the reasoning is post-hoc rationalization that doesn't reference the scoring criteria. This makes pipeline decisions un-auditable and hides systematic errors. Guardrail: Require structured justification per variant that maps to specific scoring dimensions (e.g., recall potential, precision risk, backend fit). Validate that every selected variant has a non-empty justification field before execution.

03

Backend Mismatch: Variant Assigned to Wrong Index Type

What to watch: A query variant optimized for dense vector retrieval gets routed to a sparse keyword index, or vice versa. The variant executes but returns irrelevant results because the formulation doesn't match the backend's matching algorithm. Guardrail: Include backend type as a required field in the selection output schema. Validate that each selected variant's formulation style matches its assigned backend before dispatch. Add a pre-execution check that rejects dense-style queries sent to BM25 indexes.

04

Over-Selection: Too Many Variants Executed

What to watch: The model selects all or most generated variants, defeating the purpose of scoring and selection. This wastes compute, increases latency, and produces redundant results that complicate fusion. Guardrail: Set an explicit maximum variant count in the prompt constraints. Implement a hard cutoff in the application layer that only executes the top-N variants by score, regardless of what the model returns. Log over-selection events as a prompt drift signal.

05

Intent Drift During Variant Scoring

What to watch: The scoring model misinterprets the original user intent and rewards variants that answer a different question. This is common with ambiguous queries where the model latches onto a plausible but wrong interpretation. Guardrail: Include the original user query and any disambiguation context as a required reference in the scoring prompt. Add an eval check that compares the selected variant's predicted intent against the original query's intent classification. Flag selections where intent diverges beyond a threshold.

06

Score Inconsistency Across Batches

What to watch: The same query variant receives different scores when evaluated in different batches or at different times, making selection thresholds unreliable. This is caused by model non-determinism, context window differences, or batch composition effects. Guardrail: Calibrate scores with a small set of reference variants included in every scoring batch. Normalize scores relative to these anchors. Monitor score drift over time and trigger prompt review when calibration variants shift by more than a configurable delta.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Query Variant Scoring and Selection Prompt's output before deploying it in a production retrieval pipeline. Each criterion targets a specific failure mode common in scoring and selection tasks.

CriterionPass StandardFailure SignalTest Method

Scoring Consistency

All variants of the same intent receive scores within a 0.2 range on a 0-1 scale when evaluated against identical objectives.

Score variance exceeds 0.2 for semantically equivalent variants; contradictory scores for similar queries.

Run the prompt on a golden set of 10 query clusters with known-good variants. Calculate the standard deviation of scores within each cluster.

Selection Justification

Every inclusion or exclusion decision is accompanied by a non-generic, evidence-based reason tied to a specific retrieval objective.

Justifications are missing, circular (e.g., 'selected because it scored well'), or hallucinate retrieval properties not present in the variant.

Parse the output for the justification field. Assert it is non-null and contains at least one keyword from the retrieval objectives list. Manually spot-check 20 samples for hallucinated reasoning.

Objective Alignment

The top-ranked variant for each objective demonstrably optimizes for that objective's stated metric (e.g., recall, precision).

A variant optimized for lexical precision is ranked highest for a semantic recall objective, or vice versa.

Using a labeled dev set, verify that the highest-scoring variant for 'semantic recall' has a higher embedding similarity to the ground-truth answer than the variant selected for 'lexical precision'.

Output Schema Adherence

The output is valid JSON matching the [OUTPUT_SCHEMA] exactly, including all required fields and correct data types.

JSON parsing fails. Required fields like selected_variants or excluded_variants are missing. Scores are strings instead of floats.

Validate the raw model output against the [OUTPUT_SCHEMA] using a JSON schema validator. The test must pass with zero errors on a 50-sample run.

Exclusion Handling

All generated variants are accounted for in either the selected_variants or excluded_variants list. No variant is silently dropped.

The total count of selected plus excluded variants does not equal the number of input variants. A variant ID appears in neither list.

Assert that len(selected_variants) + len(excluded_variants) == len(input_variants). Flag any mismatch as a critical failure.

Redundancy Detection

Near-duplicate variants are identified, and only the highest-scoring representative is selected for execution.

Two variants with a high ROUGE-L similarity (>0.9) are both present in the selected_variants list without a justification explaining their complementary value.

Compute pairwise ROUGE-L similarity for all selected variants. Flag any pair above 0.9. Check if the justification field explicitly addresses their complementary nature.

Latency Awareness

The selection respects a [MAX_VARIANTS] constraint, prioritizing the highest-impact variants when the candidate pool exceeds the limit.

The number of selected variants exceeds [MAX_VARIANTS] without an explicit override justification. The selection includes low-scoring variants while omitting higher-scoring ones.

Assert that len(selected_variants) <= [MAX_VARIANTS]. If not, check for an override_reason field. Sort selected variants by score and confirm no lower-scored variant is chosen over a higher-scored one that was excluded.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base scoring prompt and a small set of 3–5 query variants. Use a single scoring dimension (e.g., retrieval relevance) and a simple 1–5 scale. Skip strict output schema enforcement initially—accept a JSON object with variant IDs and scores. Run against 10–20 known queries and manually review the selections.

Watch for

  • The model scoring all variants equally high without differentiation
  • Selection bias toward longer or more verbose query variants
  • Missing justification fields that make debugging impossible
  • Overfitting to a single retrieval backend's behavior
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.