This prompt is designed for search engineers and RAG pipeline builders who need to identify and classify semantic overlap across retrieved chunks before those chunks enter the answer-generation step. It works on a set of retrieved passages and produces a structured overlap report that classifies each pair as an exact duplicate, a paraphrase, or a partial overlap, along with a recommended retention decision. Use this when retrieval returns multiple chunks from the same document, when dense embeddings pull in near-identical passages from different sources, or when you need to reduce context-window bloat without losing unique information.
Prompt
Near-Duplicate Detection Prompt for Retrieved Chunks

When to Use This Prompt
A practical guide for search engineers and RAG pipeline builders to identify and classify semantic overlap across retrieved chunks before answer generation.
This prompt is not a general-purpose deduplication tool for entire document corpora. It assumes you have already retrieved a candidate set and need pairwise semantic comparison, not fuzzy hashing or syntactic dedup. The ideal user is a search engineer or AI engineer who has a working retrieval pipeline and is now tuning the quality of the context that enters the answer-generation step. You should have a concrete set of 5–50 retrieved passages per query, each with a unique ID and source metadata. The prompt expects you to supply these passages in a structured format, and it will return a JSON report you can use programmatically to filter, merge, or flag passages before synthesis.
Do not use this prompt when you need to deduplicate an entire document corpus at index time—that requires different techniques like document fingerprinting or embedding clustering. Do not use it when your retrieval returns fewer than three passages, as pairwise comparison adds latency without meaningful benefit. Do not use it when your passages are extremely long (over 2,000 tokens each), as the model may struggle to compare full-text semantics accurately. For those cases, consider first extracting key claims or summaries from each passage, then running this prompt on the compressed representations. The next section provides the copy-ready template you can adapt for your pipeline.
Use Case Fit
Where the Near-Duplicate Detection Prompt works well, where it breaks, and the operational prerequisites for production use.
Good Fit: High-Recall Retrieval Pipelines
Use when: your retrieval system returns top-k chunks from a dense vector store and you observe the same paragraph appearing in multiple results with slight text variations. Guardrail: Run this prompt before answer generation to collapse redundant evidence and prevent the model from double-weighting the same fact.
Bad Fit: Real-Time Streaming or Sub-100ms Latency Budgets
Avoid when: you need context cleaning in under 100ms or are operating on a per-token streaming path. Guardrail: Offload deduplication to a preprocessing step or use deterministic simhash/MinHash for latency-sensitive paths. Reserve LLM-based overlap classification for offline or async pipelines.
Required Inputs: Chunk Pairs with Metadata
What you need: a list of chunk pairs with unique IDs, full text content, source document identifiers, and retrieval scores. Guardrail: Without source metadata, the prompt cannot resolve which version to keep. Always include document date, authority level, or version tags when available to inform retention decisions.
Operational Risk: Over-Aggressive Deduplication
Risk: removing chunks that share surface-level vocabulary but contain distinct facts, especially in technical or legal documents where precise wording differences matter. Guardrail: Always pair this prompt with an over-filtering risk assessment step that checks whether answer-critical evidence was removed. Set a conservative threshold for partial overlaps.
Operational Risk: Source Provenance Loss
Risk: when merging or removing near-duplicate chunks, the system loses track of which original documents contributed to the final context, breaking citation chains. Guardrail: Use a provenance tracking prompt after deduplication to maintain attribution mappings. Never discard source references without logging the merge decision for audit.
Scale Consideration: Pairwise Comparison Explosion
Risk: running all-pairs comparison on large retrieval sets creates O(n²) LLM calls, blowing up cost and latency. Guardrail: Pre-filter with embedding cosine similarity or locality-sensitive hashing to identify candidate pairs before invoking the LLM. Only send high-similarity candidates to the near-duplicate detection prompt.
Copy-Ready Prompt Template
A copy-ready prompt template for detecting near-duplicate chunks in a retrieved context set, with structured overlap classification and retention decisions.
This prompt template is designed to be pasted directly into your orchestration layer. It instructs the model to analyze a set of retrieved chunks, identify pairs with high semantic overlap, and classify each pair as an exact duplicate, paraphrase, or partial overlap. The output is a structured JSON report that your application can parse to deduplicate the context window before answer generation, reducing token waste and improving answer quality by removing redundant information.
textYou are a retrieval quality analyzer. Your task is to examine a set of retrieved text chunks and identify pairs that are near-duplicates. For each pair with significant semantic overlap, classify the relationship and recommend which chunk to retain. ## INPUT [CHUNKS] ## INSTRUCTIONS 1. Compare every pair of chunks for semantic overlap. Ignore pairs where overlap is trivial (e.g., sharing only common stop words or domain boilerplate). 2. For each pair with meaningful overlap, classify the relationship as one of: - `exact_duplicate`: The chunks convey identical information with only minor wording differences. - `paraphrase`: The chunks convey the same core information but with different phrasing, structure, or level of detail. - `partial_overlap`: The chunks share some information but each also contains unique content not present in the other. 3. For each classified pair, recommend which chunk to retain based on: - Information completeness (prefer the chunk with more unique detail). - Authority (prefer chunks with clearer provenance or more recent dates if available). - Clarity (prefer well-formed, self-contained chunks over fragmented ones). 4. If two chunks are exact duplicates, retain the first occurrence by position. 5. Do not flag pairs where the overlap is below the threshold defined in [OVERLAP_THRESHOLD]. ## CONSTRAINTS - Do not modify chunk content. Only analyze and classify. - If no pairs meet the overlap threshold, return an empty overlaps array. - Preserve the original chunk IDs exactly as provided in the input. - If [INCLUDE_CHUNK_TEXT] is false, reference chunks by ID only in the output. ## OUTPUT SCHEMA Return valid JSON matching this schema: { "overlaps": [ { "chunk_a_id": "string", "chunk_b_id": "string", "overlap_type": "exact_duplicate | paraphrase | partial_overlap", "overlap_summary": "Brief description of what information the chunks share.", "unique_to_a": "What chunk A contains that B does not, or null if exact_duplicate.", "unique_to_b": "What chunk B contains that A does not, or null if exact_duplicate.", "retention_decision": "keep_a | keep_b | keep_both", "retention_reason": "One-sentence justification for the retention decision." } ], "total_chunks_analyzed": number, "total_overlap_pairs_found": number, "recommended_retain_count": number }
To adapt this prompt, replace [CHUNKS] with your retrieved passages formatted as an array of objects, each containing an id and text field. Set [OVERLAP_THRESHOLD] to a value like "partial_overlap" if you want to catch all levels of redundancy, or "exact_duplicate" if you only want to remove identical content. The [INCLUDE_CHUNK_TEXT] boolean controls whether the output repeats chunk text—set to false in production to keep the response compact. After receiving the output, your application should parse the overlaps array, apply the retention_decision for each pair, and assemble a deduplicated context set using only the retained chunks. Always validate the output against the schema before using it to prune context, and log any schema violations for prompt tuning.
Prompt Variables
Required inputs for the near-duplicate detection prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CHUNK_PAIR_LIST] | Array of chunk pairs to evaluate for near-duplicate overlap. Each pair contains two text chunks and their metadata. | [{"chunk_a": {"id": "doc12_chunk3", "text": "The cat sat on the mat..."}, "chunk_b": {"id": "doc7_chunk1", "text": "A cat was sitting on the mat..."}}] | Must be valid JSON array with 1-50 pairs. Each pair requires chunk_a and chunk_b objects, each with non-empty id and text fields. Reject if text fields are empty or ids are missing. |
[OVERLAP_CLASSES] | Taxonomy of overlap categories the model must use for classification. Defines the boundary between exact duplicate, paraphrase, and partial overlap. | ["exact_duplicate", "paraphrase", "partial_overlap", "distinct"] | Must be a non-empty array of 2-6 unique string labels. Validate that the set includes at least one duplicate class and one non-duplicate class. Default set shown in example is recommended. |
[SIMILARITY_THRESHOLD] | Minimum semantic similarity score required to flag a pair as near-duplicate. Pairs below this threshold are classified as distinct. | 0.75 | Must be a float between 0.0 and 1.0. Values below 0.5 produce excessive false positives; values above 0.95 risk missing paraphrases. Recommend 0.70-0.85 for production. |
[RETENTION_RULE] | Decision rule for which chunk to retain when overlap is detected. Specifies priority logic for retention. | "retain_longer_chunk" | Must be one of: retain_longer_chunk, retain_first_in_list, retain_higher_source_authority, retain_newer_timestamp. If source_authority or timestamp is used, corresponding metadata fields must be present in chunk objects. |
[OUTPUT_SCHEMA] | JSON schema describing the expected output structure for each pair evaluation. | {"pair_index": "int", "overlap_class": "string", "overlap_score": "float", "retention_decision": "string", "rationale": "string"} | Must be a valid JSON Schema object or example structure. Validate that required fields include pair_index, overlap_class, overlap_score, and retention_decision. Reject schemas missing a rationale or explanation field for auditability. |
[MAX_PAIR_TEXT_LENGTH] | Maximum character length per chunk text before truncation. Prevents token overflow when chunks are very long. | 2000 | Must be a positive integer. Recommended range 1000-4000 characters. Validate that chunk texts exceeding this limit are truncated with an ellipsis marker before prompt assembly. Log truncation events for observability. |
[SOURCE_AUTHORITY_MAP] | Optional mapping of source identifiers to authority scores, used when retention_rule is retain_higher_source_authority. | {"doc12": 0.9, "doc7": 0.6} | Must be a valid JSON object mapping source_id strings to float scores between 0.0 and 1.0. Required only when RETENTION_RULE is retain_higher_source_authority. Validate that every chunk source_id has a corresponding entry or set a default of 0.5. |
[LANGUAGE_HINT] | ISO 639-1 language code for the primary language of the chunks. Helps the model apply language-appropriate paraphrase detection. | "en" | Must be a valid two-letter ISO 639-1 code. Default to "en" if not specified. Validate against a known language code list. Mismatched language hints degrade paraphrase detection accuracy. |
Implementation Harness Notes
How to wire the near-duplicate detection prompt into a RAG pipeline with validation, retries, and structured output handling.
This prompt is designed to be called as a pre-processing step inside your retrieval pipeline, after chunks are returned from your vector store or search index but before they are assembled into the final context window for answer generation. The typical integration point is a deduplicate_context function that accepts a list of retrieved chunks and returns a filtered, deduplicated list with overlap annotations. Because the prompt operates on pairs of chunks, you will need to implement a pairing strategy—either all-pairs (O(n²)) for small retrieval sets (k ≤ 20) or a sliding-window approach that only compares chunks with high embedding cosine similarity (≥ 0.85) for larger sets. The prompt expects two chunks at a time, so your harness should iterate over candidate pairs, collect the structured overlap reports, and then apply the retention decisions to produce the final deduplicated context set.
Validation and structured output handling are critical here because downstream answer generation depends on the deduplication decisions. Parse the model's JSON output against a strict schema that checks for required fields: chunk_a_id, chunk_b_id, overlap_type (must be one of exact_duplicate, paraphrase, partial_overlap, no_overlap), overlap_score (0.0–1.0), overlapping_spans (array of text excerpts), and retention_decision (must be one of keep_both, keep_a, keep_b, merge). If the model returns invalid JSON, missing fields, or an unrecognized enum value, retry once with the validation error injected into the prompt as a [PREVIOUS_ERROR] constraint. After two failures, log the pair for human review and default to keep_both to avoid silent evidence loss. For high-stakes domains like legal or clinical RAG, route all merge decisions to a human review queue before final context assembly.
Model choice matters. This is a classification and structured extraction task that benefits from models with strong instruction-following and JSON output reliability. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all perform well, but smaller models (e.g., GPT-4o-mini, Claude Haiku) may struggle with the overlapping_spans extraction and produce hallucinated span text. If you are using a smaller model for cost reasons, add a post-processing step that verifies each returned span actually appears in the source chunks using exact substring matching, and discard any spans that fail this check. For latency-sensitive pipelines processing many chunk pairs, consider batching up to 5 pairs in a single prompt call with a numbered list format, but be aware that batching increases the risk of cross-pair confusion—add explicit pair delimiters and validate that the output contains exactly one report per input pair.
Logging and observability should capture: the number of chunk pairs evaluated, the distribution of overlap types, the number of chunks retained vs. removed, and any validation failures or retries. Emit these metrics to your existing monitoring stack so you can track deduplication behavior over time and detect drift—for example, if exact_duplicate rates suddenly spike, your retrieval pipeline may have introduced a chunking bug. Store the full overlap reports alongside the final deduplicated context in your trace store so that downstream answer generation failures can be debugged by replaying the exact context that was assembled. When a user reports a missing fact in an answer, you can trace back through the deduplication decisions to see if critical evidence was incorrectly classified as a duplicate and removed.
What to avoid: Do not run this prompt on every retrieval call if your chunking strategy and document collection are static—cache deduplication decisions per document pair and only re-evaluate when chunks change. Do not use the merge retention decision unless you have a separate synthesis step that can faithfully combine overlapping chunks without introducing hallucinated content; in most cases, keep_a (retain the more complete or authoritative chunk) is safer. Finally, do not skip the span verification step if you are using a model that occasionally hallucinates—a single fabricated overlapping span can cause you to incorrectly merge or discard chunks, silently degrading answer quality in ways that are hard to detect without explicit eval gates.
Expected Output Contract
Define the structured overlap report fields, types, and validation rules so the model output can be parsed, validated, and consumed by downstream deduplication logic.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
overlap_report | JSON object | Top-level key must exist and be a valid JSON object. Parse check. | |
overlap_report.chunk_pairs | Array of objects | Must be a non-empty array. Schema check: each element must contain chunk_a_id, chunk_b_id, overlap_class, overlap_score, and retention_decision. | |
overlap_report.chunk_pairs[].chunk_a_id | String | Must match an input chunk ID from [RETRIEVED_CHUNKS]. Citation check against input. | |
overlap_report.chunk_pairs[].chunk_b_id | String | Must match an input chunk ID from [RETRIEVED_CHUNKS] and differ from chunk_a_id. Citation check against input. | |
overlap_report.chunk_pairs[].overlap_class | Enum string | Must be one of: exact_duplicate, paraphrase, partial_overlap. Enum check. | |
overlap_report.chunk_pairs[].overlap_score | Float between 0.0 and 1.0 | Must be a number. Range check: 0.0 <= score <= 1.0. Higher score indicates greater semantic overlap. | |
overlap_report.chunk_pairs[].retention_decision | Enum string | Must be one of: keep_a, keep_b, keep_both, merge. Enum check. keep_a and keep_b must reference a valid chunk ID from the pair. | |
overlap_report.summary.total_pairs_evaluated | Integer | Must equal the length of chunk_pairs array. Count check. |
Common Failure Modes
Near-duplicate detection prompts fail in predictable ways. Here are the most common failure modes and how to guard against them before they reach production.
Semantic Blindness to Structural Similarity
What to watch: The model treats two chunks as duplicates because they share topic and vocabulary, even when they contain different facts, dates, or entities. This is common in legal and financial documents where boilerplate language surrounds distinct clauses. Guardrail: Add explicit instruction to compare factual payloads, not framing language. Require the output to cite the specific differing claim before classifying as duplicate.
Threshold Instability Across Document Types
What to watch: A similarity threshold that works for technical documentation fails on narrative text or vice versa. The model applies the same standard to all chunk pairs, causing over-deduplication in dense technical content and under-deduplication in verbose prose. Guardrail: Include a document-type context field in the prompt and calibrate overlap definitions per type. Log threshold decisions by document category for eval.
Partial Overlap Misclassification
What to watch: Chunks with 40-60% overlap are the hardest to classify. The model oscillates between 'paraphrase' and 'partial overlap' inconsistently, making retention decisions unreliable. This is the most common source of downstream answer hallucination. Guardrail: Add a confidence score requirement for partial overlap classifications. Route low-confidence decisions to a secondary verification prompt or human review queue.
Ordering Bias in Pairwise Comparison
What to watch: When comparing chunk A to chunk B, the model's classification changes depending on which chunk is presented first. The first chunk anchors the comparison, causing asymmetric overlap judgments. Guardrail: Run bidirectional comparisons and flag pairs where the classification differs by direction. Use a symmetric overlap score or average the two directional results before making retention decisions.
Retention Decision Drift in Large Sets
What to watch: When processing many chunk pairs in a single prompt, the model's retention criteria drift. Early pairs get strict treatment while later pairs get lenient treatment as the model loses track of the standard. Guardrail: Batch comparisons into small groups of 5-10 pairs per prompt call. Include the overlap criteria as a repeated anchor at the top of each batch. Validate retention consistency across batches in eval.
Information Loss from Aggressive Deduplication
What to watch: The model correctly identifies overlap but recommends removing the chunk that contains the most complete or authoritative version of the information. The retained chunk is missing critical qualifiers, dates, or source attribution present in the removed chunk. Guardrail: Add a coverage-preservation check after deduplication. Compare the retained set against the original for missing entities, dates, and claims. Flag gaps above a coverage threshold for re-inclusion.
Evaluation Rubric
Criteria for testing the near-duplicate detection prompt before integrating it into a production RAG pipeline. Each row defines a pass standard, a failure signal, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Output Schema Validity | Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present for every chunk pair | JSON parse error, missing required fields, or unexpected data types in overlap report | Schema validation script run against 50 test cases with known overlap types |
Duplicate Classification Accuracy | Exact duplicates correctly classified with overlap_type=exact and overlap_score >= 0.95 for identical chunks | Identical chunks classified as paraphrase or partial overlap, or overlap_score below 0.90 for exact matches | Golden dataset of 30 known-exact chunk pairs verified by human annotation |
Paraphrase Detection Recall | Paraphrased pairs detected with overlap_type=paraphrase and overlap_score between 0.70 and 0.94 for semantically equivalent but reworded chunks | Paraphrased pairs missed entirely or classified as partial_overlap with score below 0.50 | Synthetic paraphrase test set with 20 pairs generated from source documents and verified by two reviewers |
Partial Overlap Boundary | Chunks sharing some facts but not full semantic equivalence classified as partial_overlap with overlap_score between 0.30 and 0.69 | Partial overlaps misclassified as duplicates or paraphrases, or scored above 0.70 | Boundary test set of 25 chunk pairs with controlled fact overlap ratios from 20% to 60% |
Non-Overlap Discrimination | Unrelated chunks correctly classified with overlap_type=none and overlap_score below 0.20 | Unrelated chunks flagged as partial_overlap or scored above 0.30 | Random negative sampling of 40 chunk pairs from different document topics |
Retention Decision Correctness | retain_chunk field correctly identifies the more complete or authoritative version when duplicates detected | Retained chunk is shorter, less complete, or less authoritative than the discarded alternative | Manual review of 20 duplicate pairs comparing retention decisions against source document quality |
Token Budget Compliance | Prompt completes within [MAX_OUTPUT_TOKENS] for input sets up to [MAX_CHUNK_PAIRS] pairs | Output truncated mid-JSON or missing pair analyses when input approaches maximum pair count | Load test with 10, 25, and 50 chunk pairs measuring output completeness and token consumption |
Edge Case: Near-Identical with Minor Differences | Chunks differing only by a date, number, or name classified as exact or paraphrase with difference_notes populated | Minor-difference chunks classified as partial_overlap or none, or difference_notes field left empty | Curated edge case set of 15 near-identical pairs with controlled single-fact variations |
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 set of 10–20 chunk pairs. Use a frontier model (GPT-4o, Claude 3.5 Sonnet) with temperature 0. Remove the strict JSON schema enforcement and let the model output a human-readable overlap report first. Iterate on the overlap categories (exact duplicate, paraphrase, partial overlap) until the classifications match your intuition.
Prompt modification
Replace the structured [OUTPUT_SCHEMA] block with: Output a bulleted list for each pair: (1) overlap type, (2) one-sentence explanation, (3) keep/remove recommendation.
Watch for
- The model collapsing "paraphrase" and "partial overlap" into one category
- Overly cautious retention recommendations (keeping too many near-duplicates)
- Inconsistent overlap thresholds across runs

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