This prompt is for RAG system builders and search engineers who must fit the most valuable evidence into a constrained context window. When your retrieval pipeline returns 20, 50, or 100 passages but your answer-generation model can only accept 4K tokens of context, you need a selection step that maximizes coverage while eliminating redundancy. This prompt operates after retrieval and before answer generation, acting as a budget-aware gate that picks the top-K passages most likely to produce a grounded, complete answer. Use this when your context budget is fixed, your retrieval set is larger than your budget allows, and you need explicit coverage verification before downstream generation.
Prompt
Top-K Evidence Selection Prompt Template

When to Use This Prompt
Identify the production scenarios where a budget-aware Top-K evidence selector is the right tool, and recognize when simpler or different approaches are required.
The ideal deployment scenario has three characteristics: a known token or passage-count budget, a retrieval set that exceeds that budget by at least 2x, and a downstream generator that will faithfully use only the selected passages. The prompt template accepts a ranked or unranked list of candidate passages, a query or claim to ground against, a selection budget (K), and optional constraints like diversity requirements or source authority preferences. It returns exactly K passages with selection rationale and a coverage assessment that flags any query aspects not addressed by the selected set. This coverage check is the key differentiator from simpler relevance scoring—it prevents the common failure mode where all top-K passages address the same sub-topic while leaving other parts of the question unanswered.
Do not use this prompt when your retrieval set already fits within the context budget, when you need real-time sub-50ms selection latency, or when your downstream generator has its own built-in attention mechanisms that handle long contexts natively. For retrieval sets under 10 passages, direct inclusion is simpler and avoids an extra model call. For latency-critical paths, consider embedding-based similarity ranking or a lightweight cross-encoder instead. This prompt is also inappropriate when the evidence requires complex multi-hop reasoning to assess—the selection step should evaluate individual passage value, not solve the full reasoning chain. If your use case involves regulated domains like healthcare or legal, add a human review step between selection and answer generation, and log the full selection rationale for audit trails.
Use Case Fit
Where the Top-K Evidence Selection prompt works, where it fails, and what you must provide before using it in production.
Good Fit: Budget-Constrained RAG Pipelines
Use when: Your context window is limited and you must select the top-K most valuable passages from a larger retrieval set. Guardrail: Always pair selection with a coverage check to ensure the chosen passages collectively address all query aspects.
Bad Fit: Single-Source or Small Retrieval Sets
Avoid when: You have fewer than K passages or all passages come from a single document. Selection adds latency without benefit. Guardrail: Bypass the selection step entirely when the retrieval set is already within budget.
Required Input: Scored Retrieval Set
Risk: Running selection on unscored passages produces arbitrary rankings. Guardrail: Provide relevance scores, source metadata, and passage IDs. The prompt needs enough signal to compare passages, not just raw text.
Operational Risk: Coverage Gaps Under Budget
Risk: Top-K selection can drop passages that cover required sub-topics, producing incomplete answers downstream. Guardrail: Add a coverage verification step after selection. If gaps exist, trigger re-retrieval or expand K before proceeding to generation.
Operational Risk: Redundancy Amplification
Risk: Near-duplicate passages can consume K slots, crowding out diverse evidence. Guardrail: Run deduplication before selection or include a diversity constraint in the prompt to prevent single-source dominance.
Operational Risk: Position and Length Bias
Risk: Models may favor earlier or longer passages regardless of relevance. Guardrail: Randomize passage order before prompting and include explicit anti-bias instructions. Validate with pairwise comparison tests on a golden dataset.
Copy-Ready Prompt Template
A production-ready template for selecting the top-K most valuable evidence passages from a larger retrieval set, optimized for coverage and non-redundancy within strict token budgets.
This template is designed to be pasted directly into your system prompt or as a user message in a RAG pipeline. It instructs the model to act as a strict evidence curator, selecting a fixed number of passages that maximize informational value while respecting a hard context budget. The prompt forces explicit trade-offs between relevance, redundancy, and coverage, making the selection logic auditable rather than a black box. Before using it, ensure you have already retrieved a candidate set of passages and have a clear understanding of your downstream task's token limit.
textYou are an evidence curator for a retrieval-augmented generation system. Your task is to select the top [K] most valuable evidence passages from the provided candidate set. You must operate within a strict total token budget of [MAX_TOKENS] tokens for the selected passages combined. ## INPUT **User Query:** [QUERY] **Candidate Passages:** A list of [N] passages, each with a unique ID, source metadata, and text content. [CANDIDATE_PASSAGES] ## SELECTION CRITERIA Rank and select passages based on the following weighted priorities: 1. **Direct Relevance (Highest Priority):** The passage must directly address a core aspect of the user query. Penalize tangential or merely topically related content. 2. **Specificity and Factual Density:** Prefer passages with concrete facts, numbers, or specific claims over vague or general statements. 3. **Non-Redundancy:** If two passages convey the same information, select only the one with the highest authority or specificity. Do not waste the budget on duplicates. 4. **Coverage:** The final set of [K] passages should collectively cover as many distinct aspects of the query as possible. Identify and flag any critical query sub-topics that have zero supporting passages. 5. **Source Authority:** When choosing between equally relevant passages, prefer those from more authoritative or recent sources based on the provided metadata. ## CONSTRAINTS - You MUST select exactly [K] passages. No more, no less. - The combined token count of the selected passages MUST NOT exceed [MAX_TOKENS]. - You MUST NOT modify, summarize, or paraphrase the passage text. Output the full original text of each selected passage. - If fewer than [K] passages meet a minimum relevance threshold, select only those that do and explain the shortfall. ## OUTPUT FORMAT Return a valid JSON object with the following schema: { "selected_passages": [ { "passage_id": "string", "rank": integer, "relevance_score": float (0.0 to 1.0), "selection_rationale": "One-sentence explanation of why this passage was chosen.", "text": "Full original passage text." } ], "coverage_assessment": { "covered_aspects": ["list of query sub-topics covered"], "missed_aspects": ["list of query sub-topics with no supporting evidence"], "redundancy_removed": ["list of passage IDs excluded due to redundancy"] }, "budget_utilization": { "total_tokens_used": integer, "budget_remaining": integer } }
To adapt this template for your application, replace the square-bracket placeholders with your runtime data. The [CANDIDATE_PASSAGES] placeholder should be populated with a pre-serialized list of your retrieval results, each containing an ID, text, and any available metadata like date or source domain. The [K] and [MAX_TOKENS] values should be derived from your downstream model's context window and the space reserved for instructions and the final answer. If your use case is high-stakes—such as medical or legal reasoning—add a [RISK_LEVEL] field and a constraint requiring the model to flag any selected passage that contains speculative or unverified claims. Always validate the output JSON against the schema before passing the selected passages to your answer generation step. A common failure mode is the model returning K-1 or K+1 passages; implement a retry loop that detects count mismatches and re-prompts with a stricter instruction.
Prompt Variables
Required inputs for the Top-K Evidence Selection Prompt Template. Each variable must be populated before the prompt is assembled and sent to the model. Missing or malformed inputs are the most common cause of selection failures in production.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The user question or claim that evidence must support | What were the root causes of the March 2024 outage? | Must be non-empty string. Check for vague queries under 10 chars; flag for human review if query is ambiguous |
[RETRIEVAL_SET] | Array of evidence passages with metadata from upstream retrieval | [{"id":"doc-12","text":"The primary cause was...","source":"postmortem.md","date":"2024-03-15"}] | Must be valid JSON array with at least 1 passage. Each passage requires id and text fields. Null or empty array triggers early abort |
[TOP_K] | Number of evidence passages to select within the context budget | 5 | Must be positive integer. Validate against [MAX_TOKENS] budget: estimated tokens per passage × TOP_K must not exceed budget. Reject if TOP_K > len([RETRIEVAL_SET]) |
[MAX_TOKENS] | Total token budget available for selected evidence in the downstream prompt | 4000 | Must be positive integer. Used to calculate per-passage token allocation. If budget is too small for meaningful evidence, trigger fallback to narrower retrieval |
[SELECTION_CRITERIA] | Ordered list of criteria for ranking evidence priority | ["relevance", "specificity", "source_authority", "non_redundancy"] | Must be non-empty array. Validate each criterion against allowed set. Missing criteria defaults to ["relevance", "non_redundancy"]. Warn if "coverage" is omitted for multi-aspect queries |
[COVERAGE_REQUIREMENT] | Whether the selected set must cover all query aspects or best-effort is acceptable | strict | Must be "strict" or "best_effort". Strict mode triggers gap detection and re-retrieval recommendation. Best-effort mode selects strongest evidence even with coverage gaps |
[OUTPUT_SCHEMA] | Expected JSON structure for the ranked selection output | {"selected":[{"id":"string","rank":int,"rationale":"string"}],"coverage_gaps":["string"],"budget_used_tokens":int} | Must be valid JSON Schema or example structure. Validate that schema includes id, rank, and rationale fields. Missing rationale field disables explainability output |
[DOMAIN_CONTEXT] | Optional domain-specific terminology, authority signals, or ranking preferences | {"domain":"infrastructure","prefer_sources":["postmortems","incident_reports"],"deprioritize":["chat_messages"]} | Nullable. If provided, must be valid JSON object. Domain context is injected into ranking instructions. Null is acceptable for general-purpose ranking |
Implementation Harness Notes
How to wire the Top-K Evidence Selection prompt into a production RAG pipeline with validation, retries, and budget-aware gating.
The Top-K Evidence Selection prompt is designed to sit between retrieval and answer generation in a RAG pipeline. It consumes a larger retrieval set and produces a compact, ranked subset that fits within a strict context budget. The implementation harness must handle three core responsibilities: enforcing the token budget, validating the output structure, and providing a fallback path when the model fails to produce a usable ranking. This prompt is not a standalone component—it is a gating step that determines which evidence reaches the downstream answer generator, so harness reliability directly impacts answer quality.
Wire the prompt into your application as a pre-generation filter. After retrieval returns N passages, call the Top-K selection prompt with [RETRIEVED_PASSAGES], [QUERY], [TOP_K], and [MAX_TOKENS]. Parse the output against a strict JSON schema that requires selected_passages (array of passage IDs), selection_rationale (string), and coverage_gaps (array of strings). Implement a validation layer that checks: (1) the number of selected passages does not exceed [TOP_K], (2) all selected passage IDs exist in the input set, (3) the total token count of selected passages is under [MAX_TOKENS], and (4) the coverage_gaps field is populated when the model identifies missing sub-topics. If validation fails, retry once with the validation errors injected into the prompt as [PREVIOUS_ERRORS]. After two failures, fall back to a deterministic baseline: select the top [TOP_K] passages by retrieval score and truncate each to fit the budget.
For model choice, use a model with strong instruction-following and structured output capabilities. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are all suitable. Avoid smaller or older models that struggle with multi-constraint ranking tasks—they tend to ignore the token budget or produce malformed passage IDs. Set temperature=0 or very low (0.1) to maximize ranking stability. For logging, capture the full input retrieval set, the selected subset, the rationale, any coverage gaps flagged, validation results, and retry counts. This trace data is essential for debugging when downstream answer quality degrades—you need to know whether the problem originated in retrieval, evidence selection, or answer generation.
When integrating with a RAG pipeline, connect the coverage gap output to a re-retrieval trigger. If the model flags that no passage addresses a required sub-topic, your harness should issue a targeted retrieval query for that gap and re-run the selection prompt with the expanded set. Cap re-retrieval at one or two rounds to avoid infinite loops. For high-stakes domains (legal, medical, financial), add a human review step when coverage gaps are detected or when the model's confidence language in the rationale indicates uncertainty. The harness should also track the token utilization ratio (selected tokens / budget) to identify cases where the model is consistently under- or over-packing the context window—both patterns indicate ranking behavior that needs tuning.
Avoid wiring this prompt directly into a synchronous user-facing response path without the validation and fallback layers described above. A malformed ranking that passes garbage passage IDs to the answer generator will produce hallucinated citations that are difficult to detect downstream. Instead, treat the Top-K selection step as an internal pipeline gate with its own monitoring: track selection latency, validation failure rate, coverage gap frequency, and fallback activation rate. These metrics will tell you when your retrieval set quality, prompt design, or model choice needs adjustment before users ever see degraded answers.
Expected Output Contract
Defines the strict JSON schema for the Top-K evidence selection response. Use this contract to validate model output before passing ranked passages to downstream answer generation.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
selected_passages | Array of objects | Array length must be between 1 and [TOP_K]. Reject if empty or exceeds budget. | |
selected_passages[].passage_id | String | Must match an id from the input [PASSAGES] array. Reject if orphaned or hallucinated. | |
selected_passages[].relevance_score | Number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Reject if null, non-numeric, or out of range. | |
selected_passages[].selection_rationale | String | Must be 1-2 sentences referencing specific content from the passage. Reject if generic, empty, or exceeding 300 characters. | |
coverage_assessment | Object | Must contain a 'covered_aspects' and 'uncovered_aspects' array. Reject if missing either key. | |
coverage_assessment.covered_aspects | Array of strings | Each string must map to a sub-topic from the input [QUERY_ASPECTS] if provided. Reject if empty when [QUERY_ASPECTS] is non-empty. | |
coverage_assessment.uncovered_aspects | Array of strings | Must list any [QUERY_ASPECTS] not addressed by selected passages. Reject if a known aspect is missing from both covered and uncovered lists. | |
total_tokens_used | Number (integer) | Must be an integer less than or equal to [TOKEN_BUDGET]. Reject if exceeded or if value is not a positive integer. |
Common Failure Modes
Top-K evidence selection fails in predictable ways. These are the most common production failure modes and the specific guardrails that catch them before they affect users.
Position Bias Skews Selection
What to watch: The model disproportionately selects passages at the beginning or end of the retrieval list, ignoring stronger evidence in the middle. This happens because attention mechanisms overweight boundary positions. Guardrail: Shuffle passage order before prompting, run selection twice with reversed ordering, and flag passages that change selection status across runs as unstable.
Length Bias Favors Verbose Passages
What to watch: Longer passages get selected over shorter, more precise ones because token count correlates with perceived informativeness. A 500-word passage with one relevant sentence beats a 50-word passage that is entirely on-point. Guardrail: Normalize passage lengths before ranking, include a brevity preference in the prompt, and validate that selected passages are not simply the longest in the candidate set.
Redundant Selections Waste Budget
What to watch: Top-K selections contain semantically near-duplicate passages from the same source or covering identical facts. This consumes the context budget without adding coverage, starving other relevant evidence. Guardrail: Add an explicit diversity constraint in the prompt, run a post-selection deduplication check using embedding similarity, and enforce a maximum passages-per-source limit.
Coverage Gaps Go Undetected
What to watch: The selected Top-K passages all address one aspect of a multi-faceted query while leaving other required sub-topics completely uncovered. The model confidently selects what it has rather than flagging what is missing. Guardrail: Decompose the query into required sub-topics before selection, verify that each sub-topic has at least one supporting passage, and trigger re-retrieval for uncovered facets.
Authority Overfitting Ignores Content
What to watch: The model overweights source authority signals and selects passages from trusted domains even when the content is tangential or outdated, while rejecting highly relevant passages from less familiar sources. Guardrail: Separate authority assessment from relevance ranking, apply authority as a tiebreaker not a primary filter, and spot-check whether rejected high-relevance passages came from lower-authority sources.
Budget Exhaustion Without Verification
What to watch: The model fills the token budget with selections but never verifies whether the chosen set is collectively sufficient to answer the query. Budget-full does not mean evidence-complete. Guardrail: Reserve a portion of the context budget for a self-verification step, ask the model to identify what the selected set still cannot answer, and escalate to human review when critical gaps remain.
Evaluation Rubric
Criteria for testing the Top-K Evidence Selection prompt before deployment. Each row defines a pass standard, a failure signal, and a concrete test method to catch regressions early.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Budget Adherence | Total token count of selected passages is less than or equal to [MAX_TOKENS]. | Selected passages exceed [MAX_TOKENS] by any amount. | Run prompt with a large retrieval set. Parse the output and sum the token count of all selected passage IDs. Assert sum <= [MAX_TOKENS]. |
K-Constraint | Exactly [K] passages are selected unless the total retrieval set is smaller than [K]. | Output contains more than [K] passages or fewer than the available passages when the set size is >= [K]. | Provide a retrieval set with size > [K]. Assert the length of the selected passage list equals [K]. Provide a set with size < [K] and assert all are selected. |
Non-Redundancy | No two selected passages convey the same core fact or quote the same source line. | Two selected passages have a pairwise cosine similarity > 0.9 or are from the same document section with identical claims. | Compute pairwise semantic similarity of all selected passages. Assert all pairs are below a similarity threshold. Manually review a sample for near-duplicate claims. |
Coverage Verification | The selected set collectively addresses all distinct sub-topics in [QUERY]. | A required sub-topic from [QUERY] has zero supporting passages in the selected set. | Decompose [QUERY] into a checklist of sub-topics. For each sub-topic, assert at least one selected passage is relevant. Flag any uncovered sub-topic. |
Schema Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present. | JSON parsing fails, a required field like | Validate the raw output string against the expected JSON schema. Assert no parsing errors and all required fields are present with correct types. |
Selection Rationale | Each selected passage includes a concise | A selected passage has a null, empty, or generic rationale like 'relevant' or 'good evidence'. | Parse the output and assert that every entry in the |
Stability | Running the same input twice produces an identical ranked list of passage IDs. | The list of selected passage IDs changes between runs with the same input and temperature=0. | Execute the prompt twice with identical inputs and temperature set to 0. Assert the ordered list of |
Abstention on Empty Retrieval | When the retrieval set is empty, the output returns an empty selection list and a | The model hallucinates passage IDs, throws a format error, or fabricates evidence. | Provide an empty |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base template and a small retrieval set (10-15 passages). Use a frontier model with default temperature. Skip strict schema enforcement initially—accept natural language rankings to validate the selection logic before engineering the output contract.
Simplify the prompt by removing budget-awareness and coverage verification checks. Focus on getting the core selection behavior right: can the model pick the top [K] passages that maximize relevance and minimize redundancy?
Prompt modification
Remove the [OUTPUT_SCHEMA] block and replace with: Return a numbered list of the top [K] passages with a one-sentence justification for each selection.
Watch for
- Position bias where early passages are favored regardless of content
- Length bias where longer passages are selected over shorter, more relevant ones
- Model selecting passages that sound authoritative but lack specific evidence
- No redundancy detection without explicit instructions

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us