Inferensys

Prompt

Multi-Passage Deduplication and Selection Prompt

A practical prompt playbook for using Multi-Passage Deduplication and Selection Prompt in production AI workflows.
Developer designing multi-agent workflow on laptop, architecture diagram on screen, casual home office setup with afternoon light.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, ideal user, required inputs, and operational boundaries for the Multi-Passage Deduplication and Selection Prompt.

This prompt is designed for RAG pipeline builders who face a common retrieval failure mode: the top-k results from vector or keyword search contain near-duplicate passages that waste context window space and dilute the answer signal. The job-to-be-done is to transform a noisy, redundant retrieval set into a minimal set of unique, information-dense passages before they reach the answer synthesis step. The ideal user is an AI engineer or search engineer who already has a working retrieval pipeline and needs a deduplication layer that preserves complementary details—such as a passage that adds a date or a specific constraint—while removing verbatim or high-overlap copies. You should use this prompt when your retrieval corpus contains multiple versions of the same document, when chunking strategies produce overlapping passages, or when you observe that your synthesis model is wasting tokens on repeated evidence and producing less precise answers as a result.

You should not use this prompt when your retrieval set is already small (fewer than 3 passages), when passages are guaranteed unique by your chunking strategy, or when your downstream model has a context window large enough to absorb redundancy without quality degradation. This prompt is also not a substitute for better retrieval. If your search pipeline consistently returns irrelevant results, fix retrieval quality first—deduplication cannot rescue bad recall. The prompt assumes that input passages are at least partially relevant to the query and that the primary problem is redundancy, not noise. For noise filtering, pair this with an evidence relevance scoring step before deduplication. The prompt requires a user query and a list of candidate passages as input, and it produces a deduplicated subset with information gain scores and explicit exclusion reasons. This structured output is designed to be consumed programmatically by a downstream synthesis prompt or logged for observability.

Before deploying this prompt, define your semantic similarity threshold. The prompt uses an information gain scoring approach rather than strict cosine similarity, which means it will preserve passages that share a topic but contribute distinct facts. If your use case requires aggressive deduplication (e.g., removing all passages about the same entity regardless of new details), you will need to adjust the instructions or add a stricter similarity constraint. For high-stakes domains such as clinical or legal RAG, always include a human review step or an automated eval that verifies no unique evidence was incorrectly removed. The next section provides the copy-ready prompt template with placeholders you can adapt to your retrieval schema and output format requirements.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and what you must provide before deploying it in a production RAG pipeline.

01

Good Fit: High-Redundancy Retrieval Sets

Use when: your retrieval pipeline returns 20+ passages with significant semantic overlap from dense vector search or multi-query expansion. Guardrail: set a minimum passage count threshold (e.g., 15+) before invoking deduplication to avoid unnecessary latency on small sets.

02

Bad Fit: Single-Source or Low-Overlap Corpora

Avoid when: all passages come from one document or retrieval already returns highly distinct results. Guardrail: run a pre-check measuring pairwise cosine similarity across the retrieval set; skip deduplication if mean similarity is below 0.3.

03

Required Input: Passage Metadata for Scoring

What to watch: deduplication quality degrades without source identifiers, timestamps, or section labels. Guardrail: require at minimum source_id, chunk_index, and retrieval_score fields in each passage object before invoking the prompt.

04

Operational Risk: Information Loss from Over-Aggressive Deduplication

What to watch: the model may discard complementary details that appear semantically similar but contain distinct facts. Guardrail: implement an information gain scoring threshold and retain any passage with a unique entity or numeric value not present in the selected set.

05

Latency Risk: Token-Heavy Prompt on Large Retrieval Sets

What to watch: passing 30+ passages through an LLM for deduplication adds 2-5 seconds of latency. Guardrail: pre-filter with a lightweight Jaccard or MinHash step to remove exact near-duplicates before invoking the LLM for semantic deduplication.

06

Eval Requirement: Semantic Near-Duplicate Detection Accuracy

What to watch: the model may miss paraphrased duplicates or incorrectly merge passages with different implications. Guardrail: maintain a golden dataset of passage pairs labeled as duplicate, complementary, or distinct, and measure precision/recall on each prompt version before release.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for deduplicating and selecting unique evidence passages from overlapping retrieval results, with information gain scoring.

This prompt template is designed to be dropped directly into your RAG pipeline after retrieval and before answer synthesis. It accepts a list of retrieved passages that may contain semantic near-duplicates, overlapping content, or redundant information, and returns a deduplicated set of passages ranked by unique information contribution. The template uses square-bracket placeholders that you replace with your actual retrieval output, deduplication thresholds, and output format requirements. Copy the template below, replace the placeholders with your pipeline's values, and wire it into your evidence selection stage.

text
You are an evidence deduplication and selection system. Your job is to process a set of retrieved passages, identify semantic near-duplicates and overlapping content, and return a deduplicated set of unique passages ranked by information gain.

## INPUT PASSAGES
[RETRIEVED_PASSAGES]

## DEDUPLICATION RULES
1. Compare all passages pairwise for semantic overlap. Two passages are near-duplicates if they convey substantially the same information, even if wording differs.
2. When a group of near-duplicate passages is found, select the single passage that is most complete, precise, and well-sourced. Discard the others.
3. For partially overlapping passages, keep both only if each contributes unique information not present in the other. If one passage subsumes the other entirely, keep only the more complete passage.
4. Do not discard a passage solely because it is shorter. Short passages with unique facts are valuable.
5. Do not merge or rewrite passages. Always return original passage text.

## INFORMATION GAIN SCORING
For each kept passage, assign an information gain score from 0.0 to 1.0 based on:
- **Novelty**: How much new information this passage adds beyond what earlier-ranked passages already cover.
- **Specificity**: How precise and fact-dense the passage is, versus vague or generic statements.
- **Relevance**: How directly the passage addresses the user query: [USER_QUERY]

## OUTPUT FORMAT
Return a JSON object with this exact schema:
{
  "deduplicated_passages": [
    {
      "passage_id": "original ID from input",
      "passage_text": "exact text of the selected passage",
      "information_gain_score": 0.85,
      "kept_because": "brief explanation of unique contribution",
      "duplicates_removed": ["passage_id_1", "passage_id_2"]
    }
  ],
  "total_input_passages": 0,
  "total_kept_passages": 0,
  "total_duplicates_removed": 0
}

## CONSTRAINTS
- [SIMILARITY_THRESHOLD]: Treat passages as near-duplicates if semantic overlap exceeds this threshold (e.g., 0.85).
- [MAX_OUTPUT_PASSAGES]: Maximum number of passages to return. If more unique passages exist, keep the highest-scoring ones.
- [MIN_INFORMATION_GAIN]: Exclude any passage scoring below this threshold, even if unique.

To adapt this template for your pipeline, replace [RETRIEVED_PASSAGES] with your actual retrieval output, formatted as an array of objects each containing a passage_id and passage_text. Set [USER_QUERY] to the original question that triggered retrieval. Tune [SIMILARITY_THRESHOLD] based on your tolerance for near-duplicates—start at 0.85 and lower it if you see redundant passages slipping through. Set [MAX_OUTPUT_PASSAGES] to match your downstream context window budget, and use [MIN_INFORMATION_GAIN] to filter out low-signal passages that add noise rather than value. If your retrieval system does not provide passage IDs, generate them from chunk indices or content hashes before calling this prompt. For high-stakes domains, add a human review step before the deduplicated set feeds into answer synthesis, and log the duplicates_removed field to maintain an audit trail of what was excluded and why.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Multi-Passage Deduplication and Selection Prompt. Each variable must be populated before the prompt is assembled and sent to the model. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[RETRIEVED_PASSAGES]

The raw list of passages returned from the retrieval step, including duplicates and near-duplicates

[ {"id": "doc-12-chunk-4", "text": "The capacitor discharges...", "score": 0.89}, {"id": "doc-12-chunk-5", "text": "When the capacitor discharges...", "score": 0.87} ]

Must be a non-empty array. Each object requires id and text fields. score is optional but recommended. Reject if array length is 0 or any object is missing text.

[QUERY]

The original user question or search query that produced the retrieved passages

What causes capacitor failure in high-temperature environments?

Must be a non-empty string. Trim whitespace. Reject if null, empty, or exceeds 2000 characters. The query should match what was sent to the retriever.

[SIMILARITY_THRESHOLD]

The cosine or semantic similarity score above which two passages are considered near-duplicates

0.85

Must be a float between 0.0 and 1.0. Default to 0.85 if not provided. Values below 0.70 risk over-deduplication; values above 0.95 risk under-deduplication. Log the threshold used.

[MAX_OUTPUT_PASSAGES]

The maximum number of unique passages to return after deduplication

5

Must be a positive integer. Default to 5 if not provided. If the deduplicated set is smaller than this value, return all available passages. If larger, select top passages by information gain score.

[INFORMATION_GAIN_WEIGHTS]

Optional weights for scoring information gain: novelty, relevance, and complementarity

{"novelty": 0.4, "relevance": 0.4, "complementarity": 0.2}

If provided, weights must sum to 1.0 within 0.01 tolerance. If omitted, use equal weighting. Validate JSON structure with numeric values only. Reject if any weight is negative.

[OUTPUT_SCHEMA]

The expected JSON structure for the deduplicated output

{"passages": [{"id": "string", "text": "string", "info_gain_score": "float", "is_representative": "boolean"}]}

Must be a valid JSON Schema or example structure. Validate that the schema includes id, text, and info_gain_score fields at minimum. Reject if schema is not parseable JSON.

[DOMAIN_TERMINOLOGY]

Optional domain-specific terms that should be preserved during deduplication to avoid merging passages with different technical meanings

["dielectric breakdown", "thermal runaway", "ESR"]

If provided, must be a JSON array of strings. Each term is treated as a signal that two passages may differ in meaning even if superficially similar. Null allowed if no domain terms are needed.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when deduplicating and selecting passages, and how to guard against it in production.

01

Semantic Near-Duplicate Leakage

What to watch: Passages with high semantic similarity but different wording slip through deduplication, bloating the context window with redundant information and starving genuinely unique evidence. Guardrail: Implement a two-pass check—first exact n-gram overlap, then embedding cosine similarity with a calibrated threshold (typically 0.85–0.92). Log similarity scores for threshold tuning.

02

Information Gain Collapse on Complementary Passages

What to watch: The prompt treats complementary passages (different facts about the same entity) as duplicates and removes one, losing critical details. This happens when deduplication criteria are too aggressive or entity-focused rather than fact-focused. Guardrail: Add an explicit 'information gain' scoring dimension in the prompt. Require the model to state what new fact each passage contributes before deciding to keep or drop it.

03

Context Window Starvation from Over-Selection

What to watch: The prompt selects too many passages after deduplication, exceeding the token budget for downstream synthesis and forcing truncation that drops the most relevant evidence last. Guardrail: Enforce a hard token budget in the output schema. Require the model to output a total_tokens count and a within_budget boolean. Add a post-processing truncation fallback that prioritizes by information gain score.

04

Order Bias in Selection Decisions

What to watch: The model favors passages appearing earlier in the input list, assigning them higher relevance or uniqueness scores regardless of actual content quality. This is a known positional bias in LLM ranking tasks. Guardrail: Randomize passage order before sending to the prompt. Run the deduplication twice with different orderings and flag passages where selection decisions flip. Use majority-vote or intersection as the final set.

05

Hallucinated Uniqueness Justifications

What to watch: The model fabricates differences between near-identical passages to justify keeping both, or invents reasons to exclude a passage that doesn't fit a perceived narrative. The output looks plausible but the deduplication logic is unsound. Guardrail: Require the model to quote the specific differentiating text from each passage in its justification. Add an eval that checks whether quoted text actually exists in the source passage using exact string matching.

06

Silent Dropping of Low-Confidence Evidence

What to watch: The model omits passages it judges as low quality or uncertain without surfacing that decision, creating a false impression of evidence completeness. Downstream synthesis then answers from an artificially clean but incomplete evidence set. Guardrail: Require an explicit excluded_passages array in the output with a required exclusion_reason field for every dropped passage. Log exclusion reasons for audit and tune the exclusion criteria if too many borderline passages are being dropped.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the deduplication and selection prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Semantic Near-Duplicate Detection

Passages with >90% semantic overlap are flagged as duplicates and only the highest information gain passage is retained

Two passages with near-identical meaning both appear in the final output set

Curate 10 known near-duplicate passage pairs from your retrieval corpus; assert only one from each pair survives deduplication

Information Gain Scoring Consistency

Retained passages each contribute at least one unique fact or detail not present in other retained passages

Output contains passages that restate the same fact in different words without adding new information

Extract claims from each retained passage; compute pairwise claim overlap; assert no passage has 100% claim overlap with another retained passage

Complementary Detail Preservation

When two passages cover the same topic but provide different details, both are retained with distinct information gain justifications

Complementary passages are incorrectly merged or one is dropped despite containing unique information

Construct a test set with 5 passage pairs where each adds one unique detail; assert both passages appear in output with correct gain labels

Output Schema Compliance

Output is valid JSON matching the expected schema with all required fields present and correctly typed

Missing fields, wrong types, or unparseable JSON in the output

Validate output against JSON Schema using a programmatic validator; run on 50 diverse retrieval sets and assert 100% schema compliance

Token Budget Adherence

Selected passage set stays within the specified [MAX_TOKENS] budget while maximizing unique information coverage

Output exceeds token budget or leaves significant budget unused while excluding high-gain passages

Count tokens in output passage set; assert count <= [MAX_TOKENS] and >= 80% of [MAX_TOKENS] when sufficient unique passages exist

Ordering Stability

Re-running the prompt on the same input set produces the same deduplication decisions and passage ordering

Passage selection or ranking changes across identical runs without input changes

Run prompt 5 times on identical input; assert output passage IDs and order match exactly across all runs

Edge Case: All-Duplicate Input

When all input passages are near-duplicates, output contains exactly one passage with an explanation that all others were redundant

Output returns empty set, returns multiple duplicates, or fails to explain the deduplication decision

Feed 5 semantically identical passages with minor wording differences; assert output contains exactly 1 passage with clear deduplication rationale

Edge Case: All-Unique Input

When all input passages are semantically distinct, all passages are retained with unique information gain justifications and no false deduplication

Legitimate unique passages are incorrectly flagged as duplicates or excluded

Feed 5 passages on completely different subtopics; assert all 5 are retained and each has a distinct information gain justification

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the deduplication prompt into a production RAG pipeline with validation, retries, and observability.

The Multi-Passage Deduplication and Selection Prompt is designed to sit between retrieval and answer synthesis in a RAG pipeline. It accepts a list of retrieved passages and returns a deduplicated set with information gain scores. In production, this prompt is not a one-shot call—it requires a harness that validates the output schema, handles malformed responses, logs selection decisions, and respects context window budgets. The harness should treat the prompt as a deterministic filter: same inputs should produce a stable deduplicated set, and any deviation should be logged as a regression signal.

Wire the prompt into your application as a post-retrieval processing step. After your retriever returns N passages, assemble the prompt with [PASSAGES] as a JSON array of objects, each containing id, text, and optional source and date fields. Set [SIMILARITY_THRESHOLD] to a float between 0.0 and 1.0 (start at 0.85 for near-duplicate detection). Set [MAX_OUTPUT_PASSAGES] to your context window budget divided by average passage tokens. Call the model with response_format set to JSON mode or structured outputs if available. Parse the response into a DeduplicationResult schema with fields: selected_passages (array of passage objects with added information_gain_score and uniqueness_rationale), removed_passages (array of IDs with removal_reason and duplicate_of_id), and coverage_summary (string describing what information is preserved). Validate that every duplicate_of_id in removed_passages exists in selected_passages, that no passage ID appears in both arrays, and that information_gain_score values are floats between 0.0 and 1.0. If validation fails, retry once with the validation errors appended to [CONSTRAINTS]. If the retry also fails, log the failure, fall back to a simpler deduplication method (e.g., exact text hash matching), and alert the on-call channel.

For observability, log the full deduplication trace: input passage count, output passage count, removed IDs with reasons, and the coverage_summary string. Compare these metrics across prompt versions to detect regressions in deduplication behavior. For high-stakes domains where information loss from over-deduplication could cause harm, add a human review step when the deduplication ratio exceeds a threshold (e.g., more than 50% of passages removed) or when information_gain_score values cluster near 0.5, indicating ambiguity. Use a smaller, faster model for this prompt when latency matters—deduplication is a classification-style task that does not require the largest model. Test with golden datasets containing known near-duplicate pairs, exact duplicates, and complementary passages to calibrate your [SIMILARITY_THRESHOLD] before production deployment.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base deduplication prompt and a small set of 10-20 passages. Use a simple JSON output contract with unique_passages and removed_duplicates arrays. Skip strict schema validation initially—focus on whether the model correctly identifies semantic near-duplicates versus complementary information. Test with obvious duplicates (identical text, paraphrased same facts) before moving to edge cases.

Prompt modification

code
You are a passage deduplication assistant. Given a list of retrieved passages, identify and remove semantic duplicates. For each group of duplicates, keep the most complete version and discard the rest.

Passages: [PASSAGES]

Return JSON with two arrays:
- "unique_passages": passages to keep
- "removed_duplicates": passages removed with reason

Watch for

  • Model keeping near-duplicates that differ by one sentence
  • Removing complementary passages that share a topic but contain different facts
  • Inconsistent deduplication thresholds across runs
  • No handling of partially overlapping passages
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.