This prompt is for RAG system builders who need to assemble a context window from a large set of retrieved passages but are hitting a wall with redundancy. When a vector store returns ten chunks that all say the same thing in slightly different words, the language model loses the signal it needs to answer complex, multi-aspect questions. The job-to-be-done is to rerank those passages so the final context set maximizes both relevance to the query and novelty relative to the passages already selected. The ideal user is an AI engineer or search engineer who already has a working retrieval pipeline and needs a controllable diversity mechanism before answer generation.
Prompt
Maximal Marginal Relevance Rerank Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Maximal Marginal Relevance Rerank Prompt.
Use this prompt when your retrieval results exhibit high semantic overlap, when users complain about shallow answers that miss nuance, or when you need to cover multiple facets of a query within a fixed token budget. It is particularly effective for exploratory questions ('What are all the causes of X?'), comparative questions ('How does A differ from B?'), and regulatory or due-diligence research where missing a distinct piece of evidence is worse than including a slightly less relevant one. The prompt expects a list of passages with relevance scores and a query, and it returns a reranked list with both relevance and novelty scores so you can tune the diversity trade-off yourself.
Do not use this prompt when your retrieval pipeline already returns highly diverse results, when latency constraints prohibit an extra LLM call before answer generation, or when the downstream task requires strict rank preservation from the initial retriever. It is also the wrong tool when you need to deduplicate near-identical passages—use a dedicated deduplication prompt for that. If your application is in a regulated domain such as healthcare or legal, this prompt should feed into a human review step where the reranked passage set is inspected for evidence loss before it reaches the answer generation stage. The next step after reading this section is to review the prompt template, wire it into your context assembly harness, and define the eval criteria that will tell you whether the diversity gain is worth the added latency.
Use Case Fit
Where the Maximal Marginal Relevance Rerank Prompt delivers value and where it introduces risk. Use these cards to decide if MMR reranking fits your pipeline before integrating it into production.
Good Fit: High-Redundancy Retrieval Sets
Use when: your vector or keyword retrieval returns many near-duplicate passages that waste context window tokens. MMR reranking explicitly penalizes similarity to already-selected passages, producing a diverse top-k set. Guardrail: set a minimum relevance threshold so novelty doesn't promote off-topic passages above marginally relevant ones.
Bad Fit: Single-Answer Factoid Queries
Avoid when: the user needs one definitive answer from a single authoritative passage. MMR's diversity bias can demote the best-matching passage in favor of a novel but less relevant one. Guardrail: for factoid Q&A, use pure relevance ranking. Reserve MMR for exploratory, comparative, or summarization queries where coverage matters more than precision at rank 1.
Required Inputs: Scored Candidate Set
Risk: applying MMR to unscored passages produces arbitrary diversity rather than relevance-balanced diversity. Guardrail: require a relevance score per passage from your retriever or a cross-encoder before MMR reranking. The prompt template expects [PASSAGES_WITH_SCORES] as input—don't skip the scoring step.
Operational Risk: Lambda Sensitivity
What to watch: the diversity-relevance trade-off parameter (lambda) heavily influences output quality, and the optimal value varies by query type and corpus. A fixed lambda will fail silently on some query distributions. Guardrail: log lambda values with each rerank result, monitor relevance@k and novelty metrics per query cluster, and build an eval harness that sweeps lambda values on a golden dataset before production deployment.
Operational Risk: Token Cost Amplification
What to watch: MMR reranking via an LLM prompt adds inference cost and latency to every query. For high-throughput systems, this can multiply costs without proportional user-facing improvement. Guardrail: implement a redundancy gate—only invoke MMR reranking when the initial retrieval set exceeds a similarity threshold. Cache rerank results for repeated queries. Consider algorithmic MMR for latency-sensitive paths and reserve LLM-based reranking for premium or low-volume tiers.
Eval Requirement: Novelty-Redundancy Trade-off
What to watch: standard relevance metrics (NDCG, recall) don't capture whether MMR improved diversity. A reranked set can look worse on pure relevance while being better for downstream answer quality. Guardrail: add a novelty-aware eval metric—measure unique information coverage across the top-k passages and compare against a relevance-only baseline. Run side-by-side answer quality evals with human review before claiming MMR improvement.
Copy-Ready Prompt Template
A reusable prompt template for applying Maximal Marginal Relevance reranking to a set of retrieved passages, balancing relevance against novelty.
The following prompt template applies Maximal Marginal Relevance (MMR) to a set of retrieved passages. It instructs the model to iteratively select passages that are both relevant to the query and novel compared to already-selected passages. The template uses square-bracket placeholders for all dynamic inputs, making it straightforward to integrate into a RAG pipeline where retrieval returns a candidate set that needs diversity filtering before answer generation.
textYou are a context reranking engine. Your task is to apply Maximal Marginal Relevance (MMR) to a set of retrieved passages, selecting a diverse subset that balances relevance to the query with novelty relative to already-selected passages. ## INPUTS **Query:** [QUERY] **Candidate Passages:** [PASSAGES] **Diversity Parameter (λ):** [LAMBDA] **Target Selection Count (k):** [K] ## INSTRUCTIONS 1. For each candidate passage, assess its relevance to the query on a scale of 0.0 to 1.0, where 1.0 is perfectly relevant. 2. Initialize an empty set of selected passages. 3. Iteratively select the next passage that maximizes the MMR score: - MMR = λ × relevance(passage, query) - (1 - λ) × max_similarity(passage, already_selected) - Where max_similarity is the highest cosine similarity between the candidate passage and any already-selected passage. 4. Stop when you have selected [K] passages or no remaining candidates meet a minimum relevance threshold of [MIN_RELEVANCE_THRESHOLD]. 5. For each selected passage, compute and report: - The relevance score to the query - The novelty score (1 - max_similarity to already-selected passages at time of selection) - The final MMR score at selection time ## OUTPUT SCHEMA Return a JSON object with this exact structure: { "query": "[QUERY]", "lambda": [LAMBDA], "total_candidates": <integer>, "selected_count": <integer>, "ranked_passages": [ { "rank": <integer starting at 1>, "passage_id": "<original passage identifier>", "passage_text": "<full passage text>", "relevance_score": <float 0.0-1.0>, "novelty_score": <float 0.0-1.0>, "mmr_score": <float>, "selection_rationale": "<brief explanation of why this passage was selected at this rank>" } ], "excluded_passages": [ { "passage_id": "<original passage identifier>", "relevance_score": <float>, "exclusion_reason": "<redundancy | below_threshold | not_reached>" } ], "diversity_assessment": "<summary of how well the selected set covers distinct aspects of the query>" } ## CONSTRAINTS - Preserve the original passage text exactly. Do not summarize or paraphrase. - If two passages have identical relevance scores, prefer the one with higher novelty. - If [LAMBDA] is close to 1.0, prioritize relevance over diversity. If close to 0.0, prioritize diversity. - Report scores to 3 decimal places. - If fewer than [K] passages meet the minimum relevance threshold, select only those that do and note the shortfall.
To adapt this template, replace the placeholders with your pipeline's actual values. [QUERY] should be the original user question or search query. [PASSAGES] should be a JSON array of objects, each with an id and text field. [LAMBDA] controls the relevance-diversity trade-off—start with 0.7 for balanced results and tune based on your use case. [K] sets the target number of passages to retain, typically matching your context window budget. [MIN_RELEVANCE_THRESHOLD] prevents low-quality passages from being selected purely for novelty; 0.3 is a reasonable starting point. Before deploying, validate that the output JSON matches the schema exactly, and run a few test queries to confirm that the diversity assessment accurately reflects the selected set's coverage.
Prompt Variables
Required and optional inputs for the Maximal Marginal Relevance Rerank Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The original user question or search string used for retrieval. Drives relevance scoring against each passage. | What are the side effects of drug X? | Non-empty string. Length > 0. Check for injection patterns if user-supplied. |
[PASSAGES] | The list of retrieved passages to rerank. Each passage should include an id and text field at minimum. | [{"id":"p1","text":"Drug X may cause..."}, {"id":"p2","text":"Common side effects..."}] | Valid JSON array. Minimum 2 passages. Each object must have id and text keys. Text must be non-empty. |
[LAMBDA] | The trade-off parameter between relevance and novelty. 0.0 = pure novelty, 1.0 = pure relevance. Typical range 0.5-0.7. | 0.6 | Float between 0.0 and 1.0 inclusive. Parse as float and range-check before prompt assembly. |
[TOP_K] | The number of passages to return after reranking. Controls final context window size. | 5 | Positive integer. Must be <= length of [PASSAGES]. Validate against passage count to avoid out-of-range errors. |
[RELEVANCE_WEIGHT] | Optional weight multiplier for the relevance score component. Use 1.0 for standard MMR. Adjust upward to favor relevance more aggressively. | 1.0 | Float >= 0.0. Default to 1.0 if not provided. Null allowed if using default behavior. |
[NOVELTY_WEIGHT] | Optional weight multiplier for the novelty score component. Use 1.0 for standard MMR. Adjust upward to penalize redundancy more aggressively. | 1.0 | Float >= 0.0. Default to 1.0 if not provided. Null allowed if using default behavior. |
[OUTPUT_SCHEMA] | The expected JSON structure for the reranked output. Defines fields like rank, passage_id, relevance_score, novelty_score, and selection_reason. | {"rank":int,"passage_id":str,"relevance_score":float,"novelty_score":float,"selection_reason":str} | Valid JSON schema object or string. Must include rank and passage_id fields at minimum. Schema check before prompt injection. |
[SIMILARITY_METHOD] | Specifies how similarity between passages should be computed for novelty scoring. Options: semantic, lexical, or hybrid. | semantic | Must be one of: semantic, lexical, hybrid. Enum check. Default to semantic if not provided. |
Implementation Harness Notes
How to wire the MMR rerank prompt into a production RAG pipeline with validation, logging, and threshold tuning.
The MMR rerank prompt is not a standalone step—it sits between retrieval and answer generation in your RAG pipeline. The typical call sequence is: (1) retrieve an initial candidate set from your vector store or hybrid search, (2) pass those candidates plus the original query into this prompt, (3) receive a reranked list with relevance and novelty scores, (4) apply a threshold or top-k cut to select the final context, and (5) feed that filtered context into your answer-generation prompt. The prompt expects a structured input containing the query string and an array of passage objects, each with at minimum an id and text field. You can extend the passage schema with metadata like source, date, or authority if your downstream answer prompt needs citation provenance.
Validation and retry logic. Parse the model's JSON output immediately after generation. Validate that every passage ID in the output exists in the input set, that relevance_score and novelty_score are numbers between 0 and 1, and that the rank field is a sequential integer starting at 1 with no gaps. If validation fails, retry once with the same prompt plus a brief error note appended to the system message—something like: 'Previous output failed validation: [specific error]. Return valid JSON only.' If the second attempt also fails, log the raw output, fall back to the original retrieval order, and fire an alert. For high-stakes domains, add a human review step before the reranked context reaches answer generation, especially when the MMR lambda parameter is tuned aggressively toward novelty and risks dropping highly relevant but redundant passages.
Model choice and latency budget. This prompt works well with models that have strong instruction-following and JSON output capabilities—GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are solid defaults. For lower latency or cost, smaller models like Claude 3 Haiku or GPT-4o-mini can handle the task if you constrain the input passage count to 20 or fewer and keep the output schema tight. If you're reranking 50+ passages, consider batching: split the candidate set into overlapping windows of 15-20 passages, run MMR on each window independently, then merge results with a final deduplication pass. Always log the lambda value, input passage count, output passage count, and per-call latency so you can tune the trade-off between rerank quality and pipeline speed.
Threshold tuning and eval. The relevance_score and novelty_score fields are your primary tuning levers. Start by logging score distributions across a few hundred queries to understand your retrieval baseline. Set an initial relevance floor (e.g., 0.4) and a novelty floor (e.g., 0.3), then run a side-by-side eval comparing answer quality with and without MMR reranking. Use an LLM judge or human review to score answer completeness and faithfulness. If you see answer quality drop, your novelty threshold may be too aggressive—back it off. If you see no improvement, your retrieval set may already be diverse enough, and MMR reranking may be adding latency without value. Store the reranked passage list alongside each query in your trace store so you can replay and debug specific cases later.
What to avoid. Don't use this prompt as a replacement for retrieval quality improvements—if your initial retrieval is returning mostly irrelevant passages, MMR reranking won't fix it. Don't set the lambda parameter to an extreme (0.0 or 1.0) without testing; pure relevance ranking duplicates your retriever's job, and pure novelty ranking can surface irrelevant but unique passages. Don't skip the output validation step—model JSON errors in production are common, and a single malformed rerank output can break your entire answer-generation pipeline. Finally, don't treat the MMR scores as absolute truth; they're model estimates and should be calibrated against your own eval data before you rely on them for automated threshold decisions.
Common Failure Modes
MMR reranking fails in predictable ways. Here's what breaks first and how to catch it before it reaches your answer generation step.
Diversity Overreach Kills Critical Evidence
What to watch: The lambda parameter is tuned too high for diversity, causing the reranker to discard the second and third most relevant passages in favor of tangentially related but novel content. The final context set looks diverse but misses the core evidence needed to answer the query. Guardrail: Run a relevance-only baseline alongside MMR and compare answer completeness. Set a minimum relevance threshold that diversity cannot override, and log dropped high-relevance passages for review.
Novelty Collapse on Short Context Windows
What to watch: When the target k is small relative to the retrieval pool, MMR greedily selects the top passage and then struggles to find anything both relevant and sufficiently novel. The output collapses to one good passage and several low-relevance fillers. Guardrail: Validate that the novelty score distribution has meaningful variance. If all post-selection passages cluster near zero novelty, widen the initial retrieval pool or reduce the diversity weight before reranking.
Embedding Model Mismatch Produces Garbage Novelty Scores
What to watch: The similarity function used for novelty calculation uses a different embedding model than the one used for retrieval. Cosine similarity between mismatched embedding spaces produces novelty scores that are effectively random, making the diversity term noise. Guardrail: Pin the embedding model used for MMR similarity to the same model used for retrieval. If models differ, run a calibration check by computing pairwise similarities on a known duplicate set and verifying expected high overlap.
Query-Document Similarity Drift Under Long Queries
What to watch: For verbose or multi-sentence queries, the relevance score computed by embedding similarity dilutes across too many concepts. MMR selects passages that match peripheral query terms rather than the core intent, and the novelty term amplifies the drift. Guardrail: Preprocess long queries with a query decomposition or focus-extraction step before MMR. Compute relevance against a condensed query representation, not the raw user input.
Greedy Selection Order Bias
What to watch: MMR's greedy algorithm picks the highest-scoring passage first and builds the set incrementally. If the initial retrieval ranking is noisy, a mediocre passage can claim the first slot and anchor all subsequent novelty comparisons, locking out better passages that are similar to the anchor. Guardrail: Run MMR with multiple seed passages (top-3 from retrieval) and compare output sets. If results diverge significantly, the retrieval ranking is too noisy for greedy MMR and needs a quality filter upstream.
Lambda Tuning Without Ground Truth Leads to Silent Degradation
What to watch: Teams set lambda based on intuition or a one-time manual review, then never recalibrate. As the document corpus, query distribution, or embedding model changes, the optimal relevance-diversity tradeoff shifts and answer quality degrades without obvious errors. Guardrail: Implement a periodic eval loop using an LLM judge to score answer completeness and faithfulness at multiple lambda values on a held-out query set. Set a drift alert if the optimal lambda moves more than 0.1 between evaluations.
Evaluation Rubric
Use this rubric to test the quality of the MMR rerank output before integrating it into a production RAG pipeline. Each criterion targets a specific failure mode common to diversity-focused reranking.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Relevance Preservation | Top-ranked passage has a relevance score >= 0.8 to the [QUERY] | The most novel passage is ranked first despite low relevance to the query | Calculate cosine similarity between the query embedding and the top-1 passage; assert score >= threshold |
Redundancy Reduction | No two passages in the top-K output have a pairwise cosine similarity > 0.85 | Near-duplicate passages appear in the final list, defeating the purpose of MMR | Compute all pairwise similarities in the output list; assert max similarity < 0.85 |
Lambda Sensitivity | Changing [LAMBDA] by ±0.1 produces a measurable change in the top-5 ordering | The output is identical for lambda=0.3 and lambda=0.9, indicating the parameter is ignored | Run the prompt with lambda=0.3 and lambda=0.9; assert Jaccard similarity of top-5 sets < 0.8 |
Output Schema Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present | Missing | Validate output against the JSON schema; assert no missing required fields and correct types |
Score Range Validity | All | Scores outside the 0-1 range, null values, or non-numeric strings in score fields | Parse all score fields; assert 0.0 <= score <= 1.0 for every passage |
Ranking Monotonicity | Passages are ordered by descending MMR score, and the MMR score is consistent with the stated [LAMBDA] | A passage with a higher relevance and novelty score is ranked below a lower-scoring passage | Calculate expected MMR = lambda*relevance + (1-lambda)*novelty; assert list is sorted descending by this value |
Input Passage Fidelity | The text of each output passage exactly matches a passage in the [INPUT_PASSAGES] list | The model hallucinates a new passage, truncates content, or merges two passages into one | Exact string match of each output passage text against the input list; assert 100% match rate |
Edge Case: Single Passage Input | When [INPUT_PASSAGES] contains only 1 passage, the output contains that single passage with scores assigned | The prompt returns an error, an empty list, or refuses to process a single-passage input | Unit test with a single-passage input; assert output list length == 1 with valid scores |
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 MMR prompt with a small retrieval set (10–20 passages) and a fixed lambda of 0.7. Skip strict output schema enforcement—accept free-text ranked lists. Focus on tuning the relevance-vs-novelty balance through lambda adjustments in the prompt body.
Prompt modification
Replace [LAMBDA] with a hardcoded value like 0.7 and remove [OUTPUT_SCHEMA] constraints. Use: Rank these passages by balancing relevance to the query against novelty relative to already-selected passages. Return a simple ordered list with a short justification per passage.
Watch for
- Over-ranking near-duplicates when lambda is too low
- Missing edge cases where all passages are equally relevant
- No baseline comparison to pure relevance ranking

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