Inferensys

Prompt

Evidence Deduplication and Ranking Prompt

A practical prompt playbook for deduplicating and ranking evidence passages in production RAG systems to prevent answer skew from repeated information.
Developer building agentic RAG system, retrieval pipeline diagram on laptop, technical workspace with notes.
PROMPT PLAYBOOK

When to Use This Prompt

Identifies when to apply evidence deduplication and ranking in RAG pipelines to prevent skewed answer generation from redundant passages.

This prompt is designed for RAG pipelines that retrieve from overlapping document collections, mirrored content, or versioned knowledge bases where near-duplicate passages inflate retrieval sets. When multiple retrieved passages convey the same information, downstream answer generation can over-weight that evidence, producing skewed or repetitive answers. This prompt identifies semantically redundant passages, selects the strongest representative from each duplicate cluster, and ranks the resulting unique evidence by relevance, specificity, and support strength. Use this prompt after retrieval and before answer generation. It assumes you already have a retrieval set with passage IDs and source metadata.

Do not use this prompt when every passage is known to be unique or when deduplication is handled at the retrieval index level. If your vector store already applies distinct filters, exact-match hashing, or embedding-based deduplication at query time, running this prompt adds latency without benefit. Similarly, skip this prompt for single-source retrieval sets where passage overlap is structurally impossible. The prompt is most valuable when your retrieval pipeline pulls from multiple indexes, document versions, or mirrored corpora where the same fact appears in several nearly identical forms. In those cases, deduplication before ranking prevents a single piece of evidence from dominating the answer simply because it was stored in three places.

Before wiring this into production, verify that your retrieval set includes passage IDs and source metadata. The prompt expects structured input with identifiable passages. If your retrieval layer returns raw text without identifiers, add a pre-processing step to assign stable IDs. Also plan for the token cost: deduplication requires the model to compare all passages against each other, so very large retrieval sets (50+ passages) may need chunking or a pre-filter step. Start with retrieval sets of 10–30 passages and measure whether deduplication improves answer quality before scaling up. If answer quality doesn't change, your retrieval set likely has low redundancy and you can remove this step.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Evidence Deduplication and Ranking Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your pipeline before you integrate it.

01

Good Fit: High-Recall, Overlapping Retrieval Sets

Use when: your RAG pipeline retrieves from multiple document collections, mirrors, or chunked corpora where near-duplicate passages are common. Guardrail: Run deduplication before answer generation to prevent repetitive evidence from skewing the model's attention and producing unbalanced summaries.

02

Bad Fit: Single-Source, Curated Knowledge Bases

Avoid when: your retrieval set comes from a single, deduplicated vector store with no overlapping documents. Guardrail: Skip deduplication to save latency and tokens. Add a lightweight uniqueness check in your retrieval pipeline instead of prompting the model.

03

Required Inputs: Ranked Retrieval Set with IDs

What to watch: The prompt needs passage IDs, full text, and source metadata to compare content and select the strongest representative. Guardrail: Ensure your retrieval pipeline attaches stable identifiers before passing passages to the deduplication prompt. Missing IDs break downstream citation linking.

04

Operational Risk: Semantic Drift in Near-Duplicate Detection

What to watch: The model may treat thematically similar but factually distinct passages as duplicates, collapsing important nuance. Guardrail: Set an explicit similarity threshold in the prompt instructions and require the model to explain why two passages are considered redundant before removing one.

05

Operational Risk: Ranking Instability Across Calls

What to watch: The same input set may produce different representative selections across multiple invocations, breaking reproducibility. Guardrail: Use low-temperature settings and provide a deterministic tie-breaking rule in the prompt, such as preferring the passage with the highest retrieval score or earliest publication date.

06

Latency and Cost: Quadratic Comparison Overhead

What to watch: Pairwise comparison of many passages consumes significant tokens and increases latency. Guardrail: Pre-filter the retrieval set to a manageable top-N before deduplication. If the set exceeds 20 passages, batch the comparisons or use embedding-based similarity as a pre-filter before model-based ranking.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt for deduplicating and ranking evidence passages in RAG systems with overlapping document collections.

This prompt template is designed to be pasted directly into your system instructions or user message for an LLM call. It instructs the model to identify near-duplicate or semantically redundant passages from a retrieval set, select the strongest representative from each cluster, and produce a final ranked list of unique evidence. The template uses square-bracket placeholders that you must replace with your specific data before sending the request to the model.

text
You are an evidence deduplication and ranking engine for a retrieval-augmented generation (RAG) system. Your task is to process a set of retrieved passages, identify near-duplicates or semantically redundant entries, select the strongest representative from each cluster, and rank the unique evidence by relevance, specificity, and support strength for the given query.

## INPUT

**Query:** [USER_QUERY]

**Retrieved Passages:**
[PASSAGE_LIST]
- Each passage must include a unique ID and the full text.
- Format: `[PASSAGE_ID]: [PASSAGE_TEXT]`

## TASK STEPS

1. **Semantic Comparison:** Compare all passages pairwise. Identify clusters of passages that convey substantially the same information, even if wording differs. Two passages are duplicates if they would support the same claim with no meaningful additional detail.

2. **Representative Selection:** For each duplicate cluster, select the single strongest representative based on:
   - **Specificity:** Prefer passages with concrete details, numbers, dates, or named entities over vague statements.
   - **Completeness:** Prefer passages that contain the full claim rather than partial fragments.
   - **Source Quality:** If source metadata is provided, prefer higher-authority sources.
   - **Query Alignment:** Prefer passages that more directly address the query.

3. **Uniqueness Verification:** Confirm that all remaining passages after deduplication are semantically distinct. If two passages still overlap significantly, merge them into the same cluster.

4. **Relevance Ranking:** Rank the unique passages by their relevance and support strength for the query. Assign each passage a rank position starting from 1 (most relevant).

## OUTPUT SCHEMA

Return a JSON object with the following structure:

```json
{
  "query": "[USER_QUERY]",
  "total_input_passages": [NUMBER],
  "duplicate_clusters_found": [NUMBER],
  "unique_passages_count": [NUMBER],
  "ranked_evidence": [
    {
      "rank": 1,
      "passage_id": "[PASSAGE_ID]",
      "passage_text": "[FULL_PASSAGE_TEXT]",
      "relevance_score": [0.0-1.0],
      "strength_tier": "[high|medium|low]",
      "deduplication_note": "[original|selected_representative_of_cluster_X]",
      "rationale": "[One sentence explaining why this passage is ranked here.]"
    }
  ],
  "removed_duplicates": [
    {
      "removed_passage_id": "[PASSAGE_ID]",
      "replaced_by_passage_id": "[PASSAGE_ID]",
      "reason": "[Why this passage was removed as a duplicate.]"
    }
  ]
}

CONSTRAINTS

  • Do not invent or modify passage text. Use the exact text provided.
  • If no duplicates are found, set duplicate_clusters_found to 0 and include all passages in the ranked list.
  • If the entire retrieval set is empty, return an empty ranked_evidence array and set counts to 0.
  • Assign relevance_score values that are calibrated and distinguishable. Avoid giving all passages the same score.
  • The strength_tier must be one of: high, medium, low.
  • Every removed duplicate must appear in the removed_duplicates array with a clear reason.
  • If source metadata is provided in the passage list, use it for authority assessment. If not provided, rely only on passage content.

EXAMPLE

Query: "What are the side effects of drug X?"

Passages:

  • P1: "Drug X may cause nausea and headache in some patients."
  • P2: "Common side effects of Drug X include nausea, headache, and dizziness."
  • P3: "Clinical trials show Drug X is effective for condition Y with mild side effects."

Expected Deduplication: P1 and P2 are near-duplicates. P2 is the stronger representative because it includes dizziness as an additional side effect and is more complete. P3 is distinct because it discusses efficacy, not side effects.

Expected Ranking: P2 (rank 1, directly addresses side effects with specific list), P3 (rank 2, mentions side effects tangentially but provides clinical context), P1 removed as duplicate.

Now process the input passages and return the JSON output.

Adaptation guidance: Replace [USER_QUERY] with the original question or claim being evaluated. Replace [PASSAGE_LIST] with your retrieved passages, ensuring each has a unique ID and the full text. If your retrieval system provides source metadata such as publication date, author, or domain authority score, include it alongside each passage and adjust the representative selection criteria accordingly. For high-stakes domains like medical or legal, add a [RISK_LEVEL] parameter and require human review when confidence is low or when the deduplication removes passages that might contain critical nuance. Always validate the output JSON against the schema before passing ranked evidence to downstream answer generation.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Evidence Deduplication and Ranking Prompt needs to work reliably. Validate these before sending to prevent ranking collapse, redundancy bleed, and silent evidence loss.

PlaceholderPurposeExampleValidation Notes

[QUERY]

The user question or claim that evidence must support or refute

What are the side effects of drug X?

Must be non-empty string. Check for vague queries that produce low-specificity rankings. If query is under 10 chars, flag for human review.

[RETRIEVED_PASSAGES]

The raw retrieval set containing potential near-duplicates and overlapping content

Array of {id, text, source, score} objects from vector search or hybrid retrieval

Must contain at least 2 passages to deduplicate. Validate array length. If fewer than 2, skip deduplication and return single-passage ranking. Check that text field is non-null and non-empty for each passage.

[PASSAGE_METADATA]

Source-level metadata for authority and recency weighting during tie-breaking

Array of {passage_id, source, publication_date, author, doc_type}

Optional but strongly recommended. If null, deduplication relies on semantic similarity alone. Validate date format (ISO 8601). Missing metadata should not crash ranking but should reduce confidence scores.

[SIMILARITY_THRESHOLD]

Cosine or semantic similarity threshold above which passages are considered near-duplicates

0.85

Float between 0.0 and 1.0. Default 0.85. Lower values increase deduplication aggressiveness. Validate range. If threshold < 0.7, log warning: high false-positive risk for distinct passages.

[MAX_RANKED_PASSAGES]

Maximum number of unique evidence passages to return after deduplication

5

Integer >= 1. Must not exceed context window budget. Validate against downstream token limit. If [RETRIEVED_PASSAGES] count is less than this value, return all unique passages without padding.

[RANKING_CRITERIA]

Ordered list of dimensions for ranking unique passages after deduplication

["specificity", "directness", "source_authority", "recency"]

Must be non-empty array of valid criterion strings. Allowed values: specificity, directness, source_authority, recency, query_alignment, factual_precision. Invalid criteria should cause pre-flight rejection with error message.

[OUTPUT_SCHEMA]

Expected JSON structure for ranked, deduplicated evidence output

{ranked_passages: [{id, text, rank, confidence_tier, dedup_info: {is_representative_of: [ids]}}]}

Validate schema before prompt assembly. Missing required fields in schema definition should halt request. Schema must include dedup_info to trace which passages were collapsed into each representative.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Evidence Deduplication and Ranking Prompt into a RAG pipeline with validation, retry, and logging.

This prompt is designed to sit between retrieval and answer generation in a RAG pipeline. It consumes a flat list of retrieved passages and outputs a deduplicated, ranked list of unique evidence items. The implementation harness must enforce a strict contract: the prompt receives a JSON array of passages with IDs, text, and optional metadata, and it must return a JSON array of ranked, unique passages with deduplication rationale. Because this step directly shapes the context window for downstream generation, the harness must validate the output before any answer is produced.

Wire the prompt into your application as a post-retrieval processor. After your retriever returns N passages, serialize them into the [RETRIEVED_PASSAGES] placeholder as a JSON array with fields: id, text, source, and optional score or date. Call the model with a low temperature (0.0–0.2) to maximize deterministic deduplication. Parse the response and validate the JSON schema: each output item must contain id, text, rank, deduplication_decision (either kept or removed_as_duplicate_of), and rationale. If the output fails schema validation, retry once with a repair prompt that includes the validation error. If the second attempt fails, log the failure and fall back to a simpler deduplication heuristic (e.g., exact text hash or embedding cosine similarity above 0.95) to avoid blocking the pipeline.

Logging and observability are critical here because deduplication errors compound downstream. Log the input passage count, output passage count, deduplication decisions, and any validation failures. Include a trace ID that links the retrieval set, deduplication output, and final generated answer. For high-stakes domains such as legal or medical, route outputs where more than 30% of passages were flagged as duplicates to a human review queue before answer generation. Avoid running this prompt on retrieval sets larger than 20–30 passages without chunking, as model context limits and ranking stability degrade with very long input lists. If your retriever returns more passages, pre-filter by relevance score before deduplication.

PRACTICAL GUARDRAILS

Common Failure Modes

Evidence deduplication and ranking pipelines break in predictable ways. These are the most common failure modes and how to guard against them before they reach production.

01

Near-Duplicate Collapse

What to watch: Semantically similar passages from overlapping document collections receive nearly identical scores, causing the top-K to be filled with redundant evidence. The model treats repeated information as consensus, skewing answer generation. Guardrail: Add a diversity constraint that penalizes passages with cosine similarity above 0.85 to already-selected evidence. Enforce a minimum source or document-ID spread in the final ranked set.

02

Length Bias in Scoring

What to watch: Longer passages receive higher relevance scores not because they are more relevant, but because they contain more tokens that match the query. Short, highly specific evidence gets buried. Guardrail: Normalize relevance scores by passage length or use a specificity-to-length ratio. Include a calibration check that compares short, high-precision passages against long, diffuse ones in eval.

03

Position Bias in Ranking

What to watch: The model over-weights passages that appear first in the input list, regardless of actual relevance. Retrieval order leaks into ranking order. Guardrail: Shuffle passage order before ranking and run the prompt multiple times. Flag passages whose rank changes by more than two positions across shuffles. Use position as a feature, not a default tiebreaker.

04

Authority Overfitting

What to watch: The model assigns high scores to passages from known authoritative domains even when the content is tangential or outdated. A prestigious source name overrides content relevance. Guardrail: Separate authority scoring from relevance scoring. Require the model to justify each ranking decision with a content-specific reason, not a source-name appeal. Flag rankings where authority and content relevance diverge by more than one tier.

05

Query-Answer Leakage

What to watch: The ranking prompt inadvertently leaks the expected answer into the evidence selection criteria, causing the model to rank passages that confirm the expected answer rather than passages that best address the query. Guardrail: Design the ranking prompt to reference only the query and evidence, never a pre-generated answer. Use a separate faithfulness check after ranking to verify that selected evidence supports the query, not a presupposed conclusion.

06

Silent Deduplication Failures

What to watch: The deduplication step removes passages that appear identical but contain critical differentiating details—such as updated figures, contradictory caveats, or version-specific information. The strongest representative loses nuance. Guardrail: Before deduplication, extract key claims from each candidate passage. Only merge passages whose claim sets overlap above 90%. Preserve passages with unique claims even if surface text is similar. Log deduplication decisions for audit.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks on a golden dataset of 20-50 retrieval sets with known duplicates. Each criterion targets a specific failure mode in evidence deduplication and ranking.

CriterionPass StandardFailure SignalTest Method

Duplicate Recall

All known near-duplicate pairs in the golden set are identified with a similarity score >= 0.85

A known duplicate pair receives a similarity score < 0.70 or is missing from the output entirely

Compare output duplicate pairs against golden-set labels; count false negatives

Representative Selection

For each duplicate cluster, the selected representative passage has the highest composite score (relevance + specificity + authority) among cluster members

A lower-scoring passage is selected as representative when a higher-scoring passage exists in the same cluster

For each cluster, verify selected passage ID matches the golden-set expected representative

Non-Duplicate Preservation

No more than 5% of unique passages are incorrectly flagged as duplicates or removed from the ranked output

A unique passage with no golden-set duplicate is assigned to a cluster or excluded from ranking

Count false positive deduplications against total unique passages in golden set

Ranking Order Stability

After deduplication, the top-5 ranked passages maintain the same relative order as the golden-set expected ranking

A passage ranked 3rd in golden set appears at position 7 or lower in output; position swaps exceed 2 slots

Compute Kendall tau distance between output ranking and golden-set ranking for top-K

Score Calibration

Deduplicated passage relevance scores correlate with golden-set relevance judgments at Spearman rho >= 0.80

Output scores show weak or negative correlation with golden-set judgments; high scores assigned to irrelevant passages

Calculate Spearman rank correlation between output scores and golden-set relevance labels

Coverage Completeness

The deduplicated ranked set contains at least one passage for each distinct evidence facet required by the query

A required evidence facet from the golden set has zero representative passages in the output

Check facet coverage: map output passages to golden-set facet labels and count missing facets

Output Schema Validity

100% of output records conform to the defined schema with all required fields present and correctly typed

Missing [PASSAGE_ID], null [RANK], or malformed [SIMILARITY_SCORE] in any output record

Validate output against JSON Schema; flag any record failing required-field or type checks

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base deduplication and ranking prompt. Use a simple JSON output schema with fields like unique_passages, removed_duplicates, and ranking_order. Skip strict validation and focus on whether the model correctly identifies near-duplicates and selects the strongest representative.

For quick iteration, reduce the input to 5-10 passages with obvious duplicates. Use a lightweight model call without retries.

code
[PASSAGES]
[QUERY]

Identify near-duplicate passages. For each duplicate group, select the most complete and specific passage. Return unique passages ranked by relevance.

Output JSON:
{
  "unique_passages": [{"id": "...", "text": "...", "rank": 1}],
  "removed_duplicates": [{"removed_id": "...", "kept_id": "...", "reason": "..."}]
}

Watch for

  • Semantic near-duplicates missed when wording differs significantly
  • Over-aggressive deduplication removing complementary passages
  • Ranking that doesn't account for query alignment after dedup
  • Missing rationale for why one passage was kept over another
Prasad Kumkar

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.