Inferensys

Prompt

Passage Deduplication and Redundancy Removal Prompt

A practical prompt playbook for using Passage Deduplication and Redundancy Removal Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, ideal user, required context, and constraints for the Passage Deduplication and Redundancy Removal Prompt.

This prompt is designed for RAG pipeline operators and search engineers who need to clean a retrieved passage set before it enters the context window for answer generation. The job-to-be-done is straightforward: take a list of passages returned from vector, keyword, or hybrid search and produce a deduplicated set where near-duplicate content is merged rather than repeated. Redundant context wastes token budget, dilutes signal, and often causes models to over-index on repeated information, leading to verbose or skewed answers. The ideal user is someone integrating this step into an automated retrieval pipeline—typically an engineer who already has a working retrieval system and is now hardening it for production cost and quality.

This prompt is most effective when your retrieval system returns multiple chunks from the same source document or semantically overlapping passages from different documents. It expects a structured input: a list of passages, each with a unique ID and text content. The output is a deduplicated set with merge notes explaining which passages were combined and why. Use this prompt when you observe repeated information in your context windows, when your token costs are inflated by redundant passages, or when answer quality degrades due to the model fixating on duplicated evidence. Do not use this prompt as a substitute for better retrieval. If your retriever is returning fundamentally irrelevant passages, deduplication won't fix that—you need a relevance filter or reranker upstream. Similarly, if your passages are already highly diverse and non-overlapping, this step adds latency without benefit.

Before wiring this into production, you must define what counts as a duplicate for your use case. Semantic near-duplicates (same fact, different wording) require a higher similarity threshold than exact string matches. The prompt includes a [SIMILARITY_THRESHOLD] placeholder that lets you tune this boundary. Start with a moderate threshold and adjust based on false-merge and missed-duplicate rates measured against a labeled evaluation set. Always run the deduplication step before context assembly, not after, and log merge decisions for debugging retrieval quality over time. If your domain includes passages where near-duplicate content carries different metadata, authority levels, or timestamps, you may need to extend the prompt with merge rules that preserve the most authoritative or recent version rather than simply combining text.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational preconditions required before you put it into a RAG pipeline.

01

Good Fit: High-Recall Retrieval Pipelines

Use when: your retrieval step returns many near-duplicate passages (e.g., dense retrieval over chunked documents with overlap). Guardrail: Run deduplication after retrieval but before context packing to prevent redundant tokens from consuming your context budget and diluting answer quality.

02

Good Fit: Multi-Source Aggregation

Use when: passages come from multiple knowledge bases, scraped pages, or mirrored documentation that contain substantial content overlap. Guardrail: The prompt's merge notes help trace which sources contributed overlapping content, preserving provenance for downstream citation verification.

03

Bad Fit: Single-Source or Sparse Retrieval

Avoid when: your retrieval set is small (fewer than 5 passages) or comes from a single document with no chunk overlap. Guardrail: Deduplication adds latency without benefit when overlap is unlikely. Gate the prompt behind a passage-count threshold to skip it for sparse sets.

04

Bad Fit: Semantic Equivalence Without Lexical Overlap

Avoid when: passages express the same meaning using entirely different vocabulary, structure, or framing. Guardrail: This prompt relies on surface-level and near-duplicate detection. For semantic deduplication, pair it with a cross-encoder similarity step or use embedding-based clustering before this prompt.

05

Required Input: Passage Set with Source IDs

What to provide: an array of passages, each with a unique passage_id, source_document_id, and text field. Guardrail: Without stable identifiers, the merge notes cannot reference which passages were combined, breaking downstream citation linking and audit trails.

06

Operational Risk: False Merges on Distinct Content

What to watch: the prompt may incorrectly merge passages that share keywords but cover different topics, entities, or time periods. Guardrail: Implement a post-deduplication validation step that checks merged passages for semantic drift. Flag merges where the combined text introduces contradictions or covers distinct subtopics for human review.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for deduplicating and merging near-duplicate passages in a RAG retrieval set.

This section provides a copy-ready prompt template you can adapt directly into your retrieval pipeline. The prompt is designed to take a batch of retrieved passages, identify exact duplicates and near-duplicates, and produce a cleaned set with merge notes. It uses square-bracket placeholders for all variable inputs so you can wire it into your application without rewriting the core instruction logic.

text
You are a passage deduplication engine for a RAG pipeline. Your job is to clean a set of retrieved passages before they are used for answer generation.

## INPUT
You will receive a list of passages. Each passage has an ID and text content.

[PASSAGES]

## TASK
1. Identify exact duplicate passages (identical or near-identical text).
2. Identify near-duplicate passages that convey the same information with minor wording differences.
3. For each group of duplicates or near-duplicates, select the single best passage to keep based on:
   - Completeness of information
   - Clarity of expression
   - Absence of contradictory statements within the passage
4. For near-duplicates, produce a brief merge note explaining what additional information the discarded passages contained, if any.
5. Return all unique, non-duplicate passages unchanged.

## CONSTRAINTS
- Do not merge passages that convey different facts, even if they share a topic.
- Do not discard a passage unless you are confident it is a duplicate or near-duplicate.
- Preserve the original passage text exactly for kept passages. Do not rewrite or summarize.
- If uncertain whether two passages are duplicates, keep both and flag them for human review.

## OUTPUT FORMAT
Return a JSON object with the following structure:

{
  "kept_passages": [
    {
      "id": "original passage ID",
      "text": "original passage text unchanged",
      "status": "kept | merged",
      "merged_from_ids": ["list of discarded passage IDs"],
      "merge_note": "explanation of what was merged, or null if kept as-is"
    }
  ],
  "discarded_passages": [
    {
      "id": "discarded passage ID",
      "reason": "exact_duplicate | near_duplicate",
      "merged_into_id": "ID of the kept passage"
    }
  ],
  "flagged_for_review": [
    {
      "id": "passage ID",
      "reason": "why this passage could not be confidently classified"
    }
  ]
}

## EXAMPLES
[EXAMPLES]

## RISK LEVEL
[RISK_LEVEL]

To adapt this template, replace [PASSAGES] with your serialized passage list, typically as a JSON array of objects with id and text fields. The [EXAMPLES] placeholder should contain 2-3 few-shot examples showing correct deduplication behavior, including a borderline near-duplicate case. Set [RISK_LEVEL] to high if downstream answers have regulatory or safety implications—this should trigger additional human review flags in your harness. For production use, validate the output JSON against the schema before passing deduplicated passages to your answer generation step. If the model returns malformed JSON, use a repair prompt or retry with stricter format instructions rather than silently falling back to the raw retrieval set.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Passage Deduplication and Redundancy Removal Prompt. Validate each before calling the model to prevent malformed requests and silent failures.

PlaceholderPurposeExampleValidation Notes

[PASSAGE_SET]

The list of retrieved passages to deduplicate, each with a unique ID and full text content.

{"passages": [{"id": "p1", "text": "The cat sat on the mat."}, {"id": "p2", "text": "A cat was sitting on a mat."}]}

Must be a valid JSON array. Each object requires non-empty 'id' (string) and 'text' (string) fields. Reject if array is empty or contains duplicate IDs.

[SIMILARITY_THRESHOLD]

The minimum semantic similarity score (0.0 to 1.0) at which two passages are considered near-duplicates and flagged for merging.

0.85

Must be a float between 0.0 and 1.0. Values below 0.7 produce excessive false merges; values above 0.95 miss genuine duplicates. Default to 0.85 if not specified.

[MERGE_STRATEGY]

Instruction for how to handle near-duplicate passages: 'keep_longest', 'keep_first', 'keep_most_complete', or 'merge_and_note'.

keep_most_complete

Must be one of the four enumerated string values. Reject unknown strategies. 'merge_and_note' requires the model to produce a [MERGE_NOTES] field in the output.

[OUTPUT_SCHEMA]

The expected JSON structure for the deduplicated result, including required fields and their types.

{"deduplicated_passages": [], "removed_passages": [], "merge_notes": []}

Must be a valid JSON Schema or example object. Validate that 'deduplicated_passages' is a required array field. Schema mismatch is the most common cause of parse failures downstream.

[MAX_OUTPUT_PASSAGES]

The maximum number of passages to retain after deduplication. Used to enforce a hard cap when the input set is large.

20

Must be a positive integer. If null, no cap is applied. When set, the model must prioritize retaining the most information-dense passages. Validate that output count does not exceed this value.

[LANGUAGE_HINT]

Optional ISO 639-1 language code to improve semantic comparison accuracy for non-English passage sets.

en

Must be a valid two-letter language code or null. When provided, the model should use language-appropriate similarity heuristics. Null is acceptable for multilingual sets but may reduce accuracy.

[GROUND_TRUTH_PAIRS]

Optional list of known duplicate pairs for evaluation. Used to measure recall against human-labeled duplicates.

[{"id1": "p1", "id2": "p2", "label": "duplicate"}]

If provided, each object must contain 'id1', 'id2', and 'label' fields. 'label' must be 'duplicate' or 'not_duplicate'. Use this to compute recall and false-merge rate post-generation. Null allowed when no ground truth exists.

PROMPT PLAYBOOK

Implementation Harness Notes

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

The deduplication prompt should sit between retrieval and answer generation in your RAG pipeline. After your retriever returns a set of passages, batch them into groups that fit within your model's context window—typically 10–30 passages per call depending on passage length. The prompt expects a list of passages with IDs, so assign a stable identifier (e.g., doc_7_chunk_3) to each passage before calling the prompt. This ID is critical for traceability: downstream components need to know which original passages were merged or retained.

Wrap the prompt call in a validation layer that checks the output schema before passing results to the answer generator. The prompt returns a JSON object with kept_passages and merge_notes. Validate that every kept_passage_id references an ID that existed in the input, that no passage ID appears in both kept_passages and merge_notes.merged_ids, and that every merged_id in merge_notes also existed in the input. If validation fails, retry once with the same input and a stronger constraint instruction appended to the prompt. If the second attempt also fails, log the failure and fall back to using the raw, undeduplicated passage set with a warning flag.

For model choice, use a model with strong instruction-following and JSON output capabilities. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all perform well on this structured deduplication task. Avoid smaller models (under 7B parameters) for production use unless you've calibrated them extensively—they tend to over-merge dissimilar passages or miss near-duplicates with minor wording differences. If cost is a concern, consider using a cheaper model for the initial deduplication pass and a stronger model as a judge to spot-check 5–10% of outputs for false merges and missed duplicates.

Logging and observability are essential. For every deduplication call, log: the input passage count, the output passage count, the merge decisions (which IDs were merged and why), the model used, latency, and any validation failures. This data lets you monitor deduplication ratios over time and detect drift—for example, if your retriever starts returning more near-duplicates from a new data source, you'll see the merge rate spike. Set up an alert if the deduplication ratio (output count / input count) drops below 0.3 or exceeds 0.95, as both extremes suggest the prompt may be misbehaving.

For evaluation, maintain a golden dataset of passage sets with known duplicates. Run the prompt against this dataset weekly or on every prompt change. Measure precision (did we avoid merging passages that aren't actually duplicates?) and recall (did we catch all the duplicates we should have?). A false merge—combining two distinct passages—is more harmful than a missed duplicate, so weight precision higher in your acceptance criteria. If your application is in a regulated domain, route all merge decisions to a human review queue for the first month of production to calibrate trust before allowing automated deduplication to feed directly into answer generation.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when deduplicating passages and how to guard against it.

01

False Merges of Distinct Passages

What to watch: The prompt merges passages that share keywords but cover different facts, entities, or time periods. This collapses distinct evidence into a single, misleading record. Guardrail: Require the model to output a merge_confidence score and a distinction_note explaining why passages were merged. Flag any merge with confidence below 0.85 for human review.

02

Missed Near-Duplicates with Synonym Drift

What to watch: Passages expressing the same fact with different terminology, paraphrases, or entity aliases are left as separate entries. This inflates context windows with redundant information. Guardrail: Include a pre-processing step that normalizes entities and expands synonyms before deduplication. Add eval test cases with known paraphrase pairs to measure recall.

03

Loss of Granularity in Merged Output

What to watch: The merged passage summary omits specific numbers, dates, names, or qualifiers present in the originals. The output becomes vaguer than any single input passage. Guardrail: Add an output constraint requiring that all quantitative values, named entities, and temporal markers from source passages appear in the merged result. Validate with a field-level preservation check.

04

Order-Dependent Deduplication Bias

What to watch: The model preferentially keeps the first or last passage in a set of near-duplicates, discarding better-phrased or more complete versions elsewhere in the list. Guardrail: Randomize passage order before deduplication and run the prompt twice. Compare outputs for consistency. If results differ, surface the unstable passages for manual resolution.

05

Context Window Overflow from Merge Notes

What to watch: Verbose merge justifications and distinction notes consume more tokens than the redundancy they were meant to save, defeating the purpose of deduplication. Guardrail: Set a hard token budget for merge notes. If the total output exceeds the original passage set size, fall back to a simpler deduplication method or truncate notes to key identifiers only.

06

Silent Dropping of Low-Similarity Passages

What to watch: The model removes passages it judges as low relevance during deduplication, even though the task is only to remove duplicates. This conflates deduplication with filtering and loses potentially useful context. Guardrail: Explicitly instruct the model that the ONLY valid reason for removal is near-duplicate content. Require a kept or merged status for every input passage. Validate that the output passage count equals the input count minus confirmed duplicates.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the deduplication prompt's output quality before shipping. Each criterion targets a known failure mode in passage deduplication systems. Run these checks on a golden dataset of 50-100 passage sets with known duplicates.

CriterionPass StandardFailure SignalTest Method

Duplicate Recall

All known near-duplicate pairs in the golden set are identified and merged

A known duplicate pair appears as two separate entries in the output

Compare output passage IDs against labeled duplicate pairs; calculate recall as true positives / (true positives + false negatives)

False Merge Rate

No more than 5% of merged groups contain passages that are not actually duplicates

Two semantically distinct passages are merged into one group with a merge note

Human review of all merge groups; flag any group where passages discuss different topics or make contradictory claims

Merge Note Quality

Every merge group includes a specific, accurate reason for merging that cites the overlapping content

Merge note is generic (e.g., 'similar content'), missing, or describes overlap that does not exist

LLM-as-judge evaluation: present merge note alongside both passages and ask if the noted overlap is factually present

Information Preservation

The deduplicated output retains all unique facts present in the input set

A fact present only in one passage of a merged group is absent from the representative passage or merge note

Extract all atomic claims from input and output; check that every input claim appears in either the representative passage or the merge note

Representative Passage Selection

The chosen representative passage for each merge group is the most complete and well-formed version

The representative passage is shorter, less coherent, or missing details present in another passage from the same group

Pairwise comparison by human evaluator or LLM judge: is the selected representative at least as complete as the alternatives?

Non-Duplicate Preservation

All unique, non-duplicate passages appear unchanged in the output

A passage with no duplicate is modified, truncated, or omitted from the output

Exact match check: for each input passage with no known duplicate, verify an identical passage exists in the output

Output Schema Compliance

Output strictly matches the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing fields, extra fields, wrong types, or malformed JSON that fails schema validation

Automated JSON Schema validation against the expected schema; reject on any validation error

Edge Case: Partial Overlap

Passages with partial but incomplete overlap are kept separate with no merge, or merged only if overlap exceeds the [SIMILARITY_THRESHOLD]

Passages sharing only a minor detail are incorrectly merged, or passages with substantial overlap are incorrectly kept separate

Test with a curated set of partial-overlap pairs at varying similarity levels; measure precision and recall at the configured threshold

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small sample of 10-20 passage pairs. Use the prompt as-is with a frontier model (GPT-4o, Claude 3.5 Sonnet) and manually review outputs. Skip formal schema validation initially—just check that deduplication decisions make sense. Focus on tuning the [SIMILARITY_THRESHOLD] placeholder and the merge-note format until the output feels reliable.

Prompt modification

  • Remove strict output schema requirements; accept natural-language merge notes.
  • Lower the threshold for flagging near-duplicates to surface more candidates for review.
  • Add: If uncertain whether two passages are duplicates, mark them for human review and explain why.

Watch for

  • Over-merging: passages with different details collapsed into one.
  • Under-merging: near-duplicates left as separate entries.
  • Merge notes that lose critical nuance from the original passages.
  • No baseline to measure improvement against.
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.