Inferensys

Prompt

Top-K Passage Selection Prompt for Constrained Context Windows

A practical prompt playbook for using Top-K Passage Selection Prompt for Constrained Context Windows in production AI workflows.
Engineer optimizing context window usage on laptop, token usage charts visible, technical work session.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the job-to-be-done, ideal user, and production boundaries for the Top-K Passage Selection prompt.

This prompt is designed for retrieval-augmented generation (RAG) pipelines where the total retrieved evidence exceeds the model's context window or a strict token budget. Instead of naive truncation, which discards potentially critical information, this prompt instructs the model to select an optimal subset of passages that maximizes information coverage, relevance, and diversity. Use this when you need a smart, budget-aware gate between retrieval and answer synthesis. It is ideal for production systems where cost and latency constraints require packing the most signal into a limited context.

The ideal user is an AI engineer or search engineer who has already tuned their retrieval step but now faces a context-packing problem. You have more good passages than you can fit. You need a selection step that understands query intent, avoids redundant information, and preserves complementary facts from different sources. This prompt works best when your upstream retrieval returns 20–100 passages and your downstream synthesis model has a budget of 4K–16K tokens. It is not a replacement for retrieval quality—if your top-10 retrieval is already poor, no selection prompt will fix it. It also assumes passages are already chunked and have basic metadata like source titles or IDs.

Do not use this prompt when you have only a handful of passages that easily fit in context, when you need real-time sub-50ms decisions, or when your passages are extremely long and cannot be individually evaluated. In those cases, consider embedding-based re-ranking, simple recency filters, or expanding your context window. For high-stakes domains like healthcare or legal, always log the selected and excluded passages for auditability, and consider a human review step before answers reach users. After implementing this prompt, pair it with an evidence sufficiency check to confirm the selected subset actually contains enough information to answer the question.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Top-K Passage Selection Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your pipeline before integrating it into production.

01

Good Fit: Token-Budgeted RAG Pipelines

Use when: You have a strict context window limit and more retrieved passages than you can fit. The prompt excels at maximizing information coverage under a hard token cap. Guardrail: Always pass the exact token budget as a constraint and validate that the output respects it before synthesis.

02

Bad Fit: Single-Passage or Trivial Retrieval Sets

Avoid when: Your retrieval always returns 1-3 passages that easily fit in the context window. The selection overhead adds latency and cost without meaningful benefit. Guardrail: Implement a pre-check that skips the selection step when len(passages) <= 3 or total tokens are under budget.

03

Required Inputs: Scored Passages with Metadata

What to watch: The prompt needs relevance scores, source identifiers, and passage text. Missing scores force the model to guess relevance, degrading selection quality. Guardrail: Enforce a strict input schema with score, source_id, and text fields. Reject or flag any passage missing these before calling the prompt.

04

Operational Risk: Information Loss from Over-Aggressive Pruning

Risk: The prompt may drop passages containing critical but low-scoring facts, especially for multi-hop questions where a key detail appears in a lower-ranked passage. Guardrail: Log all excluded passages with their scores. Implement an overflow mechanism that flags when excluded passages contain entities present in the user query but absent from selected passages.

05

Operational Risk: Diversity vs. Relevance Trade-Off

Risk: The prompt may over-prioritize diversity and select tangentially relevant passages to cover different angles, diluting the core answer. Guardrail: Add a minimum relevance threshold. Passages below this threshold are excluded even if they would add diversity. Tune this threshold on a golden eval set.

06

Bad Fit: Real-Time Streaming with Ultra-Low Latency

Avoid when: Your system requires sub-200ms response times. The selection step adds a full model round-trip before answer synthesis begins. Guardrail: For latency-sensitive paths, use a deterministic re-ranking heuristic (e.g., score threshold + diversity sampling) and reserve this prompt for async or batch processing pipelines.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for selecting the optimal subset of passages that maximizes information coverage within a strict token budget.

This prompt template is designed to be placed directly into your system or user prompt, acting as a deterministic filter before answer synthesis. It forces the model to make explicit trade-offs between relevance, information diversity, and token cost. The core logic asks the model to prioritize passages that are not only highly relevant but also complementary, ensuring that the final selection covers distinct aspects of the user's query rather than repeating the same information from multiple sources. You should use this when your retrieval step returns more passages than can fit in a single context window and you need a programmatic, auditable selection step.

text
You are an evidence selection specialist. Your task is to select the optimal subset of passages from the provided [RETRIEVED_PASSAGES] that maximizes information coverage for the [USER_QUERY] while strictly adhering to a token budget of [MAX_TOKENS].

# Selection Criteria
1.  **Relevance:** The passage must directly address the [USER_QUERY] or a necessary sub-component of it.
2.  **Information Density:** Prefer passages with high factual content per token. Avoid verbose, redundant, or preamble-heavy passages.
3.  **Complementarity:** Select passages that provide *distinct* pieces of evidence. If two passages convey the same fact, choose the one with higher source credibility or recency and discard the other.
4.  **Source Credibility:** Prioritize passages from sources with higher [CREDIBILITY_WEIGHT] based on authority, recency, and domain expertise.

# Constraints
- The total token count of all selected passages MUST NOT exceed [MAX_TOKENS].
- You must select at least [MIN_PASSAGES] passages, unless fewer than [MIN_PASSAGES] are provided or relevant.
- Do not modify the text of the selected passages. Output them exactly as provided.
- If no passages are sufficiently relevant, return an empty selection and set `sufficient_evidence` to `false`.

# Output Format
You must respond with a valid JSON object conforming to this exact schema:
{
  "sufficient_evidence": boolean,
  "total_selected_tokens": number,
  "selection_rationale": "string explaining the trade-offs made",
  "selected_passages": [
    {
      "passage_id": "string",
      "passage_text": "string",
      "selection_reason": "string"
    }
  ],
  "excluded_passages": [
    {
      "passage_id": "string",
      "exclusion_reason": "string"
    }
  ]
}

# Input Data
**User Query:** [USER_QUERY]
**Token Budget:** [MAX_TOKENS]
**Retrieved Passages:** [RETRIEVED_PASSAGES]

To adapt this template, start by replacing the square-bracket placeholders with your application's dynamic variables. The [RETRIEVED_PASSAGES] should be a pre-formatted list, likely as a JSON array of objects each containing an id, text, and optional metadata like a date or source authority score. The [CREDIBILITY_WEIGHT] placeholder can be replaced with a static instruction like 'prioritize peer-reviewed sources and official documentation' or a dynamic variable if you have a pre-calculated score. The most critical adaptation is the [MAX_TOKENS] value, which you must calculate dynamically based on your model's context window minus the tokens reserved for the system prompt, user query, and the expected output tokens for the final answer. A common failure mode is setting this budget too high, leaving no room for the synthesis step, so implement a token-counting function in your application harness to set this value precisely before calling the model.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Top-K Passage Selection Prompt. Each variable must be validated before prompt assembly to prevent budget overruns, malformed outputs, or selection bias.

PlaceholderPurposeExampleValidation Notes

[PASSAGES]

Array of candidate passages with metadata for selection

[{"id":"doc4_chunk2","text":"The 2024 Q3 revenue...","source":"earnings_report.pdf","date":"2024-10-15","relevance_score":0.87}]

Must be valid JSON array. Each object requires id and text fields. source, date, and relevance_score are optional but recommended. Empty array triggers abstention path. Max 200 passages before pre-filtering is recommended.

[QUERY]

User question or information need driving passage selection

What were the primary drivers of revenue growth in Q3 2024?

Must be non-empty string. Length under 500 tokens recommended. Multi-sentence queries allowed. Check for adversarial or malformed input before passing to prompt.

[TOKEN_BUDGET]

Maximum total tokens allowed for selected passages

4096

Must be positive integer. Should account for downstream synthesis prompt overhead. Validate against model context window minus system prompt and output token reservation. Budget under 512 tokens triggers warning; under 128 may prevent meaningful selection.

[DIVERSITY_WEIGHT]

Controls trade-off between relevance and source diversity in selection

0.3

Float between 0.0 and 1.0. 0.0 maximizes relevance only; 1.0 enforces maximum source diversity. Default 0.3 for balanced selection. Null allowed to use prompt default. Values outside range should clamp or reject.

[MIN_SOURCES]

Minimum number of distinct sources required in selected set

2

Positive integer. Must be <= number of unique sources in [PASSAGES]. Set to 1 to disable diversity enforcement. Null allowed to use prompt default. If impossible given budget, prompt should flag rather than silently violate.

[OUTPUT_SCHEMA]

Expected JSON structure for selected passages and metadata

{"selected_passages":[{"id":"string","text":"string","selection_rationale":"string"}],"total_tokens":0,"coverage_score":0.0,"excluded_passages":[{"id":"string","exclusion_reason":"string"}]}

Must be valid JSON Schema or example structure. Validate that downstream consumers can parse this shape. Include exclusion_reason field for auditability. Schema mismatch between prompt instruction and harness validation causes silent failures.

[OVERFLOW_STRATEGY]

Behavior when no passages fit within token budget

"select_top_1_with_truncation"

Must be one of: "abstain", "select_top_1_with_truncation", "relax_diversity", or "return_empty". "abstain" returns no passages and flags insufficient budget. "select_top_1_with_truncation" picks highest relevance passage and truncates. Validate strategy is implemented in harness, not just prompt.

[PRE_FILTER_THRESHOLD]

Minimum relevance score for passage consideration

0.5

Float between 0.0 and 1.0. Passages below threshold are excluded before selection. Null disables pre-filtering. Set too high and valid evidence may be excluded; set too low and noise dilutes selection quality. Log exclusion count for observability.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Top-K Passage Selection prompt into a production RAG pipeline with token budgeting, validation, and fallback handling.

The Top-K Passage Selection prompt is designed to sit between your retrieval step and your answer synthesis step. It receives a ranked or unranked set of candidate passages and a strict token budget, then returns the optimal subset. In production, this prompt is typically called inside a pre-synthesis filtering function that enforces the budget before the final LLM call. The harness must handle three critical concerns: budget enforcement, output validation, and overflow fallback.

Budget enforcement should happen at the application layer, not just in the prompt. Before calling the selection prompt, calculate the available token budget by subtracting your system prompt, synthesis prompt, and output reservation from the model's context window. Pass this budget as [TOKEN_BUDGET]. After receiving the selected passages, re-count tokens using the same tokenizer your model uses (e.g., tiktoken for OpenAI models). If the returned set exceeds the budget, apply a hard truncation that drops the lowest-ranked passage first, then re-check. Log every budget violation as a warning so you can tune the prompt's compliance rate over time. For high-throughput systems, consider setting the prompt's budget 5-10% below the actual limit to create a safety margin.

Output validation must verify the JSON schema before the selected passages reach synthesis. Check that selected_passages is a valid array, each entry has a passage_id and text field, no passage appears twice, and the exclusion_reasons map references only passages that were excluded. If validation fails, do not silently proceed with partial data. Implement a retry with stricter instructions: append the specific validation error to the next attempt and reduce the temperature. After two retries, fall back to a simpler selection method (e.g., top-N by retrieval score) and log the incident for review. For regulated domains, flag validation failures for human review before any answer reaches the user.

Overflow handling is the most common production failure mode. When the candidate set is so large or passages are so long that even the selection prompt plus the minimum viable context exceeds the model's window, you need a pre-filter. Implement a two-stage selection: first, use a lightweight relevance score threshold or a smaller, faster model to reduce candidates to 2-3x the target count. Only then invoke the full Top-K selection prompt. If the prompt itself fails due to context length, catch the error, apply aggressive truncation to the input passages (keeping only title and first 200 tokens of each), and retry once. If that also fails, escalate to a human operator or return a controlled degradation response indicating insufficient context.

Model choice matters for this prompt. The selection task requires comparative reasoning across passages, not just per-passage scoring. Use a model with strong instruction-following and JSON output capabilities (e.g., GPT-4o, Claude 3.5 Sonnet, or a fine-tuned variant if you have consistent selection patterns). Avoid using the cheapest or fastest model here unless you've validated that its selection quality doesn't degrade your downstream answer accuracy. For cost-sensitive pipelines, consider caching selection results when the same query and candidate set reappear, using a hash of the normalized input as the cache key. Log every selection decision with the query, candidate IDs, selected IDs, exclusion reasons, token counts, and latency. This trace data is essential for debugging hallucination incidents and tuning your retrieval pipeline.

IMPLEMENTATION TABLE

Expected Output Contract

Schema and validation rules for the JSON response produced by the Top-K Passage Selection Prompt. Use this contract to parse, validate, and integrate the model's output into your RAG pipeline before synthesis.

Field or ElementType or FormatRequiredValidation Rule

selected_passages

array of objects

Array length must be <= [MAX_PASSAGES]. If empty, check overflow_passages for evidence of truncation.

selected_passages[].passage_id

string

Must match an id from the input [PASSAGES] array. Fail if id not found in source set.

selected_passages[].relevance_score

number (0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive. Scores should be monotonically non-increasing across the array.

selected_passages[].information_gain

string

Must be a non-empty string explaining what unique information this passage contributes. Fail if null or whitespace only.

excluded_passages

array of objects

Every passage from [PASSAGES] not in selected_passages must appear here. Validate set equality: selected_ids ∪ excluded_ids == input_ids.

excluded_passages[].passage_id

string

Must match an id from the input [PASSAGES] array. Fail if id not found in source set.

excluded_passages[].exclusion_reason

string

Must be one of: 'redundant', 'low_relevance', 'out_of_scope', 'unverifiable', 'stale_date'. Fail on unrecognized values.

overflow_passages

array of objects

Present only when total relevant passages exceed [MAX_PASSAGES]. Each object must contain passage_id and overflow_reason.

total_tokens_used

integer

Must be <= [TOKEN_BUDGET]. If exceeded, selection is invalid and requires retry with stricter budget enforcement.

selection_rationale

string

Must be a non-empty string summarizing the selection strategy. Should reference diversity, complementarity, and budget constraints explicitly.

PRACTICAL GUARDRAILS

Common Failure Modes

Top-K selection fails in predictable ways under token pressure. These are the most common failure modes and the guardrails that catch them before they reach users.

01

Relevance Overfit to First N Passages

What to watch: The model selects passages that all score high on relevance but cover the same narrow aspect of the query, leaving other required dimensions unanswered. This happens when the prompt optimizes for relevance without enforcing diversity. Guardrail: Add an explicit diversity constraint in the prompt requiring coverage of distinct query facets, and validate output with a facet-coverage check before synthesis.

02

Token Budget Exhaustion Without Completeness Signal

What to watch: The model fills the token budget with long passages early in the list, excluding shorter but critical passages that appear later. The selection looks valid but misses essential evidence. Guardrail: Require the model to output a completeness assessment alongside the selection, flagging any known gaps. Post-process with a keyword-recall check against the original query terms.

03

Complementarity Collapse Under Strict Limits

What to watch: When the token budget is very tight, the model drops complementary passages that provide context or counterpoints, producing a selection that is factually correct but misleadingly narrow. Guardrail: Reserve a minimum percentage of the budget for complementary or contrasting evidence. Use an eval that measures answer completeness against a ground-truth evidence set.

04

Position Bias Distorting Selection Order

What to watch: The model overweights passages that appear first in the input list, especially when the input is long. Later passages of equal or higher quality are ignored. Guardrail: Shuffle input passage order before prompting and run selection multiple times. Flag passages whose selection status changes with position as unstable and escalate for human review.

05

Hallucinated Passage Content in Selection Justifications

What to watch: The model correctly selects a passage but fabricates details in the justification or summary that are not present in the original text. This contaminates downstream synthesis. Guardrail: Run a post-selection factuality check that verifies each justification claim against the original passage text. Reject justifications with unsupported claims and regenerate.

06

Silent Truncation of Long Passages

What to watch: The model selects a passage but the application layer truncates it to fit the context window, losing critical information from the end. The selection metadata says the passage is included, but the downstream model sees only a fragment. Guardrail: Implement a pre-flight token counter that validates the full selected passages fit within the allocated budget. If truncation is unavoidable, inject an explicit truncation marker and log a warning.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Top-K Passage Selection Prompt before deployment. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Token Budget Adherence

Total tokens of selected passages are ≤ [MAX_TOKENS] and ≥ 90% of [MAX_TOKENS]

Output exceeds budget or leaves >10% unused without overflow handling

Parse output, tokenize selected passages with target model's tokenizer, sum tokens, compare to [MAX_TOKENS]

Selection Cardinality

Number of selected passages equals [K] unless fewer unique candidates exist

Returns more than [K] passages or fewer than available candidates without justification

Count selected passage IDs, compare to [K] and input candidate count

Relevance Justification

Each selected passage has a non-empty relevance justification referencing query terms

Missing justifications, generic text like 'relevant', or justifications that don't reference query

Regex check for non-empty justification field, keyword overlap check between justification and [QUERY]

Diversity Enforcement

Selected passages cover ≥ [MIN_DISTINCT_SOURCES] unique sources when available

All passages from single source despite multiple sources in candidates

Extract source IDs from selected passages, count unique values, compare to candidate source diversity

Complementarity Check

No two selected passages share >80% token overlap or are flagged as near-duplicates

Output contains passages with near-identical content or high n-gram overlap

Compute pairwise ROUGE-L or Jaccard similarity on selected passages, flag pairs above threshold

Exclusion Rationale

Each excluded passage that ranked in top [K*2] has a specific exclusion reason

High-ranking candidates excluded without explanation or with placeholder reasons

Cross-reference excluded passages against top [K*2] by score, verify exclusion_reason field is populated and specific

Output Schema Validity

JSON output validates against [OUTPUT_SCHEMA] with all required fields present

Missing required fields, wrong types, extra fields, or malformed JSON

Validate output against JSON Schema, check field types, required field presence, no additional properties

Overflow Handling

When candidates < [K], output includes overflow_note explaining shortfall

Silently returns fewer passages without acknowledging insufficient candidates

Check for overflow_note field when len(selected) < [K], verify note describes reason for shortfall

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a simple JSON schema. Use a single [PASSAGES] block with numbered entries and a fixed [TOKEN_BUDGET]. Skip diversity constraints and complementary scoring initially—focus on relevance ranking only. Test with 10-20 passages and a generous budget.

code
Select the top [K] most relevant passages from [PASSAGES] 
that fit within [TOKEN_BUDGET] tokens. Return JSON with 
"selected_passages" array containing passage IDs and relevance scores.

Watch for

  • Model ignoring the token budget entirely
  • All passages scoring 0.9+ with no differentiation
  • JSON keys changing names between runs (e.g., selected vs selected_passages)
  • Model selecting passages that exceed the budget when concatenated
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.