Inferensys

Prompt

Passage Ranking Prompt for RAG Retrieval Sets

A practical prompt playbook for using Passage Ranking Prompt for RAG Retrieval Sets 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

A guide to deploying the Passage Ranking Prompt in production RAG pipelines, including ideal use cases, prerequisites, and critical anti-patterns to avoid.

This prompt is designed for search and retrieval engineers who need to transform a noisy set of retrieved passages into a clean, ranked list before answer synthesis. It sits between retrieval and generation in a RAG pipeline. Use it when your vector or keyword search returns multiple chunks with overlapping content, varying credibility, and uneven information density. The prompt forces the model to rank passages by relevance to the user query, source credibility, and factual density while handling ties, near-duplicates, and context window constraints.

The ideal user is an AI engineer or backend developer who already has a working retrieval step but observes that the top-k results are not optimally ordered for downstream synthesis. You should have access to passage text, source metadata (title, date, author), and the original user query. The prompt works best when you can provide at least 5–20 candidate passages and need to select a smaller subset for a constrained context window. It is particularly valuable when your retrieval mix includes sources of uneven authority—such as internal documentation, user forums, and vendor docs—where credibility weighting matters as much as semantic similarity.

Do not use this prompt when you have a single retrieved passage, when retrieval already returns perfectly ordered results, or when downstream latency budgets cannot absorb an additional model call. It is also the wrong tool if your passages are already homogeneous in credibility and density, or if you need real-time ranking over thousands of candidates—this prompt is designed for re-ranking a manageable candidate set, not for full-scale retrieval. If your primary need is deduplication without relevance ordering, use the Multi-Passage Deduplication and Selection Prompt instead. If you need to decide whether the evidence is sufficient to answer at all, pair this prompt with the Evidence Sufficiency Check Prompt before proceeding to synthesis.

Before deploying, ensure you have a validation layer that checks the output schema—ranked passage IDs, scores, and exclusion reasons—and a retry path for malformed responses. For high-stakes domains like healthcare or legal, always log the ranking decisions for auditability and consider human review of the ranked set before it feeds into answer generation. Start by testing this prompt against a golden dataset of query-passage pairs with known relevance judgments to calibrate whether the model's ranking aligns with your domain-specific definition of 'best evidence.'

PRACTICAL GUARDRAILS

Use Case Fit

Where the Passage Ranking 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.

01

Good Fit: High-Volume Retrieval Pipelines

Use when: your RAG system retrieves 20–100+ passages per query and needs a reliable re-ranking step before synthesis. The prompt excels at reducing noise and prioritizing information-dense passages. Guardrail: Pair with a token budget constraint to prevent context window overflow when ranking large sets.

02

Bad Fit: Real-Time Sub-100ms Latency Requirements

Avoid when: your application requires sub-100ms response times and cannot tolerate an LLM call for re-ranking. Cross-encoder or bi-encoder models are faster alternatives. Guardrail: Use this prompt for offline indexing or async re-ranking pipelines where latency budgets exceed 500ms.

03

Required Input: Pre-Retrieved Candidate Set

Risk: Feeding raw, unretrieved documents directly into the ranking prompt produces arbitrary ordering without retrieval grounding. Guardrail: Always provide a candidate set from a retrieval step (vector, keyword, or hybrid). The prompt ranks existing candidates—it does not retrieve them.

04

Required Input: Explicit Ranking Criteria

Risk: Without defined criteria, the model defaults to superficial keyword matching rather than true relevance ranking. Guardrail: Specify ranking dimensions—relevance, credibility, information density, recency—in the prompt's [RANKING_CRITERIA] placeholder. Test criterion weight sensitivity across query types.

05

Operational Risk: Near-Duplicate Blind Spots

Risk: The prompt may rank near-duplicate passages similarly, wasting context window budget on redundant information. Guardrail: Run a deduplication step before ranking, or include explicit deduplication instructions in the prompt with semantic similarity thresholds.

06

Operational Risk: Ranking Drift Across Model Versions

Risk: Model upgrades can shift ranking behavior silently, breaking downstream answer quality without obvious errors. Guardrail: Maintain a golden ranking dataset and run regression tests comparing rank correlation (e.g., Kendall's tau) across prompt and model version changes before deployment.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for ranking retrieved passages by relevance, credibility, and information density before answer synthesis.

This prompt template is designed to be pasted directly into your system or user message for a passage ranking step in a RAG pipeline. It takes a user query and a set of retrieved passages as input, and it produces an ordered list of passages ranked by relevance, credibility, and information density. The output is structured JSON, making it suitable for direct consumption by a downstream synthesis prompt or for logging and evaluation. The square-bracket placeholders must be replaced with your specific query, passages, and constraints before execution.

text
You are a precise evidence ranking engine for a retrieval-augmented generation (RAG) system. Your only job is to rank the provided passages by their relevance, credibility, and information density for answering the user's query. Do not answer the query. Do not synthesize information. Only rank and explain.

## User Query
[USER_QUERY]

## Retrieved Passages
[RETRIEVED_PASSAGES]

## Ranking Criteria
1. **Relevance**: How directly does the passage address the core intent and entities of the user query?
2. **Credibility**: Consider the source authority, publication date, and factual consistency. A passage from a dated or unknown source should be ranked lower.
3. **Information Density**: Prioritize passages with high factual content and low redundancy. A short, fact-packed passage should outrank a long, verbose one.

## Constraints
- [CONSTRAINTS]
- If a passage is a near-duplicate of a higher-ranked passage, exclude it and note the reason.
- If no passage is sufficiently relevant, return an empty list.
- You must operate within a total output token budget of [MAX_OUTPUT_TOKENS].

## Output Schema
Return a valid JSON object with the following structure. Do not include any text outside the JSON object.
{
  "ranked_passages": [
    {
      "passage_id": "string",
      "rank": integer,
      "relevance_score": float (0.0 to 1.0),
      "credibility_score": float (0.0 to 1.0),
      "information_density_score": float (0.0 to 1.0),
      "composite_score": float (0.0 to 1.0),
      "justification": "A concise, evidence-based reason for this ranking.",
      "exclusion_reason": null
    }
  ],
  "excluded_passages": [
    {
      "passage_id": "string",
      "exclusion_reason": "One of: 'near_duplicate', 'below_relevance_threshold', 'token_budget_exceeded'"
    }
  ]
}

## Examples
[FEW_SHOT_EXAMPLES]

To adapt this template, start by replacing [USER_QUERY] with the exact user question and [RETRIEVED_PASSAGES] with a structured list of your retrieval results, ensuring each passage has a unique passage_id. The [CONSTRAINTS] placeholder is critical for enforcing domain-specific rules, such as 'Prefer peer-reviewed sources from the last 5 years' or 'Exclude passages from competitor domains.' Use the [FEW_SHOT_EXAMPLES] placeholder to provide 1-3 examples of ideal input-output pairs, which dramatically improves ranking consistency and score calibration. For high-stakes applications, the composite_score should be used as a threshold to filter passages before they reach the answer synthesis step, and all outputs should be logged for offline evaluation of ranking quality.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Validate these before sending the prompt to the model.

PlaceholderPurposeExampleValidation Notes

[QUERY]

The user question or search intent to rank passages against

What are the side effects of drug X?

Required. Must be non-empty string. Check for minimum length > 3 characters. Reject if only stop words or punctuation.

[PASSAGES]

Array of retrieved passages with metadata to rank

[{"id": "doc-1", "text": "...", "source": "...", "date": "..."}]

Required. Must be valid JSON array with 2-50 objects. Each object must have id and text fields. Reject if empty or exceeds context window budget.

[RANKING_CRITERIA]

Ordered list of factors to weight when ranking passages

["relevance", "credibility", "recency", "information_density"]

Required. Must be non-empty array of strings from allowed enum: relevance, credibility, recency, information_density, source_authority, complementarity. Validate against allowed values.

[TOP_K]

Number of top passages to return in final ranking

5

Required. Must be positive integer between 1 and [PASSAGES] length. Default to 5 if null. Clamp to available passage count if exceeds.

[CONTEXT_WINDOW_BUDGET]

Maximum token budget for selected passages

4000

Optional. Must be positive integer if provided. If set, enforce that selected passages total tokens do not exceed budget. Use tokenizer estimate before sending.

[OUTPUT_SCHEMA]

JSON schema defining the expected output structure

{"type": "object", "properties": {"ranked_passages": [...]}}

Required. Must be valid JSON Schema. Validate parse before prompt assembly. Include required fields: rank, passage_id, score, justification.

[TIE_BREAKING_RULE]

Rule for resolving passages with equal scores

"prefer_higher_source_authority"

Optional. Must be one of: prefer_higher_source_authority, prefer_more_recent, prefer_shorter, prefer_longer, maintain_original_order. Default to maintain_original_order if null.

[DUPLICATE_THRESHOLD]

Similarity threshold for flagging near-duplicate passages

0.85

Optional. Float between 0.0 and 1.0. If provided, prompt should flag passages above this similarity as potential duplicates. Validate range before sending.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the passage ranking prompt into a production RAG pipeline with validation, retries, and observability.

The passage ranking prompt is not a standalone artifact—it is a component inside a retrieval pipeline. Wire it after your initial retrieval step (vector, keyword, or hybrid) returns a candidate set of passages. The prompt receives the user query and the raw candidate passages, then returns a ranked, scored, and deduplicated list. Your application should treat this prompt as a re-ranking and filtering stage before answer synthesis. Do not send every retrieved chunk to the ranking prompt; pre-filter to a reasonable candidate count (20–50 passages) to stay within context window limits and control latency. If your initial retrieval returns hundreds of passages, apply a lightweight first-pass filter (BM25 score threshold, metadata filter, or embedding similarity cutoff) before invoking this prompt.

Integration pattern: Call the ranking prompt as a synchronous step between retrieval and synthesis. The output JSON should be validated against a strict schema before downstream use. Expect fields: ranked_passages (ordered list with passage_id, rank, relevance_score, credibility_score, information_density_score, justification), excluded_passages (with passage_id and exclusion_reason), and tie_groups (groups of passages with statistically indistinguishable scores). Validate that every passage_id in the input appears exactly once across ranked_passages and excluded_passages. If validation fails, retry once with the same input and a stronger instruction to produce complete output. If the second attempt fails, log the failure, fall back to a simpler ranking heuristic (e.g., cosine similarity sort), and alert the operations channel. Never pass unvalidated ranking output to the synthesis step.

Model choice and latency: Use a model with strong instruction-following and JSON output capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). For high-throughput pipelines, consider a smaller fine-tuned model if you have ranking-labeled data. Set response_format to json_object or equivalent structured output mode. Implement a timeout of 5–10 seconds; if the model does not return within the window, fall back to the heuristic ranking and log the timeout for capacity planning. Human review placement: For high-stakes domains (healthcare, legal, finance), insert a human review step when the ranking prompt flags unresolved ties in critical passages, when credibility scores fall below a configured threshold, or when the prompt's confidence calibration score drops below 0.7. Route these cases to a review queue rather than proceeding automatically to synthesis. Observability: Log the full prompt input, output, validation result, retry count, and fallback decision to your tracing system. This trace data is essential for debugging ranking regressions, calibrating confidence thresholds, and comparing prompt versions over time.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, data types, and validation rules for the JSON output. Use this contract to validate the model response before passing ranked passages to downstream synthesis.

Field or ElementType or FormatRequiredValidation Rule

ranked_passages

Array of objects

Array length must be between 1 and [TOP_K]. Each element must match the passage object schema.

ranked_passages[].passage_id

String

Must match a passage_id from the [INPUT_PASSAGES] array. No fabricated IDs allowed.

ranked_passages[].rank

Integer

Must be a unique integer from 1 to N. No ties, no gaps, no zero-based indexing.

ranked_passages[].relevance_score

Number (float)

Must be between 0.0 and 1.0 inclusive. Scores must be monotonically non-increasing with rank.

ranked_passages[].relevance_justification

String

Must be 1-3 sentences. Must reference specific content from the passage text. No generic justifications.

ranked_passages[].credibility_score

Number (float) or null

If present, must be between 0.0 and 1.0. Use null when source metadata is insufficient for credibility assessment.

ranked_passages[].information_density

String enum

Must be one of: high, medium, low. Assess factual content per token, not passage length.

excluded_passages

Array of objects

Array length must equal (total input passages - ranked passages). May be empty if all passages are ranked.

excluded_passages[].passage_id

String

Must match a passage_id from [INPUT_PASSAGES] that does not appear in ranked_passages.

excluded_passages[].exclusion_reason

String enum

Must be one of: irrelevant, duplicate, low_credibility, insufficient_content, contradictory_unresolvable, token_budget_exceeded.

processing_metadata

Object

Must contain fields: total_input_passages (integer), total_ranked (integer), total_excluded (integer), tie_resolution_applied (boolean).

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when ranking passages for RAG retrieval sets and how to guard against it.

01

Position Bias Toward Top Results

What to watch: The model over-ranks passages simply because they appear first in the input list, ignoring genuinely more relevant passages later in the sequence. This is especially common with long retrieval sets where attention dilutes. Guardrail: Randomize passage order before prompting, run multiple ranking passes with shuffled inputs, and use pairwise comparison prompts for tie-breaking rather than relying on list position.

02

Keyword Overlap Masquerading as Relevance

What to watch: The model assigns high scores to passages that share many words with the query but lack substantive answer content, while fact-dense passages with different vocabulary get ranked lower. This produces fluent but empty RAG answers. Guardrail: Include explicit instruction to distinguish lexical overlap from semantic relevance, add a fact-density scoring dimension, and validate rankings against human relevance judgments that penalize keyword-match-only passages.

03

Near-Duplicate Passage Clusters Consuming Rank Budget

What to watch: Multiple passages containing essentially the same information occupy top-k slots, crowding out complementary evidence and reducing answer completeness. This is common with chunked documents where adjacent chunks overlap heavily. Guardrail: Implement a deduplication pass before ranking, use information-gain scoring to penalize redundant passages, and enforce a minimum semantic distance threshold between selected passages.

04

Confidence Scores That Don't Calibrate to Actual Relevance

What to watch: The model produces confidence scores (e.g., 0.92) that look precise but don't correlate with whether the passage actually contains the answer. High-confidence irrelevant passages are more dangerous than low-confidence ones because they bypass downstream filters. Guardrail: Calibrate scores against a held-out relevance dataset, add uncertainty language when scores are uncalibrated, and implement a secondary verification prompt that checks whether the top-ranked passage actually answers the query before synthesis.

05

Context Window Overflow Silently Dropping Passages

What to watch: When the combined length of retrieved passages exceeds the model's context window, the prompt silently truncates, dropping later passages without warning. The model ranks only what it can see, producing incomplete rankings with no error signal. Guardrail: Pre-calculate token counts for all passages, enforce a hard budget with explicit overflow handling, and add a completeness check that verifies the expected number of passages appear in the output. Log truncation events as warnings.

06

Source Authority Override of Content Relevance

What to watch: The model over-weights source credibility signals (e.g., official documentation, high-authority domains) and ranks authoritative-but-irrelevant passages above less-credible-but-directly-relevant ones. This produces answers that sound trustworthy but miss the user's actual question. Guardrail: Separate credibility scoring from relevance scoring, apply credibility as a secondary sort within relevance tiers rather than a primary rank signal, and test with queries where the correct answer comes from lower-authority sources.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks on a golden dataset of 50-100 query-passage sets with human-annotated relevance judgments. Each criterion targets a specific failure mode in passage ranking before the prompt is integrated into a production RAG pipeline.

CriterionPass StandardFailure SignalTest Method

Relevance Ordering

Top-3 passages match human-annotated top-3 in at least 85% of queries

Human-preferred passages consistently appear below rank 5 or are excluded

Compare prompt-ranked top-3 against human-annotated top-3 using NDCG@3

Score Calibration

Mean relevance score for human-labeled relevant passages exceeds 0.7; mean for irrelevant passages below 0.3

Score distributions for relevant and irrelevant passages overlap by more than 20%

Compute mean and variance of scores per relevance class; check separation with Kolmogorov-Smirnov distance

Deduplication Effectiveness

No pair of selected passages has cosine similarity above 0.85 in the output set

Near-duplicate passages appear in the top-K output with similar scores

Compute pairwise cosine similarity on passage embeddings; flag any pair above threshold

Source Diversity

At least 2 distinct source documents appear in the top-5 passages when the golden set contains multiple relevant sources

All top-5 passages originate from a single document despite multiple relevant sources in the retrieval set

Count unique source identifiers in top-5; compare against golden-set source diversity expectation

Exclusion Justification

Every excluded passage with human relevance label has a non-empty exclusion reason in the output

Relevant passages are excluded with null or empty justification fields

Parse exclusion reasons from structured output; cross-reference against human relevance labels for false exclusions

Token Budget Adherence

Total token count of selected passages does not exceed [MAX_TOKENS] by more than 5%

Output exceeds token budget by more than 10% or truncates mid-passage without flagging overflow

Count tokens in selected passage set using the target model's tokenizer; verify against [MAX_TOKENS]

Confidence-Weighted Tiebreaking

When two passages have identical relevance scores, the one with higher credibility metadata ranks first

Tied passages appear in arbitrary or non-deterministic order across repeated runs

Inject synthetic tie cases into the golden set; verify deterministic ordering by credibility field

Hallucinated Passage Content

No selected passage contains claims not present in the original retrieved text

Output passages include fabricated details, merged content from multiple sources, or paraphrased additions

Diff each output passage against its source text; flag any sentence with no substring match in the original

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base ranking prompt and a small set of 5-10 passages. Use a simple relevance-only instruction without credibility or density weighting. Accept raw text output and manually inspect rankings.

code
Rank the following passages by relevance to the query: [QUERY]

Passages:
[PASSAGE_LIST]

Return an ordered list from most to least relevant.

Watch for

  • Rankings that look plausible but lack justification
  • Model ignoring implicit query intent (e.g., treating 'how to fix' as 'what is')
  • No handling of ties or near-duplicates
  • Over-ranking longer passages simply because they contain more words
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.