This prompt is designed for RAG system builders and search engineers who need a deterministic, machine-readable ranking of evidence passages before answer synthesis or citation selection occurs. The core job-to-be-done is converting an unordered set of retrieved candidate passages into a strictly ordered JSON array with explicit relevance scores, strength tiers, and selection rationale. You should use this prompt when your downstream application code requires a predictable output contract—no regex parsing, no retry-on-malformed-JSON, no guessing whether the model ranked passages or just summarized them. The ideal user is an engineer integrating this prompt into a retrieval pipeline where the ranking output feeds directly into a citation formatter, an answer generation step with a context budget, or a gating function that discards low-tier evidence before synthesis.
Prompt
Evidence Ranking with Output Contract Prompt Template

When to Use This Prompt
Determines the right production scenarios for a deterministic, machine-readable evidence ranking prompt and clarifies when simpler or different approaches are required.
This prompt assumes you have already retrieved a set of candidate passages and need to order them. It is not a retrieval query writer, a passage rewriter, or a general-purpose summarization prompt. Do not use it when you need to generate search queries, expand user questions, or decide which documents to retrieve in the first place. Do not use it when your evidence set is a single passage—ranking a set of one produces noise, not value. Do not use it when your downstream consumer is a human reading a narrative report; this prompt optimizes for machine consumption with strict JSON output, not for prose explanations. If you need human-readable ranking explanations, pair this prompt with the Evidence Ranking with Explainability Output Prompt or add a separate explanation generation step after ranking is complete.
Before deploying this prompt, verify that your retrieval step produces candidate passages with stable identifiers that can survive the ranking and citation pipeline. The output contract requires a passage_id field for each ranked item, which means your retrieval system must assign and preserve IDs through the ranking step. If your retrieval system returns raw text without identifiers, add an ID assignment step before ranking. Also confirm that your application can handle the strength_tier enum values (HIGH, MEDIUM, LOW, INSUFFICIENT) and the relevance_score range (0.0 to 1.0) without additional normalization. The prompt includes a validation harness and retry logic for malformed rankings, but those guards only work if the upstream inputs are well-formed. Start with a small retrieval set (5-15 passages) and validate ranking stability before scaling to larger sets where position bias and length bias become more pronounced.
Use Case Fit
Where the Evidence Ranking with Output Contract prompt delivers value and where it introduces risk. Use these cards to decide if this structured ranking approach fits your pipeline.
Strict Schema Consumers
Use when: Your downstream answer generation or citation module requires a predictable JSON structure with typed fields like relevance_score and strength_tier. Avoid when: The ranking is only for human review in a debugging UI where natural language bullet points are sufficient.
High-Stakes RAG Pipelines
Use when: Ranking errors directly cause hallucination in customer-facing answers, making structured rationale and strength tiers essential for gating. Avoid when: The retrieval set is small, low-risk, or already highly curated, where the overhead of contract validation outweighs the benefit.
Required Inputs
Required: A list of evidence passages with unique IDs, the user query or claim, and the strict JSON output schema. Risk: Missing passage IDs or malformed input objects will cause the prompt to fail before ranking logic even executes. Validate inputs upstream before calling this prompt.
Operational Risk: Schema Drift
Risk: The model may return valid JSON that does not conform to the expected schema, especially under high load or with unusual input lengths. Guardrail: Implement a post-generation validation harness that checks required fields, enum values, and score ranges. Trigger a retry with the validation error message injected into the next prompt.
Operational Risk: Position Bias
Risk: The model may overweight passages that appear first in the input list, replicating a known LLM bias rather than true relevance. Guardrail: Randomize passage order before sending to the model and run an eval check comparing rankings across multiple shuffles to detect position sensitivity.
Not a Replacement for a Learned Ranker
Risk: Teams may treat this prompt as a permanent replacement for a trained cross-encoder or learned ranking model. Guardrail: Use this prompt for prototyping, evaluation, and low-volume pipelines. For high-QPS production, distill the prompt's ranking behavior into a fine-tuned model or use it to generate preference data for ranker training.
Copy-Ready Prompt Template
A production-ready prompt template that ranks evidence passages against a query and returns a strict JSON output contract suitable for direct application consumption.
This prompt template is designed to be pasted directly into your system instructions or sent as a user message. It enforces a strict output contract: the model must return only a valid JSON array of ranked evidence objects. Each object includes the passage ID, a relevance score, a strength tier, and a concise rationale. The template uses square-bracket placeholders for all variable inputs, making it safe to inject data from your retrieval pipeline without risking prompt injection or format corruption.
textYou are an evidence ranking engine. Your only job is to rank the provided evidence passages by how strongly they support answering the user's query. ## INPUT Query: [QUERY] Evidence Passages: [PASSAGES_JSON_ARRAY] ## RANKING CRITERIA 1. Relevance: How directly the passage addresses the query. 2. Specificity: How detailed and precise the information is. 3. Support Strength: How well the passage substantiates a potential answer. 4. Authority: Prefer passages from [AUTHORITY_SIGNALS] when available. ## CONSTRAINTS - [CONSTRAINTS] ## OUTPUT CONTRACT Return ONLY a valid JSON array. No other text. Each object must have these exact keys: - "passage_id": string - "relevance_score": number (0.0 to 1.0) - "strength_tier": "HIGH" | "MEDIUM" | "LOW" | "INSUFFICIENT" - "rationale": string (one sentence explaining the ranking) ## EXAMPLE OUTPUT [ { "passage_id": "doc_3_para_2", "relevance_score": 0.95, "strength_tier": "HIGH", "rationale": "Directly states the requested metric with a specific figure and date." } ] ## RISK LEVEL [RISK_LEVEL] Now rank the evidence.
To adapt this template, replace each square-bracket placeholder with your application data. The [PASSAGES_JSON_ARRAY] should be a serialized JSON array of objects, each containing at minimum an id and content field. The [CONSTRAINTS] placeholder lets you inject domain-specific rules, such as 'Exclude passages older than 2023' or 'Downgrade passages from unverified sources.' The [RISK_LEVEL] field should be set to HIGH if the ranking influences safety-critical decisions; in that case, add a human-review step after ranking. Always validate the returned JSON against the schema before passing it to downstream answer generation. If the model returns malformed JSON or extra text, use a repair prompt or retry with a stricter system instruction.
Prompt Variables
Validate these inputs before sending the prompt request. Missing or malformed variables are the most common cause of ranking failures in production.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The question or claim that evidence must be ranked against | What are the side effects of drug X in elderly patients? | Required. Non-empty string. Check for minimum specificity: queries under 10 characters or purely boolean should be rejected before ranking. |
[PASSAGES] | Array of retrieved evidence passages to rank | [{"id": "doc_12", "text": "Clinical trial results show..."}, {"id": "doc_7", "text": "Elderly patients experienced..."}] | Required. Array with 2-50 objects. Each object must have id (string) and text (string). Reject if array is empty or any passage text is null or whitespace-only. |
[RANKING_CRITERIA] | Ordered list of dimensions to rank by | ["relevance_to_query", "specificity_of_evidence", "source_authority", "recency"] | Required. Array of 1-5 strings from allowed enum: relevance_to_query, specificity_of_evidence, source_authority, recency, direct_quote_support. Reject unknown criteria values. |
[OUTPUT_SCHEMA] | Strict JSON schema the ranking output must conform to | See output contract: ranked_passages array with id, rank, relevance_score, strength_tier, rationale fields | Required. Must be a valid JSON Schema object or reference to a named schema. Validate that schema defines required fields and types before sending. |
[TOP_K] | Maximum number of ranked passages to return | 5 | Required. Integer between 1 and 50. Must not exceed [PASSAGES] array length. Default to 5 if not specified. Reject values over 50 to prevent context overflow. |
[STRENGTH_TIERS] | Allowed tier labels for evidence strength classification | ["strong", "moderate", "weak", "insufficient"] | Required. Array of 2-5 unique string labels. Must include at least "strong" and "insufficient". Validate that [OUTPUT_SCHEMA] references only these tier values in strength_tier field enum. |
[SOURCE_METADATA] | Optional metadata for each passage to inform authority and recency ranking | {"doc_12": {"date": "2024-03", "authority": "peer_reviewed", "source_type": "clinical_trial"}} | Optional. Object keyed by passage id. Each value is an object with optional date (ISO or YYYY-MM), authority (string), and source_type (string) fields. Null allowed. Skip authority-based ranking criteria if absent. |
[MAX_RATIONALE_LENGTH] | Character limit for selection rationale per passage | 200 | Optional. Integer between 50 and 500. Default 150 if not specified. Used to prevent verbose rationales that waste output tokens. Validate that rationale fields in output do not exceed this limit in post-processing. |
Implementation Harness Notes
How to wire the Evidence Ranking with Output Contract prompt into a production application with validation, retry, and logging.
The Evidence Ranking with Output Contract prompt is designed to be called from application code, not used as a one-off chat. The prompt returns a strict JSON schema, which means your application must validate the response before passing ranked evidence downstream to answer generation or citation selection. Treat this prompt as a deterministic function call with a typed return value. If the model returns malformed JSON, missing required fields, or scores outside the defined range, the application must catch the error and retry rather than silently propagating broken rankings.
Wire the prompt into a validation-first harness. After receiving the model response, parse the JSON and validate it against the output contract: check that rankings is a non-empty array, each entry has a valid passage_id, relevance_score is a float between 0.0 and 1.0, strength_tier is one of the allowed enum values (high, medium, low, insufficient), and selection_rationale is a non-empty string. Reject any response where scores are identical across all passages (a sign of ranking collapse) or where the top-ranked passage has a strength_tier of insufficient without explanation. Log validation failures with the raw response and error details for debugging.
Implement a retry loop with a maximum of 3 attempts. On validation failure, re-send the prompt with the same inputs but append a brief error context to the system message: 'Your previous response failed validation. Ensure all fields match the required schema exactly. Relevance scores must be distinct where passages differ in quality.' If the third attempt still fails, fall back to a simpler ranking prompt without the strict output contract, log the incident, and alert the engineering team. Never silently return unranked or partially ranked evidence to downstream consumers.
For model selection, use a model with strong JSON-following behavior and sufficient context window for your retrieval set. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are appropriate defaults. Avoid models known to struggle with structured output consistency. Set temperature to 0 or a very low value (0.1 maximum) to reduce ranking instability. If your application requires reproducible rankings for audit purposes, log the full prompt, model version, and response for every call. For high-throughput systems, consider caching rankings for identical query-evidence pairs with a TTL appropriate to your evidence freshness requirements.
Log everything that matters for debugging. At minimum, capture: the query, the number of input passages, the model and version used, the raw response, validation status, retry count, and the final ranked output. If the ranking is used to gate downstream answer generation (e.g., only passages with strength_tier of high or medium are passed forward), log the gating decision and which passages were excluded. This trace data is essential for diagnosing ranking quality issues, position bias, and evidence selection errors in production. Wire these logs into your existing observability stack rather than creating a separate system.
When to escalate beyond this prompt: If your retrieval set regularly exceeds 20 passages, split the ranking into batches and merge results with a second ranking pass. If evidence conflicts are common in your domain, pair this prompt with the Evidence Ranking with Contradiction Detection variant. If rankings must be explainable to end users, switch to the Evidence Ranking with Explainability Output prompt. And if ranking quality directly affects safety-critical decisions, add a human review step for low-confidence rankings or cases where the top passage has a relevance_score below 0.5.
Expected Output Contract
Validation rules and schema checks for the structured JSON output of the Evidence Ranking prompt. Use this contract to build a parser, validator, and retry harness before the ranking result enters downstream answer generation.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
ranked_evidence | array | Must be a non-empty array. If empty, treat as a ranking failure and trigger retry or fallback. | |
ranked_evidence[].passage_id | string | Must match a passage ID from the input [PASSAGES] array. Reject unknown or hallucinated IDs. | |
ranked_evidence[].relevance_score | number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Scores outside this range trigger a schema rejection. | |
ranked_evidence[].strength_tier | enum: [HIGH, MEDIUM, LOW, INSUFFICIENT] | Must be one of the four allowed enum values. Case-sensitive. Reject any other string. | |
ranked_evidence[].rationale | string | Must be a non-empty string with at least 10 characters. Null or whitespace-only strings trigger a validation failure. | |
ranked_evidence[].supporting_quote | string | null | If present, must be a substring or close match of the passage text from [PASSAGES]. Null is allowed when no direct quote exists. | |
ranking_confidence | number (0.0-1.0) | Must be a float between 0.0 and 1.0. If below [CONFIDENCE_THRESHOLD], flag the entire ranking for human review. | |
coverage_gap_flag | boolean | Must be true or false. If true, the downstream system should trigger re-retrieval or refuse to answer for the uncovered sub-topic. |
Common Failure Modes
Evidence ranking with output contracts fails in predictable ways. These cards cover the most common production failure modes and the guardrails that catch them before they reach users.
Schema Drift Under Load
What to watch: The model produces valid JSON but omits required fields, renames keys, or nests objects differently when passage count varies or context length grows. A ranking of 3 passages works; a ranking of 20 breaks the contract. Guardrail: Validate output against the exact JSON schema on every response. Reject and retry with a stripped-down schema reminder when validation fails. Test with minimum, typical, and maximum passage counts before shipping.
Position Bias Distorting Ranks
What to watch: Passages appearing first in the input list receive inflated relevance scores regardless of content quality. The model overweights early position and underweights later passages that are objectively stronger. Guardrail: Randomize passage order before sending to the ranking prompt. Run the same ranking twice with shuffled input order and compare score stability. Flag rankings where position correlates with score above a threshold.
Length Bias Favoring Verbose Passages
What to watch: Longer passages receive higher relevance and strength scores simply because they contain more tokens, not because they contain better evidence. Short, precise passages are unfairly penalized. Guardrail: Normalize passage lengths or include explicit length-agnostic scoring instructions in the prompt. Add an eval check that compares score-to-length ratios and flags outliers. Test with deliberately short high-quality passages and long low-quality passages.
Hallucinated Passage IDs
What to watch: The model invents passage IDs that don't exist in the input, especially when asked to rank a large set or when passages have similar content. The output looks valid but references phantom evidence. Guardrail: Cross-reference every returned passage ID against the input set. Reject rankings with unknown IDs and retry with explicit instruction to only use provided identifiers. Log hallucinated IDs for monitoring.
Score Collapse and Indistinguishable Tiers
What to watch: All passages receive nearly identical scores (e.g., 0.87, 0.86, 0.85) making the ranking useless for downstream gating or selection. The model avoids committing to clear distinctions. Guardrail: Require discrete strength tiers with forced distribution in the output contract. Add a score variance check that flags rankings where standard deviation falls below a threshold. Retry with stronger differentiation instructions.
Rationale-Only Without Actionable Scores
What to watch: The model produces eloquent selection rationales but the numerical scores and strength tiers don't align with the reasoning. A passage described as 'highly relevant' receives a medium tier, breaking downstream gating logic. Guardrail: Add a consistency check that compares rationale text against assigned scores and tiers. Use a lightweight judge prompt to verify alignment on a sample of rankings. Reject internally contradictory outputs.
Evaluation Rubric
Run these checks on a golden dataset of 50-100 queries with known relevant passages. Each criterion targets a specific production failure mode for evidence ranking.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Ranking Stability | Top-3 passages remain identical across 3 identical calls with temperature=0 | Top-3 order shifts or passages drop out between identical calls | Run 3 identical calls per query; compare top-3 passage IDs across runs |
Relevance Precision@3 | At least 2 of top-3 ranked passages are in the golden relevant set for 90% of queries | Fewer than 2 relevant passages in top-3 for more than 10% of queries | Compare top-3 passage IDs against golden relevance labels per query |
Score Calibration | Passages with relevance score >= 0.7 are in golden relevant set; passages < 0.3 are not | High-scored irrelevant passages or low-scored relevant passages exceed 15% of total | Bucket scores into 0.0-0.3, 0.31-0.69, 0.7-1.0; check alignment with golden labels |
Output Schema Compliance | 100% of responses parse as valid JSON matching [OUTPUT_SCHEMA] with all required fields present | Any response fails JSON parse or misses a required field in [OUTPUT_SCHEMA] | Validate each response against the schema; count parse failures and missing-field errors |
Strength Tier Distribution | No more than 60% of passages assigned to a single strength tier across the dataset | Single tier dominates (>80%) suggesting tier collapse or undifferentiated ranking | Count tier assignments across all responses; compute per-tier percentage |
Rationale Presence | Every ranked passage includes a non-empty selection_rationale field with >= 10 characters | Empty, null, or trivially short rationale strings appear in any response | Check character length and null status of selection_rationale for every ranked passage |
Position Bias Resistance | Passage rank correlates with relevance score (Spearman rho >= 0.6) not with original retrieval position | Rank correlates more strongly with original retrieval position than with relevance score | Compute Spearman correlation between rank and score vs. rank and original position |
Hallucinated Passage ID Rate | Zero passage IDs in output that do not exist in the input [PASSAGES] list | Any output passage ID not present in the input passage set | Extract all passage IDs from output; cross-reference with input [PASSAGES] ID list |
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
Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet). Remove the strict JSON schema enforcement and accept a looser ranked list with inline reasoning. Focus on whether the ranking order makes sense, not on perfect field compliance.
Simplify the output contract to:
json{ "ranked_passages": [ {"id": "[PASSAGE_ID]", "rank": 1, "rationale": "[BRIEF_REASON]"} ] }
Watch for
- Position bias where the first retrieved passage always wins
- Length bias favoring longer passages over shorter, more specific ones
- Missing rationale that makes ranking decisions opaque

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