This prompt is designed for RAG pipeline engineers and search architects who observe that standard relevance ranking returns a monotonous set of top passages. In open-ended or multi-faceted queries—such as 'impact of climate change on agriculture'—a pure vector similarity search might return ten passages about drought stress in corn while ignoring economic, soil health, or pest-related dimensions. The job-to-be-done is not just retrieving relevant text; it is ensuring the final context window provides comprehensive, non-redundant evidence for downstream answer synthesis. The ideal user is someone who has already tuned their retrieval but sees diminishing returns in answer quality because the model is generating from a narrow evidence base.
Prompt
Passage Diversity Enforcement Prompt for Coverage

When to Use This Prompt
Identifies the specific production scenarios where diversity enforcement is required and, critically, where it adds unnecessary latency or complexity.
You should use this prompt when your knowledge base spans broad domains, user queries are exploratory or comparative, or when downstream tasks require balanced evidence. It is particularly effective as a post-retrieval, pre-generation step in a RAG pipeline. However, do not use this prompt for factoid-style queries with a single correct answer (e.g., 'What is the boiling point of water?'), as diversity enforcement will artificially exclude highly relevant, corroborating passages. Avoid it in high-throughput, low-latency systems where the additional LLM call for diversity selection violates your SLOs; in those cases, a deterministic algorithm like Maximal Marginal Relevance (MMR) is a better fit. Also, do not use this prompt if your retrieval set is already small (fewer than 5 passages), as diversity selection requires a sufficient pool to choose from.
Before implementing, verify that your retrieval step is returning a sufficiently large candidate set (e.g., top 20-50 passages). If you are already using a re-ranker, insert this diversity prompt after re-ranking but before context assembly. The output of this prompt is a structured selection of diverse passages with explicit coverage justification, which you should log for offline evaluation. Start by running this against a golden dataset of queries with known facet coverage to calibrate the diversity threshold before enabling it in production.
Use Case Fit
Where the Passage Diversity Enforcement Prompt delivers value and where it introduces risk. Use this card set to decide if the prompt fits your RAG pipeline stage and operational constraints.
Good Fit: Broad Exploratory Queries
Use when: the user query is open-ended or spans multiple subtopics (e.g., 'What are all the causes of X?'). The prompt prevents the top-k passages from clustering on a single cause. Guardrail: Always pair with a coverage justification field in the output schema so you can audit why each passage was selected.
Bad Fit: Single-Fact Lookups
Avoid when: the query requires one specific fact or a narrow definition. Diversity enforcement can force the model to select tangentially related passages, degrading precision. Guardrail: Route queries through a classifier first; bypass this prompt for factoid or definitional intents.
Required Inputs
Risk: The prompt fails silently if the input passage set is already homogeneous or too small. Guardrail: Require a minimum of 10-15 candidate passages and a pre-computed relevance score for each. The prompt needs enough material to enforce diversity without picking irrelevant text.
Operational Risk: Latency and Cost
Risk: Diversity enforcement adds a full LLM call before generation, increasing latency and token spend. Guardrail: Use a fast, cheaper model for this step. Set a strict timeout and fall back to top-k relevance ranking if the diversity prompt exceeds the latency budget.
Operational Risk: Information Gaps
Risk: The prompt may select diverse but shallow passages, missing deep coverage on any single topic. Guardrail: Add an 'information gap' field to the output. If critical subtopics are flagged as missing, trigger a secondary retrieval with a rewritten query targeting the gap.
Evaluation Trap: Subjectivity
Risk: 'Diversity' is hard to measure automatically; human evaluators may disagree on what counts as distinct coverage. Guardrail: Define diversity in the eval rubric as 'passages that address distinct sub-questions from a pre-defined topic taxonomy.' Automate coverage checks against that taxonomy.
Copy-Ready Prompt Template
A reusable prompt template for enforcing passage diversity in RAG retrieval sets, ensuring broad topic coverage instead of redundant top passages.
This prompt template enforces passage diversity by instructing the model to select a set of retrieved passages that maximizes topic coverage rather than simply taking the top-scoring results. It is designed for knowledge-base RAG systems where users ask questions that span multiple subtopics, and where returning five near-identical passages about the same facet produces a narrow, unhelpful answer. The template requires a list of candidate passages with relevance scores, a target selection count, and a coverage justification for each chosen passage. Use this when your retrieval pipeline returns clustered results and you need to ensure the final context window represents the full breadth of the query's information needs.
codeYou are a passage diversity enforcer for a RAG retrieval pipeline. Your task is to select a diverse set of passages from the candidate list that maximizes topic coverage for the given query. ## INPUT - Query: [QUERY] - Candidate Passages: [CANDIDATE_PASSAGES] - Target Selection Count: [TARGET_COUNT] - Diversity Criteria: [DIVERSITY_CRITERIA] ## CANDIDATE PASSAGES FORMAT Each passage is provided as a JSON object with the following fields: - id: unique passage identifier - text: passage content - relevance_score: pre-computed relevance score (0.0 to 1.0) - source: document or section source ## INSTRUCTIONS 1. Review all candidate passages and identify distinct topics, facets, or information dimensions present in the set. 2. Select exactly [TARGET_COUNT] passages that maximize coverage across these distinct topics. 3. Prioritize diversity of information over raw relevance score. A slightly less relevant passage that covers an unrepresented topic is preferred over a highly relevant passage that duplicates already-covered content. 4. For each selected passage, provide a coverage justification explaining what unique topic or information dimension it contributes. 5. If fewer than [TARGET_COUNT] distinct topics exist in the candidate set, select only the available distinct passages and flag the coverage gap. ## DIVERSITY CRITERIA [DIVERSITY_CRITERIA] ## OUTPUT SCHEMA Return a JSON object with the following structure: { "selected_passages": [ { "id": "string", "coverage_justification": "string explaining what unique topic this passage covers", "relevance_score": number } ], "coverage_summary": { "topics_covered": ["list of distinct topics identified"], "topics_missing": ["list of query-relevant topics not covered by any candidate passage"], "diversity_score": number between 0.0 and 1.0 indicating how well the selection covers the query's information needs }, "selection_rationale": "brief explanation of trade-offs made between relevance and diversity" } ## CONSTRAINTS - Do not select passages that are near-duplicates or cover the same information dimension. - If two passages cover the same topic, select the one with the higher relevance score. - Flag any information gaps where the candidate set lacks coverage for a query-relevant topic. - Maintain source diversity where possible; avoid over-selecting from a single document.
Adapt this template by adjusting the [DIVERSITY_CRITERIA] placeholder to match your domain. For technical documentation, criteria might include "procedural steps, configuration options, troubleshooting guidance, and version compatibility." For legal research, criteria might include "statutory interpretation, case precedent, jurisdictional analysis, and procedural requirements." The [TARGET_COUNT] should align with your context window budget—typically 3 to 8 passages for most RAG pipelines. If your retrieval system does not provide pre-computed relevance scores, remove that field from the candidate format and adjust the selection logic to rely solely on diversity. Always validate the output against your expected schema before passing selected passages to the answer generation step. For high-stakes domains, route the coverage summary to a human reviewer when the diversity score falls below 0.5 or when critical topics appear in the missing list.
Prompt Variables
Required inputs for the Passage Diversity Enforcement Prompt. Each variable must be populated before the prompt is assembled and sent to the model. Validation notes describe how to programmatically verify the input before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RETRIEVED_PASSAGES] | The set of candidate passages from the retrieval step that need diversity filtering | Array of {id: 'doc-12-chunk-3', text: 'The authentication module supports OAuth 2.0...', score: 0.87} | Must be a non-empty array. Each object requires id (string), text (non-empty string), and score (float 0-1). Reject if passages array is empty or any text field is null. |
[QUERY] | The original user query or information need that triggered retrieval | How do I configure authentication for the API gateway? | Must be a non-empty string. Check for injection patterns or empty queries. Minimum 3 characters after trimming. |
[TOPIC_TAXONOMY] | A predefined list of topics or categories that passages should cover for this domain | ['Authentication', 'Rate Limiting', 'Routing', 'Monitoring', 'Deployment'] | Must be a non-empty array of strings. Validate that taxonomy terms are distinct and domain-relevant. Null allowed if using open-ended diversity without predefined topics. |
[DIVERSITY_THRESHOLD] | The minimum number of distinct topics or clusters the output must cover | 3 | Must be an integer between 1 and the length of [TOPIC_TAXONOMY]. Default to 3 if not specified. Reject values exceeding available taxonomy size. |
[MAX_OUTPUT_PASSAGES] | The maximum number of passages to include in the final diverse selection | 5 | Must be a positive integer. Must be greater than or equal to [DIVERSITY_THRESHOLD]. Reject if output limit prevents meeting diversity requirement. |
[SIMILARITY_METHOD] | The method used to determine passage similarity for deduplication decisions | semantic_overlap | Must be one of: 'semantic_overlap', 'ngram_jaccard', 'embedding_cosine', or 'topic_label'. Default to 'semantic_overlap' if not provided. Reject unrecognized values. |
[COVERAGE_REQUIREMENT] | Whether the prompt must explicitly flag uncovered topics in the output | Must be boolean. When true, the output must include an 'uncovered_topics' field listing taxonomy items with no representative passage. When false, uncovered topics are silently omitted. |
Implementation Harness Notes
How to wire the Passage Diversity Enforcement Prompt into a production RAG pipeline with validation, retries, and observability.
The Passage Diversity Enforcement Prompt is designed to sit between your retrieval step and your answer generation step in a RAG pipeline. It consumes a set of top-k retrieved passages and produces a diverse subset with coverage justifications. In production, this prompt is not a one-shot call—it requires a harness that validates the output structure, enforces topic coverage constraints, and provides fallback behavior when the model fails to produce a valid diverse selection. The harness should treat this prompt as a filtering and re-ranking stage with a strict output contract, not as an optional enrichment step.
Wire the prompt into your application as a post-retrieval processor. After your vector or hybrid search returns the top N passages (typically 20–50), pass them to the LLM with the diversity prompt template. The model should return a JSON object containing a selected_passages array (each with passage_id, summary, and topic_label fields) and a coverage_justification object mapping required topics to selected passages. Validation is critical: before passing the diverse subset to your answer generation step, validate that (1) the output is valid JSON, (2) every passage_id references an actual input passage, (3) the number of selected passages does not exceed your context budget, and (4) all required topics from your [REQUIRED_TOPICS] list are covered. If validation fails, implement a retry loop with a maximum of 2 attempts, appending the validation error to the retry prompt. After 2 failures, fall back to a deterministic diversity algorithm (e.g., Maximal Marginal Relevance) and log the incident for review.
For observability, log the diversity prompt's input passage count, output passage count, topic coverage ratio, and validation status on every call. Track the coverage gap rate—the percentage of calls where the model fails to cover all required topics—as a key health metric. If this rate exceeds 5%, investigate whether your retrieval step is failing to surface passages for certain topics or whether the prompt's topic definitions need refinement. For high-stakes applications where missing a topic could cause harm (e.g., medical or legal RAG), route coverage gaps to a human review queue rather than silently proceeding with incomplete context. Model choice matters: use a model with strong instruction-following and JSON output reliability (GPT-4o, Claude 3.5 Sonnet, or equivalent). Avoid smaller or older models that may collapse diverse selections into redundant top-relevance picks, defeating the purpose of this prompt.
Expected Output Contract
The expected structure of the model response for the Passage Diversity Enforcement Prompt. Use this contract to validate the output before passing it to downstream answer generation.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
selected_passages | Array of objects | Must contain 3-7 passage objects. Array length must be within range. | |
selected_passages[].passage_id | String | Must match an ID from the provided [PASSAGE_SET]. No fabricated IDs allowed. | |
selected_passages[].coverage_topic | String | Must be a unique, non-overlapping topic label relative to other selected passages. Duplicate topics trigger a retry. | |
selected_passages[].relevance_score | Number (0.0-1.0) | Must be a float between 0 and 1. Scores below 0.5 require a justification in the notes field. | |
selected_passages[].selection_justification | String | Must explain why this passage was chosen over others covering the same topic. Cannot be empty or a generic placeholder. | |
coverage_gaps | Array of strings | Must list any topics from [QUERY] or [PASSAGE_SET] not covered by the selection. Use 'None identified' if coverage is complete. | |
diversity_score | Number (0.0-1.0) | Self-assessed diversity score for the selection. If below 0.7, the selection must be re-evaluated before use. | |
rejected_passages | Array of objects | If present, each object must include passage_id and a specific rejection_reason. Null allowed if all passages were considered. |
Common Failure Modes
What breaks first when enforcing passage diversity and how to guard against it in production.
Coverage Collapse to Dominant Topic
What to watch: The prompt selects passages that all address the same dominant topic while ignoring secondary but relevant themes. This happens when the model latches onto the highest-scoring cluster and treats diversity as a soft preference rather than a hard constraint. Guardrail: Add an explicit coverage checklist of required topic dimensions in the prompt and validate output against it with a structured schema check before accepting the selection.
Token-Budget Starvation of Minority Topics
What to watch: When context windows are tight, the model allocates nearly all tokens to the primary topic and gives minority topics only a single short passage or none at all, producing a false sense of coverage. Guardrail: Enforce minimum passage counts or token floors per topic category in the output schema, and add a post-selection validator that rejects selections where any required topic falls below the floor.
Near-Duplicate Passages Under Different Labels
What to watch: The model selects semantically similar passages from different sources and labels them as distinct topics to satisfy the diversity requirement without actually increasing information coverage. Guardrail: Add a deduplication check after selection using embedding cosine similarity or an LLM-based near-duplicate detector, and require the model to justify why each selected passage contributes unique information not present in others.
Coverage Justification Without Evidence
What to watch: The model generates plausible-sounding coverage justifications that claim topic representation but don't actually map to content in the selected passages. This is a hallucination pattern specific to diversity enforcement prompts. Guardrail: Require the model to quote a specific span from each selected passage that demonstrates the claimed topic coverage, and validate that each quote exists verbatim in the source passage.
Information Gap Blindness
What to watch: The model confidently selects passages for all requested topics even when the retrieval set contains no relevant content for some topics, fabricating connections rather than reporting gaps. Guardrail: Add an explicit instruction to mark topics as UNCOVERED when no passage in the retrieval set substantively addresses them, and include a gap report field in the output schema that must be populated before the selection is accepted.
Order Bias Toward Early Retrieval Results
What to watch: When the retrieval set is presented in ranked order, the model over-selects from the top of the list and under-represents relevant passages that appear later, reducing effective diversity regardless of the diversity instructions. Guardrail: Shuffle or randomize the passage order before presenting it to the diversity enforcement prompt, or use a two-pass approach where the first pass identifies candidate passages per topic and the second pass selects from those candidates without position bias.
Evaluation Rubric
Use this rubric to test whether the Passage Diversity Enforcement Prompt produces a selection that maximizes topic coverage and minimizes redundant passages. Each criterion targets a specific failure mode observed in production RAG systems.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Topic Coverage Completeness | All distinct topics present in the input set are represented in the output selection. | One or more topics from the source passages are entirely absent from the final selection. | Extract unique topic labels from the input passages. Verify that every label appears at least once in the output selection's coverage justification. |
Redundancy Minimization | No two selected passages convey the same core information or argument. | Two or more selected passages are near-duplicates or semantically equivalent. | Compute pairwise semantic similarity (e.g., cosine similarity > 0.85) on selected passages. Flag any pair exceeding the threshold as a failure. |
Coverage Justification Validity | Each selected passage includes a specific, non-generic justification explaining its unique contribution. | Justifications are vague, repetitive, or fail to identify a distinct topic or perspective. | LLM-as-Judge check: For each justification, verify it references a specific topic not covered by other justifications in the set. |
Information Gap Detection | The output explicitly lists any topics or question aspects not covered by the available passages. | The output claims full coverage when known topics are missing, or omits the gap analysis entirely. | Compare the output's gap list against a pre-defined list of expected topics for the query. Flag if expected topics are missing from both the selection and the gap list. |
Selection Size Constraint Adherence | The number of selected passages exactly matches the [MAX_PASSAGES] constraint. | The output contains more or fewer passages than specified by [MAX_PASSAGES]. | Parse the output and count the number of passage entries. Fail if count != [MAX_PASSAGES]. |
Source Grounding Integrity | All selected passage IDs and content match the provided input passages exactly. | A selected passage contains hallucinated content, a fabricated ID, or text not present in the input. | For each selected passage, verify the ID exists in the input set and the quoted text is a substring match against the source. |
Output Schema Compliance | The output is valid JSON matching the [OUTPUT_SCHEMA] specification. | The output is not valid JSON, contains extra fields, or is missing required fields like 'selected_passages' or 'coverage_gaps'. | Validate the raw output string against the [OUTPUT_SCHEMA] using a JSON schema validator. Fail on any schema violation. |
Diversity vs. Relevance Balance | Selected passages are both topically diverse and relevant to the query; no passage is included solely for diversity if it is irrelevant. | A passage is included to satisfy a diversity quota but its content is clearly off-topic or unhelpful. | LLM-as-Judge check: For each selected passage, verify it is relevant to the query on a 1-3 scale. Flag any passage scoring 1 (irrelevant) as a failure. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a small retrieval set (10-15 passages). Remove strict output schema requirements initially—accept a plain text list of selected passages with brief coverage justifications. Use a single diversity dimension (e.g., topic only) before adding facet, entity, or temporal diversity constraints.
Simplify the coverage justification to: "For each selected passage, state which topic gap it fills."
Watch for
- The model selecting semantically similar passages that differ only in wording
- Coverage justifications that are circular ("selected because it's relevant")
- Over-selection when the retrieval set is small—diversity enforcement may force weak passages in
- No baseline to measure whether diversity actually improved answer quality

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