This prompt is for AI engineers and RAG pipeline builders who need to turn a noisy, redundant set of retrieved passages into a ranked, coverage-maximizing context window that fits within a token budget. The job is not to generate an answer—it is to select and order the evidence that will be passed to a downstream answer-generation prompt. Use it when your dense retrieval returns dozens or hundreds of chunks, many of which overlap, repeat the same facts, or contribute no unique information to the query. The prompt expects you to supply the original user query, the raw retrieved passages with their metadata, a target top-k count, and a maximum token budget. It returns a ranked list of selected passages, each annotated with a selection rationale covering relevance, uniqueness, and authority.
Prompt
Context Prioritization Prompt for Dense Retrieval Results

When to Use This Prompt
Define the job, the operator, and the constraints where context prioritization adds value before you copy the template.
Do not use this prompt when the retrieval set is already small (fewer than 10 passages), when all passages are known to be non-overlapping, or when you have already applied a separate deduplication step that guarantees uniqueness. It is also the wrong tool when you need an answer directly—this prompt produces a curated context list, not a final response. If your downstream answer prompt has strict citation requirements, pair this prioritization step with a citation-preserving context assembly so that source provenance survives the selection cut. In high-stakes domains such as clinical or legal Q&A, add a human review gate after prioritization to confirm that no answer-critical evidence was dropped during the top-k selection.
Before wiring this into production, define your evaluation criteria: measure whether the selected passages preserve answer recall compared to the full retrieval set, and track the token savings achieved. Common failure modes include over-prioritizing highly relevant but redundant passages at the expense of unique supporting evidence, or dropping a low-relevance passage that contains a critical date or figure. Start by running this prompt against a golden dataset of query–retrieval pairs where you know which passages are essential, and tune the uniqueness and authority weighting in the template until the top-k set consistently includes those essentials.
Use Case Fit
Where the Context Prioritization Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your retrieval pipeline before integrating it into production.
Good Fit: High-Volume Dense Retrieval
Use when: Your vector search returns 50–200+ chunks with significant semantic overlap, and you need to assemble a top-k set within a strict token budget. Guardrail: Set a minimum relevance threshold so the prompt never promotes low-signal passages just because they are unique.
Good Fit: Multi-Source Knowledge Bases
Use when: Retrieved passages come from documents with varying authority levels (policy docs, wiki pages, emails) and you need authority-aware ranking. Guardrail: Provide explicit source metadata fields (date, author, document type) in each passage so the model can weigh authority without guessing.
Bad Fit: Single-Document Q&A
Avoid when: The user is asking questions over one short document where retrieval returns only 3–5 chunks. Prioritization adds latency without meaningful benefit. Guardrail: Bypass this prompt entirely when the retrieved set is below a configurable chunk-count threshold.
Bad Fit: Real-Time Streaming Applications
Avoid when: Your system requires sub-second response times and the prioritization step adds unacceptable latency. Guardrail: Offload ranking to a lightweight cross-encoder reranker or heuristic scoring layer instead of an LLM call when latency budgets are tight.
Required Input: Structured Passage Metadata
Risk: Without source date, authority level, or document type per passage, the model cannot reliably prioritize by recency or credibility. Guardrail: Enforce a minimum metadata schema (source_id, date, authority_score) on every passage before it reaches this prompt. Fail fast if metadata is missing.
Operational Risk: Silent Evidence Loss
Risk: The prompt may drop passages that contain answer-critical information, especially when the query requires combining facts from multiple low-ranked chunks. Guardrail: Run an over-filtering risk assessment prompt on the filtered set before answer generation, and log dropped-passage IDs for offline eval.
Copy-Ready Prompt Template
A reusable prompt that ranks retrieved passages by relevance, uniqueness, and authority, then selects a top-k set within a token budget.
This prompt template is the core instruction set for a context prioritization step in your RAG pipeline. It expects a set of retrieved passages, a user query, and a token budget. The model ranks each passage on three axes—relevance to the query, information uniqueness relative to other passages, and source authority—then selects a final set that maximizes coverage without exceeding the budget. The output includes the selected passages, their rank scores, and a brief rationale for each selection decision. Use this template when dense retrieval returns more passages than your context window can hold and you need a principled, auditable way to choose what to keep.
codeYou are a context prioritization engine for a retrieval-augmented generation system. Your job is to rank retrieved passages and select a top-k set that maximizes information coverage within a strict token budget. ## INPUT - Query: [QUERY] - Retrieved Passages (each with a unique ID, source title, and text): [RETRIEVED_PASSAGES] - Token Budget: [TOKEN_BUDGET] - Top-K Target: [TOP_K] ## RANKING CRITERIA For each passage, assign a score from 0.0 to 1.0 on each axis: 1. **Relevance**: How directly the passage addresses the query intent. Penalize keyword matches without semantic alignment. 2. **Uniqueness**: How much new information this passage contributes beyond higher-ranked passages already selected. A passage repeating known facts scores low. 3. **Authority**: Source credibility based on recency, publication type, and author expertise. Flag passages from deprecated or unofficial sources. ## SELECTION RULES - Select passages in descending order of a composite score: (Relevance * 0.5) + (Uniqueness * 0.3) + (Authority * 0.2). - After each selection, recompute Uniqueness scores for remaining passages against the growing selected set. - Stop when adding the next passage would exceed [TOKEN_BUDGET] or when [TOP_K] passages have been selected. - If two passages have identical composite scores, prefer the one with higher Authority. ## OUTPUT SCHEMA Return a JSON object with this exact structure: { "selected_passages": [ { "passage_id": "string", "source_title": "string", "text": "string (full passage text)", "relevance_score": number, "uniqueness_score": number, "authority_score": number, "composite_score": number, "selection_rationale": "string (one sentence explaining why this passage was chosen)" } ], "excluded_passages": [ { "passage_id": "string", "exclusion_reason": "string (one of: 'below_relevance_threshold', 'redundant_information', 'budget_exhausted', 'low_authority')" } ], "coverage_assessment": "string (brief summary of what the selected set covers and any known gaps)", "total_tokens_used": number } ## CONSTRAINTS - Do not modify or paraphrase passage text. Return the original text exactly. - If no passage exceeds a relevance score of 0.3, return an empty selected_passages array and set coverage_assessment to 'No sufficiently relevant passages found.' - If the token budget cannot accommodate even the single most relevant passage, select no passages and explain in coverage_assessment.
To adapt this template, start by tuning the composite score weights. The default 0.5/0.3/0.2 split prioritizes relevance heavily; if your domain has highly redundant retrieval results, increase the Uniqueness weight to 0.4 and drop Relevance to 0.4. If source credibility is paramount—for example, in regulatory or clinical contexts—push Authority to 0.3 or higher. The relevance floor of 0.3 is a safety threshold; lower it for exploratory search use cases and raise it for high-stakes Q&A where wrong answers are costly. Always validate the output JSON against the schema before passing selected passages to your answer generation step. For production, wrap this prompt in a retry harness that catches malformed JSON, missing required fields, or empty selections when the query clearly has relevant results available.
Prompt Variables
Required and optional inputs for the Context Prioritization Prompt. Each variable must be validated before the prompt is assembled to prevent runtime failures or silent context corruption.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The user question or search intent that drives relevance ranking | What are the side effects of drug X in elderly patients? | Must be non-empty string. Check length > 0. Reject if only whitespace or stopwords. |
[RETRIEVED_PASSAGES] | Array of passage objects from dense retrieval, each with id, text, and optional metadata | [{"id":"doc_12_chunk_3","text":"...","score":0.87,"source":"FDA_label_2024.pdf"}] | Must be valid JSON array. Minimum 2 passages. Each object requires id and text fields. Reject if text field is empty or null. |
[TOP_K] | Number of passages to retain after prioritization | 5 | Must be positive integer between 1 and [RETRIEVED_PASSAGES] length. Clamp to available passage count if exceeded. Warn if TOP_K * avg_passage_tokens exceeds model context window. |
[MAX_TOKENS] | Token budget ceiling for the final selected context set | 4000 | Must be positive integer. Must be less than model context limit minus prompt overhead. Validate against tokenizer count, not character count. Reject if budget cannot fit at least 2 passages. |
[PRIORITY_WEIGHTS] | Optional object defining relative importance of relevance, uniqueness, and authority in ranking | {"relevance":0.5,"uniqueness":0.3,"authority":0.2} | If provided, values must sum to 1.0 within 0.01 tolerance. All keys must be recognized dimensions. If null or omitted, use default equal weighting. Validate float parse. |
[SOURCE_AUTHORITY_MAP] | Optional mapping of source identifiers to authority scores for ranking | {"FDA_label_2024.pdf":0.95,"user_forum_post.txt":0.2} | If provided, must be valid JSON object. Authority scores must be floats in [0.0, 1.0]. Unknown sources default to 0.5 with logged warning. Null allowed if authority weighting disabled. |
[OUTPUT_SCHEMA] | Expected structure for the ranked and selected passage output | {"selected_passages":[],"selection_rationale":[],"coverage_score":0.0,"excluded_passages":[]} | Must be valid JSON schema definition. Reject if missing required fields: selected_passages, selection_rationale. Validate that schema types match expected output types (array, string, number). |
[DEDUP_THRESHOLD] | Semantic similarity threshold above which passages are considered redundant | 0.85 | Must be float in [0.0, 1.0]. Values below 0.5 risk over-retention. Values above 0.95 risk over-filtering. Log warning if outside 0.7-0.9 range. Null allowed to disable deduplication pass. |
Implementation Harness Notes
How to wire the context prioritization prompt into a production RAG pipeline with validation, retries, and observability.
The context prioritization prompt is designed to sit between retrieval and answer generation in a RAG pipeline. It consumes a list of retrieved passages and a user query, then produces a ranked, filtered set of passages that fit within a specified token budget. In production, this prompt should be called as a dedicated preprocessing step—not bundled into the final answer-generation call—so that its output can be validated, logged, and inspected before downstream consumption. The typical call pattern is: retrieve N passages from your vector or hybrid search index, pass them through this prompt with a token budget derived from your model's context window minus space reserved for the system prompt, user query, and answer-generation instructions, then forward only the selected passages to the answer-generation model.
Validation and retry logic is critical because the prompt's output schema includes a ranked list with selection rationale. Implement a post-processing validator that checks: (1) the output is valid JSON matching the expected schema, (2) the total token count of selected passages does not exceed the specified budget, (3) every selected passage exists in the input set, and (4) the ranking is monotonic (no duplicate ranks). On validation failure, retry once with the same input and an explicit error message appended to the prompt instructing the model to correct the specific violation. If the second attempt also fails, fall back to a simpler truncation strategy (e.g., take the top-k passages by retrieval score) and log the failure for investigation. For high-stakes domains, route validation failures to a human review queue rather than silently degrading.
Model choice matters for this prompt. It requires strong instruction-following and structured output capabilities. Use a model that reliably produces valid JSON with complex schemas—GPT-4o, Claude 3.5 Sonnet, or equivalent. Avoid smaller or older models that may drop fields, hallucinate passage content, or ignore the token budget constraint. If latency is a concern, consider running this prompt on a fast, mid-tier model and validating aggressively, with a slower, more capable model as the retry fallback. Logging should capture: the input passage count, the token budget, the number of passages selected, the rationale strings, and the validation result. This data feeds directly into eval pipelines that measure whether prioritization improves downstream answer quality or reduces hallucination rates.
Tool use and RAG integration: This prompt does not call external tools itself, but it should be wired into a pipeline where retrieval scores, source metadata, and passage timestamps are available as input fields. If your retrieval system already provides relevance scores, include them in each passage object so the model can use them as a ranking signal. For compliance-sensitive deployments, preserve source provenance through the prioritization step—the output must retain document IDs or URLs so that downstream answer-generation prompts can cite original sources even after passages are filtered or merged. Wire the prioritization output directly into your answer-generation prompt's [CONTEXT] placeholder, and ensure your observability stack traces which passages were selected for each user query so you can debug answer quality regressions to specific prioritization decisions.
What to avoid: Do not set the token budget to the full context window—reserve at least 20-30% for the system prompt, user query, and answer-generation instructions. Do not skip validation in production; malformed prioritization output will silently corrupt downstream answers. Do not use this prompt for real-time streaming applications without measuring the added latency; the prioritization step adds one full model round-trip before answer generation begins. If latency is unacceptable, consider caching prioritization results for repeated queries or using a lightweight embedding-based reranker as a faster alternative, reserving this prompt for offline batch processing or high-value queries where accuracy justifies the cost.
Common Failure Modes
Context prioritization prompts fail in predictable ways when ranking and selecting passages from dense retrieval results. These are the most common failure modes and how to guard against them.
Relevance Over Novelty Collapse
What to watch: The prompt ranks passages purely by semantic similarity to the query, selecting top-k results that all say the same thing in slightly different words. The final context set has high relevance but zero information diversity, missing critical facts that appear in lower-ranked but unique passages. Guardrail: Include explicit novelty criteria in the ranking instructions. Require the model to compare each candidate against already-selected passages and penalize redundant information. Add a diversity check in post-processing that flags context sets where more than two passages cover the same fact.
Token Budget Blind Selection
What to watch: The prompt selects passages until the token budget is exhausted, but the last selected passage gets truncated mid-sentence or the model ignores the budget constraint entirely and returns an oversized context set. This breaks downstream answer generation when critical evidence is cut off. Guardrail: Require the model to output per-passage token counts and a running total. Add a hard post-processing truncation step that enforces the budget at the application layer, not just in the prompt. Validate the final context length before passing it to the answer generator.
Authority Blindness
What to watch: The prompt treats all retrieved passages as equally credible, ranking a speculative forum post above a verified documentation page because the forum post has higher lexical overlap with the query. The selected context set includes low-authority sources that produce misleading answers. Guardrail: Include source authority signals in the passage metadata (document type, recency, authoritativeness score) and require the model to weight these alongside relevance. Add an authority floor—passages below a threshold are excluded regardless of relevance score.
Selection Rationale Hallucination
What to watch: The prompt asks for selection rationale alongside ranked passages, and the model fabricates plausible-sounding but incorrect justifications for why a passage was chosen. The rationale looks convincing in logs but doesn't reflect actual selection logic, making debugging impossible. Guardrail: Constrain rationale to specific, verifiable criteria (e.g., "Passage contains entity X mentioned in query" rather than open-ended explanation). Cross-check rationale claims against passage content in post-processing. If rationale accuracy matters for audit, use a separate verification step rather than trusting inline justifications.
Query-Context Mismatch Drift
What to watch: The prompt prioritizes passages that match surface-level query terms but miss the underlying intent. For example, a query about "Python memory management" gets passages about Python snake husbandry because the retrieval returned them and the prioritization prompt didn't detect the semantic mismatch. Guardrail: Include an explicit intent-matching step before relevance ranking. Require the model to classify whether each passage addresses the same domain and intent as the query. Filter out domain-mismatched passages before ranking begins. Log mismatch decisions for retrieval quality monitoring.
Coverage Gap Blindness
What to watch: The prompt successfully selects a diverse, relevant context set but fails to detect that the selected passages collectively don't cover all aspects of a complex query. The answer generator then produces a confident but incomplete response because critical sub-questions have no supporting evidence. Guardrail: Decompose the query into sub-questions before prioritization. Require the model to map selected passages to specific sub-questions and flag any sub-question with zero supporting passages. Return a coverage report alongside the ranked context so the answer generator knows where evidence is missing.
Evaluation Rubric
Criteria for testing the Context Prioritization Prompt before shipping. Each row defines a pass standard, a failure signal to watch for, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Ranking Relevance | Top-ranked passage is the most semantically relevant to [QUERY] in 9/10 test cases | Top-ranked passage is off-topic or a distractor | Human-labeled relevance ranking on 50 retrieval sets; compare prompt output rank to ground-truth rank using NDCG@1 |
Uniqueness Coverage | Selected top-k set contains at least 80% of unique information nuggets from the full retrieval set | Multiple selected passages repeat the same fact; novel information from lower-ranked passages is excluded | Extract all unique claims from full set and selected set; compute claim recall |
Token Budget Compliance | Output context assembly is within 5% of [MAX_TOKENS] without truncating mid-sentence | Output exceeds budget by more than 5% or cuts off critical evidence mid-word | Automated token count check on 100 varied retrieval sets; flag any violation |
Selection Rationale Quality | Each selection reason references a specific passage attribute (relevance, novelty, authority) and not a generic statement | Rationale is vague (e.g., 'this is good') or hallucinates a passage attribute not present in the text | LLM-as-judge evaluation: binary pass/fail on rationale specificity and grounding to passage content |
Authority Handling | When [AUTHORITY_SIGNALS] are provided, passages from preferred sources are ranked higher than equally relevant passages from lower-authority sources | Authority signals are ignored; low-authority passage outranks high-authority passage with identical relevance | Paired comparison test: provide two equally relevant passages with different authority levels; verify correct ordering |
Output Schema Validity | Output is valid JSON matching [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing | Schema validation with jsonschema or pydantic; run on 100 outputs and require 100% pass rate |
Edge Case: Empty Retrieval Set | Prompt returns an empty ranked list with a clear abstention message when [RETRIEVED_PASSAGES] is empty | Prompt hallucinates passages or returns a non-empty list with fabricated content | Unit test with empty passage array; assert output list length is 0 and abstention field is true |
Edge Case: Single Passage | Prompt returns the single passage ranked 1 with rationale noting only one passage available | Prompt errors out, returns empty, or fabricates additional passages to rank | Unit test with single-passage input; assert output has exactly one ranked entry with valid rationale |
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 prompt and a small retrieval set (10–20 passages). Remove the strict output schema and use a simpler instruction: "Rank these passages by relevance and uniqueness. Return the top 5 with a one-line reason each." Test with 3–5 query types before adding complexity.
Watch for
- Rankings that look plausible but lack consistency across similar queries
- The model ignoring the uniqueness criterion and ranking only by relevance
- Token budget overruns when the prompt doesn't enforce a hard limit

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