This prompt is for RAG pipeline engineers who need to generate a human-readable explanation of how a set of retrieved sources was ranked. It takes the final ranked list, the ranking criteria, and the original query, and produces a structured explanation that a user or auditor can read to understand why one source appears above another. Use this when your application surfaces ranked evidence to end users, when compliance reviewers demand transparency into your retrieval logic, or when you need to debug ranking quality by inspecting the model's stated reasoning.
Prompt
Source Ranking Explanation Prompt Template

When to Use This Prompt
Understand the job-to-be-done, the required inputs, and the boundaries of the Source Ranking Explanation Prompt Template.
Do not use this prompt to perform the ranking itself. It explains an already-computed ranking. It does not re-rank, re-score, or select evidence. The ranking algorithm must run before this prompt is called. This prompt is a post-hoc explainability layer, not a ranking engine. If you need to rank sources, use a dedicated ranking prompt or a retrieval scoring model first, then pass the results here for explanation. The prompt requires three concrete inputs: the original user query, the final ordered list of sources with their metadata, and the explicit criteria that drove the ranking. Without all three, the explanation will be vague or misleading.
Before wiring this into production, define what a good explanation looks like for your use case. For audit scenarios, you may need strict traceability from each ranking decision to a specific criterion. For user-facing features, you may prioritize readability and conciseness. Build eval checks that compare the generated explanation against the actual ranking algorithm's behavior—if the explanation says source A outranks source B because of recency, but your ranker actually prioritized authority, the explanation has failed. Always validate explanation fidelity before surfacing it to users or auditors.
Use Case Fit
Where the Source Ranking Explanation prompt template delivers value and where it introduces risk. Use these cards to decide if this prompt fits your pipeline before you integrate it.
Strong Fit: User-Facing Explainability
Use when: your RAG application must show end users why certain sources were prioritized. This prompt generates human-readable ranking rationales that build trust. Guardrail: always verify that the generated explanation matches the actual ranking algorithm output; never let the prompt invent ranking criteria that differ from your production ranker.
Strong Fit: Audit and Compliance Workflows
Use when: you need documented evidence of how sources were ordered for regulatory review or internal governance. The structured explanation output creates an audit trail. Guardrail: store the raw ranking scores alongside the generated explanation so auditors can cross-reference the prompt's narrative against the ground-truth ranking data.
Poor Fit: Real-Time Ranking Replacement
Avoid when: you need the prompt to perform the actual ranking computation. This template explains rankings, it does not compute them. Risk: using an LLM to rank passages directly introduces latency, cost, and non-determinism. Guardrail: keep your production ranker as the source of truth and use this prompt only for post-hoc explanation generation.
Poor Fit: Black-Box or Proprietary Rankers
Avoid when: your ranking algorithm's internal logic is opaque, learned, or cannot be exposed. The prompt may hallucinate plausible-sounding but incorrect ranking justifications. Risk: fabricated explanations erode trust and create compliance exposure. Guardrail: only use this prompt when you can provide the actual ranking criteria, scores, and feature weights as input context.
Required Input: Ranking Metadata
Required: the prompt needs the ordered source list, per-source scores, the ranking criteria used, and any feature weights or signals that influenced ordering. Risk: without this metadata, the model will confabulate ranking reasons. Guardrail: build a pre-processing step that extracts ranking metadata from your retrieval pipeline and injects it into the prompt as structured context before generation.
Operational Risk: Explanation Drift
What to watch: over time, the prompt may produce explanations that diverge from how your ranker actually behaves, especially after ranker updates or model migrations. Guardrail: implement regression tests that compare generated explanations against known ranking outputs, and run these tests as part of your prompt versioning and deployment pipeline.
Copy-Ready Prompt Template
A production-ready prompt template for generating human-readable explanations of source rankings in RAG systems.
This prompt template is designed to be dropped directly into your RAG pipeline's explainability layer. It takes a pre-computed ranking—the output of your retrieval and scoring system—and produces a structured JSON explanation that non-technical users can understand. The prompt does not re-rank sources; it explains the ranking your system already produced. This separation of concerns keeps your ranking algorithm as the single source of truth while the LLM handles the communication layer.
textYou are an explainability engine for a retrieval-augmented generation system. Your job is to produce a human-readable explanation of why a set of sources was ranked in a specific order. You do not re-rank the sources. You explain the ranking that was already computed. ## User Query [USER_QUERY] ## Ranking Criteria The sources were ranked using the following criteria, in order of importance: [RANKING_CRITERIA] ## Ranked Sources Below is the final ranked list. Each source includes its rank position, identifier, title, author, publication date, relevance score, and a short content snippet. [RANKED_SOURCE_LIST] ## Instructions Generate a structured explanation with these sections: 1. **Ranking Summary**: A 2-3 sentence overview of how the sources were ordered, referencing the criteria. 2. **Per-Source Explanation**: For each source, explain why it received its rank. Reference the specific criteria that drove its position. For the top-ranked source, explain what made it the strongest match. For lower-ranked sources, explain what factors deprioritized them relative to higher-ranked sources. 3. **Key Trade-offs**: If any sources were close in score, explain what tipped the balance. If any criteria conflicted (e.g., high relevance but low recency), describe how the conflict was resolved. ## Constraints - Do not invent criteria that are not listed in [RANKING_CRITERIA]. - Do not claim a source was ranked for a reason that contradicts its metadata or snippet. - If a source's rank is primarily driven by its score, state that explicitly rather than fabricating additional justification. - Use the source identifiers exactly as provided in [RANKED_SOURCE_LIST]. - If the ranking criteria include weights or thresholds, reference them in your explanation. - Write in plain English suitable for a non-technical end user. Avoid jargon like 'cosine similarity' or 'BM25' unless the criteria explicitly use those terms. ## Output Format Return a JSON object with this schema: { "ranking_summary": "string", "per_source_explanations": [ { "source_id": "string", "rank": number, "explanation": "string" } ], "key_tradeoffs": [ { "description": "string", "sources_involved": ["string"] } ] }
To adapt this template, replace the four bracketed placeholders with your pipeline's actual data. [USER_QUERY] should contain the original question or search string. [RANKING_CRITERIA] must list the exact criteria your ranker used, including any weights or thresholds—this is what the LLM will reference, so be precise. [RANKED_SOURCE_LIST] needs a structured dump of your ranked results: each entry should include at minimum the source identifier, title, author, publication date, relevance score, and a content snippet. The snippet is critical because the LLM uses it to ground its explanations in actual document content rather than hallucinating reasons.
The output schema is intentionally flat and deterministic. Each source gets exactly one explanation object with its rank and source_id. The key_tradeoffs array captures edge cases where scores were close or criteria conflicted. This structure makes it straightforward to validate in your application layer: check that every source_id in the input appears in the output, verify that ranks match, and confirm that explanations reference only criteria present in [RANKING_CRITERIA]. For high-stakes deployments, add a validation step that compares the explanation's claims against the source snippets to catch hallucinated justifications before they reach users.
This prompt works best with models that have strong instruction-following and JSON output capabilities. GPT-4, Claude 3.5 Sonnet, and similarly capable models handle the constraint-following well. Weaker models may drift into re-ranking behavior or fabricate criteria. If you observe these failure modes, add a stronger preamble: 'You are forbidden from changing the rank order. Your only job is to explain the existing ranking.' For production systems, log every explanation alongside the input ranking for auditability, and consider periodic human review of a sample to detect explanation drift over time.
Prompt Variables
Required and optional inputs for the Source Ranking Explanation prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RANKED_SOURCES] | Ordered list of source objects with rank, id, title, snippet, and score | [ {"rank": 1, "id": "src-42", "title": "2024 Industry Report", "snippet": "Market growth reached 14%...", "score": 0.94}, {"rank": 2, "id": "src-17", "title": "Competitor Analysis Q3", "snippet": "Pricing pressure increased...", "score": 0.87} ] | Must be a valid JSON array with at least 2 objects. Each object requires rank, id, title, and snippet fields. Score field must be a float between 0.0 and 1.0. Reject if array is empty or contains duplicate rank values. |
[QUERY] | The original user question or search query that triggered retrieval | What were the main drivers of market growth in Q4 2024? | Must be a non-empty string. Check for injection patterns such as instructions to ignore ranking or override criteria. Truncate if longer than 2000 characters. |
[RANKING_CRITERIA] | Ordered list of criteria used to rank sources, with descriptions | [ {"criterion": "relevance", "weight": 0.5, "description": "How directly the source addresses the query"}, {"criterion": "recency", "weight": 0.3, "description": "Publication date relative to query timeframe"}, {"criterion": "authority", "weight": 0.2, "description": "Source credibility and domain expertise"} ] | Must be a valid JSON array with 1-5 criterion objects. Each object requires criterion, weight, and description fields. Weights must sum to 1.0 within a tolerance of 0.01. Reject if weights do not sum correctly. |
[OUTPUT_FORMAT] | Desired structure for the ranking explanation output | markdown | Must be one of: markdown, json, plain_text. Default to markdown if not specified. Reject unrecognized values. |
[AUDIENCE] | Target reader for the explanation, which controls tone and detail level | compliance_auditor | Must be one of: end_user, developer, compliance_auditor, internal_reviewer. Default to end_user if not specified. Controls vocabulary complexity and evidence depth. |
[MAX_EXPLANATION_LENGTH] | Maximum word count for the generated explanation | 300 | Must be a positive integer between 50 and 2000. Default to 500 if not specified. Reject values outside range. |
[INCLUDE_DEPRIORITIZATION_REASONS] | Whether to explain why lower-ranked sources were not selected | Must be true or false. Default to true. When false, the prompt skips deprioritization reasoning and focuses only on top-ranked sources. | |
[RANKING_ALGORITHM_NOTES] | Optional description of the actual ranking algorithm for fidelity checking | "BM25 with recency boost and authority multiplier" | Optional string. If provided, the explanation must not contradict the described algorithm. Null allowed. If present, eval should check for algorithmic fidelity in the output. |
Implementation Harness Notes
How to wire the Source Ranking Explanation prompt into a production RAG pipeline with validation, retries, and fallback behavior.
Wire this prompt after your ranking algorithm produces a final ordered list. The prompt is a post-processing step that runs before the ranked list is surfaced to the user. In a typical RAG pipeline, the flow is: query → retrieval → scoring/ranking → this prompt → user-facing display. Call this prompt synchronously before rendering the ranked source list in your UI. If the prompt fails or times out, fall back to displaying the ranked list without explanations rather than blocking the user.
Log every explanation alongside the ranking inputs for audit and debugging. If your application is in a regulated domain, store the explanation as part of the decision record. For latency-sensitive applications, consider running this prompt asynchronously after the ranked list is displayed, then injecting explanations when they are ready. Set a timeout of 5 seconds for the model call. If the output fails JSON schema validation, retry once with the validation error message appended to the prompt. If the retry also fails, log the failure and surface the ranked list without explanations. Do not retry more than once to avoid latency spikes.
Choose a model that balances explanation quality with latency. Faster models (e.g., GPT-4o-mini, Claude Haiku) work well for this task since the prompt requires structured reasoning over an already-ranked list rather than complex generation. Validate the output against a strict JSON schema that enforces the explanation structure, required fields, and source reference integrity. Every explanation must reference sources by their IDs from the input ranking list—reject outputs that invent source IDs or omit ranked sources without justification. Before deploying, run this prompt against a golden dataset of ranked lists with known good explanations to establish baseline eval scores for explanation fidelity and schema compliance.
Expected Output Contract
Validation rules for the structured JSON output of the Source Ranking Explanation prompt. Use this contract to parse, validate, and reject malformed responses before surfacing explanations to users.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
ranking_summary | string | Non-empty string. Must reference the total number of sources ranked and the primary ranking criteria used. | |
ranked_sources | array of objects | Array length must equal the number of input sources. Each object must contain source_id, rank, and ranking_rationale fields. | |
ranked_sources[].source_id | string | Must exactly match a source_id provided in the [SOURCE_LIST] input. No fabricated or missing IDs allowed. | |
ranked_sources[].rank | integer | Sequential integer starting at 1. No ties, no gaps, no duplicates across the array. | |
ranked_sources[].ranking_rationale | string | Non-empty string explaining why this source received this rank. Must reference at least one of the [RANKING_CRITERIA] explicitly. | |
deprioritization_explanations | array of objects | Must contain one entry for every source ranked below position 1. If only one source is provided, this array must be empty. | |
deprioritization_explanations[].source_id | string | Must match a source_id from ranked_sources with rank greater than 1. | |
deprioritization_explanations[].reason | string | Must explain why this source was ranked lower than the top source, citing specific evidence gaps or weaker criteria alignment. Cannot be a generic statement like 'less relevant'. |
Common Failure Modes
Source ranking explanations break in predictable ways. These are the most common failure modes when generating human-readable rationales for why sources were ordered a certain way, along with concrete mitigations.
Explanation Drift from Actual Ranking
What to watch: The model generates a plausible-sounding explanation that does not match the actual ranking algorithm's output. It invents criteria like 'source A was ranked higher because it is more recent' when the real ranker used only TF-IDF similarity. Guardrail: Pass the raw ranking scores and the algorithm's feature names into the prompt as [RANKING_METADATA]. Require the explanation to reference specific score components. Validate with a structured eval that checks if each stated reason maps to a real feature in the ranking payload.
Hallucinated Source Attributes
What to watch: The explanation fabricates details about a source to justify its rank, such as claiming a document is from 'a peer-reviewed journal' when that metadata was never provided. Guardrail: Constrain the prompt to only use source attributes present in the [SOURCE_METADATA] input block. Implement a post-generation validator that extracts all source descriptors from the explanation and checks them against the provided metadata fields. Flag any descriptor not found in the input.
False Conflict Fabrication
What to watch: The model invents a disagreement between sources to explain why one was deprioritized, even when the sources are complementary or address different sub-topics. Guardrail: Include a [SOURCE_RELATIONSHIPS] field in the prompt that explicitly states whether sources agree, disagree, or cover different aspects. Instruct the model to only describe conflict when the relationship field indicates disagreement. Use an eval that checks for conflict language when the input marks sources as non-conflicting.
Over-Explanation of Irrelevant Sources
What to watch: The model spends excessive tokens explaining why low-ranked sources were deprioritized, drowning the user in justification for sources that are clearly off-topic. Guardrail: Set a [FOCUS_THRESHOLD] in the prompt that instructs the model to only explain ranking decisions for sources above a relevance floor. Sources below the threshold receive a single-line dismissal. Test with a retrieval set containing obvious distractors and verify the explanation length is proportional to source relevance.
Post-Hoc Rationalization Without Score Transparency
What to watch: The explanation reads like a confident narrative but hides the fact that ranking scores were very close, making a marginal difference sound like a decisive one. Guardrail: Require the prompt to include [SCORE_DELTA] information and instruct the model to use calibrated language such as 'slightly preferred' or 'marginally higher' when score differences are below a defined threshold. Evaluate explanation tone against the actual score distribution.
Leaking Internal Ranking Signals
What to watch: The explanation exposes internal signals that should not be user-facing, such as 'source B was ranked lower because it came from a deprecated knowledge base' or 'source A won because of a hard-coded boost rule.' Guardrail: Provide an [ALLOWED_EXPLANATION_VOCABULARY] in the prompt that lists permissible ranking factors. Strip or map internal feature names to user-facing concepts before they enter the prompt. Add a regex-based output filter that catches forbidden internal terms.
Evaluation Rubric
Use this rubric to test whether the generated source ranking explanation is faithful to the actual ranking algorithm, complete in its reasoning, and safe for user-facing deployment. Run these checks before shipping the prompt to production.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Ranking Fidelity | The explanation correctly identifies the top 3 sources in the same order as the input [RANKED_SOURCES] list | Explanation reorders sources or promotes a lower-ranked source above a higher-ranked one without justification | Parse the explanation to extract the source order described; compare against the input [RANKED_SOURCES] order using exact match on source IDs |
Criteria Coverage | Every ranking criterion listed in [RANKING_CRITERIA] is mentioned and explained in the output | One or more criteria from [RANKING_CRITERIA] are omitted from the explanation | Extract all criterion names from the output; check set equality against the [RANKING_CRITERIA] input list |
Deprioritization Justification | For each source ranked below position 1, the explanation provides at least one specific reason why it was ranked lower than the source immediately above it | A lower-ranked source receives only a generic description with no comparative reason for its position | For each source at position N>1, verify the explanation contains a comparative statement referencing the source at position N-1 |
No Hallucinated Criteria | The explanation only references ranking criteria present in [RANKING_CRITERIA]; no invented criteria appear | The explanation introduces a ranking factor not listed in [RANKING_CRITERIA] such as a fabricated authority score or freshness metric | Extract all criterion-like terms from the output; verify each is a substring or semantic match to an item in [RANKING_CRITERIA] |
Source Reference Accuracy | Every source referenced in the explanation matches a source ID or title from [RANKED_SOURCES] with no fabricated identifiers | The explanation references a source ID, title, or author not present in [RANKED_SOURCES] | Parse all source identifiers from the output; check each against the [RANKED_SOURCES] input using exact or fuzzy match with a threshold of 0.9 |
Tone Appropriateness | The explanation uses neutral, factual language without praising or disparaging any source | The explanation uses subjective language such as excellent source, weak paper, or clearly superior | Run a sentiment classifier or keyword check for subjective adjectives; flag any output with positive or negative sentiment scores above 0.3 |
Explanation Length Constraint | The output respects any [MAX_TOKENS] or [MAX_SENTENCES] constraint provided in the prompt | The output exceeds the specified length constraint by more than 10% | Count output tokens or sentences; compare against [MAX_TOKENS] or [MAX_SENTENCES] constraint; fail if exceeded beyond tolerance |
Confidence Calibration | When [RANKING_CONFIDENCE_SCORES] are provided, the explanation reflects lower confidence for closely-scored adjacent sources | The explanation describes a decisive ranking difference between two sources whose confidence scores differ by less than 0.1 | Parse confidence scores from [RANKING_CONFIDENCE_SCORES]; for adjacent pairs with score delta < 0.1, verify the explanation uses hedging language such as narrowly edged out or similar relevance |
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 set of 3-5 ranked sources. Remove strict schema requirements and let the model produce free-text explanations. Use this to validate that the model understands ranking criteria before adding structure.
codeYou ranked these sources for the query: [QUERY] Ranked sources: [SOURCE_LIST_WITH_SCORES] Explain why you ordered them this way. Mention what criteria mattered most.
Watch for
- Explanations that don't match the actual ranking order
- Vague justifications like "this source was relevant" without specifics
- Model inventing criteria you didn't provide

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