This prompt is designed for the specific job of fine-grained passage ordering when your vector or keyword retrieval system has returned a candidate set that is too large or too coarsely scored for direct context assembly. The ideal user is a search engineer or RAG pipeline architect who needs to transform a set of, for example, 20-50 retrieved passages into a strictly relevance-ordered list of the top 5-10, complete with explicit justifications for each ranking decision. The required context is a well-defined user query and a set of candidate passages, each with a unique identifier. The core value is not just the final order, but the pairwise reasoning trace, which is invaluable for debugging retrieval failures and calibrating upstream embedding models.
Prompt
Cross-Encoder Reranking Prompt Template

When to Use This Prompt
A practical guide for search engineers and RAG pipeline architects on when to deploy a cross-encoder reranking prompt and when to choose a simpler alternative.
You should use this template when the cost of including irrelevant or suboptimal context in your generation step is high—for instance, in a legal research tool where a missed precedent is a critical failure, or in a technical support copilot where the correct code snippet must be found among many similar-looking results. The pairwise comparison structure forces the model to make relative judgments ('Passage A is more relevant than Passage B because...'), which is a closer match to the cross-encoder architecture than pointwise scoring. The output is explicitly designed to be consumed by a downstream context window budget allocator or to provide a ranked list for an answer generation step. However, you must not use this prompt when your task is a simple binary filter (relevant/irrelevant), as the pairwise overhead is wasteful. Similarly, avoid it when your latency budget is under a few hundred milliseconds, as the O(n²) comparison depth makes it unsuitable for real-time search over large sets.
Before implementing, verify that your passage count and length fit within a single model call with adequate comparison depth. If you have 100 passages, a full pairwise comparison is impractical; you should instead use a pointwise scoring prompt or a multi-stage filtering pipeline first. The next step after reading this section is to examine the prompt template itself, paying close attention to the [PASSAGES] and [QUERY] placeholders, and then review the implementation harness to understand how to validate the output schema and integrate it into a production RAG pipeline.
Use Case Fit
Where the Cross-Encoder Reranking Prompt Template delivers value and where it introduces risk. Use these cards to decide if this prompt fits your pipeline stage, latency budget, and quality requirements.
Good Fit: Precision Reranking
Use when: you have a candidate set of 20-50 passages from a fast first-stage retriever and need to reorder them by deep semantic relevance. Guardrail: limit the candidate set size; cross-encoder style comparison is quadratic in cost and latency.
Bad Fit: Real-Time Retrieval
Avoid when: latency must stay under 200ms or you are ranking thousands of documents. Guardrail: use a bi-encoder or vector similarity for first-pass retrieval, then apply this prompt only to the top-k candidates.
Required Inputs
What you need: a query string, a list of candidate passages with IDs, and a defined output schema for ranked results. Guardrail: validate that passage IDs are unique and stable before calling the prompt; duplicate IDs break pairwise comparison logic.
Operational Risk: Cost Amplification
Risk: running cross-encoder reranking on every query in a high-volume system multiplies token consumption. Guardrail: cache first-stage retrieval results, apply reranking only when the top-k similarity scores are close, and set a hard token budget per rerank call.
Operational Risk: Ranking Instability
Risk: small changes to candidate order or passage wording can flip rankings, causing inconsistent user experiences. Guardrail: log ranking decisions with pairwise justifications, monitor rank correlation metrics across model versions, and pin regression tests for known query-passage pairs.
When to Skip Reranking
Avoid when: the first-stage retriever already returns highly relevant results with clear score separation, or when the user query is a simple keyword match. Guardrail: implement a relevance score threshold check before invoking reranking to avoid unnecessary cost.
Copy-Ready Prompt Template
A reusable prompt template that instructs an LLM to perform pairwise comparisons on a set of passages and produce a fully ordered relevance ranking with justifications.
The following prompt template is designed to replicate the behavior of a cross-encoder reranker using a general-purpose LLM. Instead of outputting a single relevance score, the model is instructed to compare every passage against every other passage, building a ranked list from the ground up. This pairwise comparison method is more compute-intensive but often yields more accurate and explainable rankings than pointwise scoring, especially when the differences between top passages are subtle. The template is self-contained and can be copied directly into a notebook or application harness. All dynamic inputs are represented as square-bracket placeholders.
textYou are a precise relevance ranking engine. Your task is to rank a set of passages by their relevance to a given query using pairwise comparison. ## QUERY [QUERY] ## PASSAGES TO RANK [PASSAGES] ## INSTRUCTIONS 1. Compare every passage to every other passage in a pairwise fashion. 2. For each pair, determine which passage is more relevant to the query. Base your decision on: - Direct topical alignment with the query's core intent. - Specificity of the information provided. - Factual density and absence of fluff. 3. After all comparisons, produce a fully ordered list from most relevant (rank 1) to least relevant. 4. For each passage in the final ranking, provide a concise justification explaining its position relative to the passages ranked immediately above and below it. ## OUTPUT FORMAT Return a single JSON object with the following structure: { "ranked_passages": [ { "rank": 1, "passage_id": "[ID_FROM_INPUT]", "justification": "Why this passage is ranked here." }, ... ] } ## CONSTRAINTS - Do not skip any passage. Every input passage must appear in the output. - Do not assign ties. Every rank must be unique. - Base your ranking strictly on the provided text, not on external world knowledge.
To adapt this template, replace [QUERY] with the user's search string or natural language question. The [PASSAGES] placeholder should be replaced with a pre-formatted list of candidate passages, each assigned a unique identifier. A robust format for this input is a JSON array of objects, each with an id and text field. When integrating this into a RAG pipeline, this prompt should be placed after a fast, high-recall retrieval step (like vector search) and before the final context assembly for answer generation. For production use, always validate the output JSON against the expected schema and implement a retry mechanism with a stricter format reminder if the model deviates.
Prompt Variables
Required inputs for the Cross-Encoder Reranking Prompt Template. Each placeholder must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of ranking failures in production.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The user question or search intent that passages are being ranked against | What are the side effects of atorvastatin? | Must be non-empty string. Check for length > 0. Reject if only whitespace or stopwords. |
[PASSAGES] | Array of retrieved passages to rerank, each with a unique identifier and text content | [{"id":"p1","text":"Atorvastatin may cause muscle pain..."},{"id":"p2","text":"Common side effects include headache..."}] | Must be valid JSON array with 2-50 objects. Each object requires non-empty id and text fields. Reject if array is empty or contains duplicate ids. |
[TOP_K] | Number of top-ranked passages to return in the final ordered list | 5 | Must be positive integer between 1 and length of [PASSAGES]. Default to 5 if not specified. Reject if greater than passage count. |
[RANKING_CRITERIA] | Ordered list of criteria for judging passage relevance: semantic match, specificity, authority, freshness | ["semantic_relevance","specificity","source_authority"] | Must be valid JSON array of strings from allowed enum: semantic_relevance, specificity, source_authority, temporal_freshness, factual_accuracy. Reject if empty or contains unknown criteria. |
[OUTPUT_SCHEMA] | Expected JSON structure for the reranked output including justifications | {"ranked_passages":[{"id":"string","rank":"integer","score":"float","justification":"string"}]} | Must be valid JSON Schema or example structure. Validate that schema includes id, rank, score, and justification fields. Reject if schema is missing required fields. |
[PAIRWISE_COMPARISONS] | Boolean flag controlling whether the model outputs pairwise comparison reasoning between adjacent passages | Must be boolean true or false. Default to false if not specified. When true, output contract must include comparison_notes array. | |
[CONFIDENCE_THRESHOLD] | Minimum relevance score below which passages should be flagged as low-confidence and potentially excluded | 0.3 | Must be float between 0.0 and 1.0. Default to 0.0 if not specified. Scores below threshold trigger low_confidence flag in output. |
Implementation Harness Notes
How to wire the cross-encoder reranking prompt into a production retrieval pipeline with validation, retries, and quality monitoring.
The cross-encoder reranking prompt template is designed to sit between your initial retrieval stage and your answer generation stage. In a typical RAG pipeline, you first retrieve a candidate set of passages—often 20 to 100 results from a vector or hybrid search—and then use this prompt to produce a relevance-ordered list with pairwise comparison justifications. The prompt expects a [QUERY] and a [PASSAGES] list as input, and it returns a ranked output with scores and reasoning. Wire this into your application as a synchronous post-retrieval step: after retrieval but before context assembly for the generator. The model choice matters here—use a model with strong instruction-following and reasoning capabilities (such as GPT-4, Claude 3.5 Sonnet, or a fine-tuned Llama 3 variant) because pairwise comparison requires careful attention to semantic nuance. Lighter models often produce inconsistent rankings or skip justifications under load.
Validation is the most critical part of the harness. Before passing the reranked output downstream, validate that every passage in the output exists in the input set (no hallucinated passages), that the ranking is complete (all input passages appear in the output unless explicitly excluded with a reason), and that each justification references specific content from both the query and the passage. Implement a structural validator that checks the output schema—expect a JSON array of objects with passage_id, rank, relevance_score, and justification fields. If validation fails, retry once with the same prompt and add a [CONSTRAINTS] note emphasizing the validation error. After two failures, log the raw output, fall back to the original retrieval order, and flag the query for offline review. For high-stakes domains like legal or medical search, route validation failures to a human review queue rather than silently degrading.
Logging and observability are essential for production. Capture the query, the input passage count, the output ranking, per-passage scores, and the latency of the reranking call. Track reranking-specific metrics: ranking inversion rate (how often the reranker disagrees with the original retrieval order), justification quality flags (empty or generic justifications), and truncation events (when the prompt exceeds the context window and passages are dropped). If you're using this prompt in a system with user-facing citations, verify that the top-ranked passages after reranking actually contain the information needed to answer the query—this is your grounding check. Build an eval harness that compares reranked orderings against human-judged relevance labels on a golden dataset of query-passage pairs, and monitor nDCG or precision@k drift across prompt versions. When you update the prompt template, run this eval suite before deployment and set a minimum nDCG threshold as a release gate. Finally, consider cost: cross-encoder reranking with an LLM is more expensive per query than embedding-based reranking, so apply this prompt only to the top-N candidates (typically 20–30) rather than the full retrieval set, and cache reranking results for repeated queries where the passage set hasn't changed.
Expected Output Contract
Defines the required fields, types, and validation rules for the Cross-Encoder Reranking output. Use this contract to parse and validate the LLM response before passing ranked passages to downstream generation.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
ranked_passages | Array of objects | Must be a non-empty JSON array. Each element must conform to the passage object schema defined in this contract. | |
ranked_passages[].rank | Integer | Must be a positive integer starting at 1. Ranks must be sequential and unique within the array. Validate no gaps or duplicates. | |
ranked_passages[].passage_id | String | Must exactly match a [PASSAGE_ID] from the input set. Validate against the input ID list. Fail if an ID is hallucinated. | |
ranked_passages[].relevance_score | Float | Must be a float between 0.0 and 1.0 inclusive. Scores must be monotonically non-increasing by rank. Validate ordering. | |
ranked_passages[].justification | String | Must be a non-empty string. Should contain a reference to a specific keyword or phrase from the passage text. Validate string length > 0. | |
ranked_passages[].comparison_to_next | String | If present, must be a non-empty string explaining why this passage outranks the next. Required for all ranks except the last. Validate presence for ranks 1 to N-1. | |
discarded_passages | Array of objects | If present, each object must contain a passage_id and a discard_reason. Validate that no passage_id appears in both ranked_passages and discarded_passages. | |
discarded_passages[].passage_id | String | true if discarded_passages present | Must exactly match a [PASSAGE_ID] from the input set not present in ranked_passages. Validate against the input ID list. |
discarded_passages[].discard_reason | String | true if discarded_passages present | Must be a non-empty string explaining why the passage was deemed entirely irrelevant. Validate string length > 0. |
Common Failure Modes
Cross-encoder reranking with LLMs fails in predictable ways. These are the most common production failure modes and how to guard against them before they degrade your search quality.
Position Bias Toward First Passages
What to watch: The model disproportionately favors passages appearing early in the input list, mimicking a recency or primacy effect rather than true relevance comparison. This is especially pronounced when passages are semantically similar. Guardrail: Randomize passage order before each reranking call and average scores across multiple shuffled runs. Log position-vs-score correlation to detect drift.
Pairwise Comparison Collapse on Near-Ties
What to watch: When multiple passages are equally relevant, the model produces arbitrary or inconsistent rankings, often flipping relative order between runs. Justifications become vague or contradictory. Guardrail: Set a minimum relevance delta threshold. If score differences fall below it, group passages into a tie tier and preserve original retrieval order as a stable tiebreaker. Flag tie groups in eval logs.
Justification-Relevance Mismatch
What to watch: The model generates plausible-sounding justifications that contradict the actual passage content or assigned score. A passage may receive a high score with a justification describing a different passage entirely. Guardrail: Run a secondary faithfulness check that verifies each justification against its corresponding passage text. Require exact quote anchoring in justifications and flag mismatches for human review.
Query Drift in Long Passage Lists
What to watch: When reranking more than 15-20 passages, the model loses track of the original query intent and starts ranking based on internal coherence or general topic similarity rather than specific query relevance. Guardrail: Re-insert the query as a reference anchor between every 5-7 passage pairs. Use a sliding window approach for lists exceeding 20 passages and merge rankings with a stable sort.
Overfitting to Surface Lexical Overlap
What to watch: The model ranks passages with high keyword overlap above semantically relevant passages that use different terminology. This defeats the purpose of semantic reranking and reverts to BM25-like behavior. Guardrail: Include explicit instruction to prioritize semantic relevance over keyword matching. Add a few-shot example showing a lexically-different but semantically-correct passage ranked above a keyword-dense but off-topic passage.
Score Calibration Drift Across Batches
What to watch: Relevance scores shift meaning across different queries or passage sets. A score of 0.7 in one batch may indicate strong relevance while the same score in another batch indicates marginal relevance, breaking downstream threshold-based filtering. Guardrail: Include a fixed calibration passage pair in every batch with a known relevance relationship. Monitor calibration pair scores over time and trigger alerting when scores drift beyond acceptable bounds.
Evaluation Rubric
Use this rubric to evaluate the quality of cross-encoder reranking outputs before integrating them into a production RAG pipeline. Each criterion targets a specific failure mode common in LLM-based relevance ranking.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Output Format Validity | Output is a valid JSON array of objects, each containing 'passage_id', 'relevance_score', and 'justification' fields. | Malformed JSON, missing required fields, or extra fields that violate the output contract. | Schema validation check using a JSON Schema validator. Parse the output and verify all required fields are present and correctly typed. |
Relevance Score Calibration | Scores are monotonically decreasing and reflect a clear, justifiable ordering. The top passage is genuinely the most relevant to [QUERY]. | Scores are flat (all identical), randomly ordered, or the top-ranked passage is clearly less relevant than a lower-ranked one. | Pairwise comparison against a golden dataset of human-annotated relevance judgments. Measure nDCG@k against the ground truth ordering. |
Justification Grounding | Each justification references specific content from the passage that directly addresses the [QUERY], not just generic statements. | Justifications are vague ('it is relevant'), hallucinate content not in the passage, or simply paraphrase the query. | Human or LLM-as-judge review of a sample. Check if the justification contains a direct quote or specific reference to the passage text. |
Pairwise Comparison Logic | The justification for a higher-ranked passage explains why it is more relevant than the passage ranked immediately below it. | Justifications describe passages in isolation without comparative language, or the comparison logic is contradictory. | Parse justifications for comparative keywords ('more specific', 'directly addresses', 'while passage X...'). Flag outputs lacking any pairwise reasoning. |
Hallucination Resistance | No justification introduces facts, entities, or claims not present in the provided passage text. | A justification states a passage contains information it does not, or fabricates a quote. | Automated fact-verification check: extract all claims in justifications and verify their presence in the source passage via string matching or NLI model. |
Order Invariance | The relative ranking of two passages is consistent regardless of their position in the input list. The model does not exhibit position bias. | The first or last passage in the input list is consistently ranked higher, regardless of its actual relevance. | Shuffle the input passage list and rerun the prompt. Measure the correlation between the two output rankings using Kendall's Tau. A low correlation indicates position bias. |
Abstention on Empty Set | When [PASSAGES] is an empty list, the output is an empty JSON array | The model generates an error message, refuses to output, or hallucinates a passage ranking. | Unit test: 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 pairwise comparison prompt using a frontier model (GPT-4o, Claude 3.5 Sonnet). Use a small passage set (3-5 passages) and a single query. Skip formal eval harness; manually inspect ranking order and justifications for sanity.
Simplify the output schema to a flat ranked list with brief justifications:
codeRank the following passages by relevance to the query [QUERY]. Return a JSON array ordered from most to least relevant with "passage_id" and "justification" fields. Passages: [PASSAGES]
Watch for
- Position bias: the model may favor passages listed first in the input. Shuffle passage order across runs.
- Overly verbose justifications that cost tokens without adding signal.
- Missing tie-breaking logic when two passages are equally relevant.

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