Inferensys

Prompt

Evidence Deduplication Prompt to Reclaim Tokens

A practical prompt playbook for using Evidence Deduplication Prompt to Reclaim Tokens 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

Identify when semantic deduplication of retrieved evidence is the right tool versus when simpler heuristics or upstream retrieval fixes are more appropriate.

This prompt is designed for the context assembly layer of a RAG pipeline, specifically the moment after retrieval and before final answer generation. Its job-to-be-done is to reclaim context window space by identifying and merging semantically redundant passages that were retrieved from dense vector stores, keyword indexes, or hybrid search systems. The ideal user is an AI engineer or RAG system builder who observes that their retrieved context blocks contain overlapping or near-identical information, leading to wasted tokens, increased latency, and diluted model attention. You should use this prompt when your retrieval system returns multiple chunks that say essentially the same thing in different words, when you need to maximize evidence density per token, and when you require a human-readable merge report to audit what was consolidated.

Do not use this prompt when the redundancy problem can be solved upstream with better retrieval parameters. If your vector store is returning exact duplicate documents, fix the ingestion deduplication logic first. If your hybrid search is returning the same passage from both vector and keyword indexes, add a simple exact-match or hash-based deduplication step before the LLM call—it is cheaper and faster. This prompt is also inappropriate when passages contain complementary details that appear similar but are factually distinct; merging them would lose critical nuance. Reserve this prompt for cases where semantic judgment is required to decide whether two passages are true duplicates, near-duplicates with minor wording differences, or distinct pieces of evidence that happen to share vocabulary. The prompt belongs in the context assembly layer precisely because it requires the model's semantic understanding to make these distinctions.

Before deploying this prompt, establish a baseline: measure your current context window utilization, average tokens per evidence block, and answer quality metrics. After integrating the deduplication step, compare token savings against any change in answer completeness or factual accuracy. The prompt includes a token savings report in its output schema, which you should log and monitor over time. If you observe that deduplication is consistently saving fewer than 10% of tokens, reconsider whether the upstream retrieval deduplication heuristics would be more cost-effective. If you observe answer quality degradation after deduplication, check whether the model is over-merging distinct passages—this is the most common failure mode and requires tuning the deduplication threshold in the prompt's constraints.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Evidence Deduplication prompt works, where it fails, and the operational prerequisites for production use.

01

Good Fit: High-Redundancy RAG Pipelines

Use when: your retrieval step returns multiple passages with substantial semantic overlap, and you need to reclaim tokens before generation. Guardrail: always run a semantic similarity check before deduplication to avoid collapsing distinct but similarly worded evidence.

02

Bad Fit: Single-Source or Sparse Retrieval

Avoid when: the retriever returns only one or two passages, or when every passage contains unique, non-overlapping information. Guardrail: implement a minimum passage count threshold (e.g., >3 passages) before invoking deduplication to prevent unnecessary latency and potential information loss.

03

Required Input: Source-Annotated Evidence Blocks

What to watch: the prompt requires each evidence block to carry a unique source identifier and retrieval score. Guardrail: validate that your retrieval pipeline attaches stable IDs and relevance scores to every passage before assembly. Missing IDs will cause merge notes to become untraceable.

04

Operational Risk: Silent Information Loss

Risk: the model may merge passages and drop a unique detail that appears in only one source, treating it as redundant. Guardrail: implement a post-deduplication eval that checks whether all unique claims from the original set appear in the deduplicated set, and flag any missing claims for human review.

05

Operational Risk: Answer Drift After Deduplication

Risk: the downstream generation step may produce a different answer from the deduplicated evidence than it would from the full set. Guardrail: run a consistency check by generating answers from both the original and deduplicated evidence sets, and measure semantic drift. Escalate if drift exceeds a defined threshold.

06

Cost-Benefit Threshold: Token Savings vs. Compute Overhead

What to watch: deduplication itself consumes tokens and adds latency. Guardrail: estimate token savings before invoking the prompt. Only run deduplication when projected savings exceed the cost of the deduplication call itself, factoring in both input and output tokens.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders that deduplicates retrieved evidence, produces merge notes, and reports token savings.

The prompt below is designed to be copied directly into your prompt assembly pipeline. It takes a set of retrieved passages, identifies semantic duplicates and near-duplicates, merges them into a single consolidated evidence block, and returns a structured report. The report includes the deduplicated evidence set, a merge log explaining which passages were combined, and a token savings summary. All placeholders are enclosed in square brackets. Replace each placeholder with your actual data and configuration before sending the prompt to the model.

text
You are an evidence deduplication engine operating inside a RAG pipeline. Your task is to process a set of retrieved passages, identify duplicates and near-duplicates, merge them into a single consolidated evidence set, and report your work.

## INPUT

**Retrieved Passages:**
[RETRIEVED_PASSAGES]

**Deduplication Threshold:** [SIMILARITY_THRESHOLD]
**Merge Strategy:** [MERGE_STRATEGY]
**Maximum Merged Passage Length (tokens):** [MAX_MERGED_TOKENS]

## TASK

1. Compare all passages pairwise and identify groups that convey the same factual content.
2. For each group of duplicates or near-duplicates, produce a single merged passage that:
   - Preserves all unique facts from the group.
   - Resolves minor contradictions by noting the conflict.
   - Drops redundant phrasing.
   - Stays within the maximum merged passage length.
3. Passages with no duplicates must be included unchanged.
4. Count the original tokens and the deduplicated tokens.

## OUTPUT SCHEMA

Return a valid JSON object with exactly this structure:

{
  "deduplicated_evidence": [
    {
      "passage_id": "merged_1",
      "text": "Consolidated passage text here.",
      "source_ids": ["original_id_3", "original_id_7"],
      "has_conflict": false,
      "conflict_note": null
    }
  ],
  "merge_log": [
    {
      "merged_into": "merged_1",
      "original_ids": ["original_id_3", "original_id_7"],
      "reason": "Near-duplicate with overlapping facts about product launch date."
    }
  ],
  "token_report": {
    "original_token_count": 1240,
    "deduplicated_token_count": 890,
    "tokens_saved": 350,
    "savings_percentage": 28.2
  },
  "unmerged_passages": [
    {
      "passage_id": "original_id_2",
      "text": "Unchanged passage text."
    }
  ]
}

## CONSTRAINTS

- Do not merge passages that contain different facts, even if they share a topic.
- If two passages contradict each other, merge them but set `has_conflict` to true and add a brief `conflict_note`.
- Never invent facts not present in the original passages.
- If no duplicates exist, return all passages in `unmerged_passages` and set `deduplicated_evidence` to an empty array.
- Count tokens using the same tokenizer your pipeline uses. If unknown, estimate conservatively.

## EXAMPLES

**Example Input:**
Passage A: "The product launched on March 3, 2024."
Passage B: "Launch occurred on March 3, 2024, with 10,000 initial users."
Passage C: "The CEO announced a new pricing tier in June."

**Example Output:**
{
  "deduplicated_evidence": [
    {
      "passage_id": "merged_1",
      "text": "The product launched on March 3, 2024, with 10,000 initial users.",
      "source_ids": ["A", "B"],
      "has_conflict": false,
      "conflict_note": null
    }
  ],
  "merge_log": [
    {
      "merged_into": "merged_1",
      "original_ids": ["A", "B"],
      "reason": "Passage B contains all facts from Passage A plus additional detail."
    }
  ],
  "token_report": {
    "original_token_count": 42,
    "deduplicated_token_count": 28,
    "tokens_saved": 14,
    "savings_percentage": 33.3
  },
  "unmerged_passages": [
    {
      "passage_id": "C",
      "text": "The CEO announced a new pricing tier in June."
    }
  ]
}

To adapt this prompt for your pipeline, replace [RETRIEVED_PASSAGES] with the raw passages from your retriever, formatted as a list with unique IDs. Set [SIMILARITY_THRESHOLD] to a value like "high", "medium", or "low" depending on how aggressively you want to merge. Choose a [MERGE_STRATEGY] such as "keep_longest", "union_of_facts", or "most_recent" to control how conflicting information is resolved. Set [MAX_MERGED_TOKENS] to prevent any single merged passage from dominating the context window. If your pipeline uses a specific tokenizer, replace the token counting instruction with a callout to your own token-counting utility and remove the estimation fallback. For high-stakes domains such as healthcare or legal review, add a human-review step before the deduplicated evidence is used downstream, and consider routing passages with has_conflict: true to a separate review queue.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Evidence Deduplication Prompt. Each placeholder must be populated before inference. Validation notes describe how to verify the input is well-formed and safe to use.

PlaceholderPurposeExampleValidation Notes

[RETRIEVED_PASSAGES]

JSON array of passage objects from the retrieval pipeline, each with id and text fields

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

Parse as JSON array. Reject if empty, null, or missing id/text keys. Max 50 passages to avoid token overflow.

[QUERY]

The original user question or search query that triggered retrieval

What did the cat sit on?

Non-empty string. Reject if null or whitespace-only. Log if query length exceeds 200 chars for anomaly detection.

[SIMILARITY_THRESHOLD]

Float between 0.0 and 1.0 controlling how aggressively near-duplicate passages are merged

0.85

Must be a float. Clamp to [0.5, 0.95] range. Lower values merge more aggressively and risk information loss.

[MAX_OUTPUT_PASSAGES]

Integer cap on the number of deduplicated passages to return

10

Must be a positive integer. Reject if > 50. If input count is below this, return all unique passages.

[OUTPUT_SCHEMA]

JSON schema describing the expected output structure for deduplicated results

{"type":"object","properties":{"deduplicated":{"type":"array"},"merge_notes":{"type":"array"},"token_savings":{"type":"object"}},"required":["deduplicated","merge_notes","token_savings"]}

Validate as valid JSON Schema draft-07. Reject if missing required fields: deduplicated, merge_notes, token_savings.

[TOKEN_COUNT_METHOD]

Enum specifying how to estimate token counts for savings calculation

"tiktoken_cl100k_base"

Must be one of: "tiktoken_cl100k_base", "character_estimate", "word_estimate". Default to "tiktoken_cl100k_base" if null. Log warning if using estimate methods in production.

[PRESERVE_SOURCE_IDS]

Boolean flag controlling whether original passage IDs are retained in merge notes for traceability

Must be true or false. If true, merge_notes must include source_ids array per merged passage. Required for audit and citation workflows.

[ABSTAIN_ON_CONFLICT]

Boolean flag controlling behavior when passages contain contradictory information

Must be true or false. If true, conflicting passages must not be merged and should be flagged in merge_notes. Requires human review if conflict count exceeds 3.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the evidence deduplication prompt into a RAG pipeline with validation, retries, and token accounting.

The evidence deduplication prompt is designed to sit between your retrieval step and your answer generation step. After you retrieve passages from your vector store, search index, or knowledge base, assemble them into the [RETRIEVED_EVIDENCE] placeholder. The prompt returns a deduplicated, merged evidence set with a token_savings estimate and merge_notes explaining what was combined. You then pass the deduplicated evidence into your downstream answer-generation prompt, reclaiming context window space for instructions, conversation history, or additional retrieval results.

Validation and retry logic: Parse the model's JSON output and validate that deduplicated_evidence is a non-empty array, each item has content and source_ids fields, and token_savings is a positive integer. If validation fails, retry once with the same input and an added [CONSTRAINT] that says 'Your previous output failed JSON schema validation. Return ONLY valid JSON matching the schema.' If the second attempt also fails, log the raw output, fall back to the original evidence set, and increment a dedup_failure metric. For high-stakes domains like healthcare or legal, route validation failures to a human review queue instead of silently falling back.

Model choice and latency: This task benefits from models with strong instruction-following and JSON output discipline. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all perform well. For cost-sensitive pipelines, smaller models like GPT-4o-mini or Claude 3 Haiku can work if you tighten the output schema and add a retry layer. Expect 1-3 seconds of added latency. Run this prompt in parallel with your answer-generation prompt only if you can afford the extra inference cost; otherwise, run it sequentially and cache deduplication results per evidence set hash.

Logging and observability: Log the input evidence count, output evidence count, token_savings, merge notes, and validation status to your observability platform. Attach a trace ID that links the retrieval step, deduplication step, and final answer step. This lets you measure token savings over time, detect when deduplication fails to reduce evidence (indicating your retrieval step may already be diverse enough), and debug answer quality regressions by comparing answers generated with deduplicated vs. original evidence.

When to skip this prompt: If your retrieval step already returns fewer than 3 passages, or if your total context utilization is below 50% of the model's context window, the token savings may not justify the added latency and inference cost. Similarly, if your downstream task requires verbatim citation of every retrieved passage (e.g., legal document review with mandatory source listing), deduplication could obscure which specific passage supports which claim. In those cases, pass the raw evidence directly to your answer prompt and rely on citation instructions to manage attribution.

PRACTICAL GUARDRAILS

Common Failure Modes

Evidence deduplication fails silently when the prompt merges distinct facts, drops minority evidence, or breaks downstream citations. These cards cover the most common production failure modes and how to guard against them.

01

Over-Merging Distinct Evidence

Risk: The model treats two similar but distinct passages as identical and merges them, losing a unique detail, date, or qualifier. Guardrail: Require the prompt to output a merge_notes field explaining why two passages were combined, and run a spot-check eval comparing merged output against original passage pairs.

02

Silent Information Loss

Risk: The deduplication prompt drops a passage that appears redundant but contains the only source for a specific claim. Guardrail: Add a post-dedup fact-coverage eval that extracts all claims from the deduplicated set and verifies each claim traces back to at least one retained passage.

03

Broken Downstream Citations

Risk: The deduplication step renumbers or removes passage IDs, causing citation markers in the final answer to point to missing or wrong sources. Guardrail: Output a source_mapping object that maps original passage IDs to deduplicated passage IDs, and validate citation targets before rendering the final response.

04

Token Savings Claimed Without Verification

Risk: The prompt reports token savings that don't match actual tokenizer counts, leading to budget overruns. Guardrail: Compute token counts independently using the target model's tokenizer before and after deduplication, and reject savings claims that deviate by more than 5%.

05

Dedup Prompt Drift on Long Contexts

Risk: When the evidence set is large, the model starts skipping passages or producing incomplete deduplication, especially in the middle of the context window. Guardrail: Chunk evidence into batches of 10-15 passages, deduplicate within each batch, then run a second cross-batch dedup pass with a strict token budget.

06

Answer Consistency Degradation

Risk: The downstream answer quality drops after deduplication because the model now works with compressed evidence that lost nuance. Guardrail: Run a paired eval comparing answer quality using the original evidence set vs. the deduplicated set on a held-out test suite, and block the dedup prompt if answer accuracy drops below threshold.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the Evidence Deduplication Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method to catch regressions early.

CriterionPass StandardFailure SignalTest Method

Token Reduction

Output token count is at least 20% lower than input evidence token count

Output is longer than input or reduction is below 20% threshold

Compare token counts of [INPUT_EVIDENCE] and [OUTPUT_DEDUPLICATED] using tiktoken or equivalent

Information Preservation

All unique facts from [INPUT_EVIDENCE] appear in [OUTPUT_DEDUPLICATED] or [MERGE_NOTES]

A fact present in input is absent from both deduplicated output and merge notes

Run fact-extraction eval on input and output; diff the fact sets; require 100% recall

Merge Note Completeness

Every deduplication decision is documented in [MERGE_NOTES] with source IDs and rationale

Two passages are merged in output but no corresponding merge note exists

Parse [MERGE_NOTES] for source ID pairs; verify each pair maps to a single passage in output

Answer Consistency

Answer generated from [OUTPUT_DEDUPLICATED] matches answer from [INPUT_EVIDENCE] within tolerance

Answers diverge on key claims, numbers, or entities

Run the same QA prompt on both evidence sets; compare answers using LLM judge with pairwise comparison

Source Traceability

Every passage in [OUTPUT_DEDUPLICATED] references at least one source ID from [INPUT_EVIDENCE]

Output contains a passage with no source ID or an invented source ID

Extract all source IDs from output; validate each exists in input source ID set

Hallucination Check

No new claims, entities, or numbers appear in [OUTPUT_DEDUPLICATED] that are absent from [INPUT_EVIDENCE]

Output introduces a fact not grounded in any input passage

Run claim extraction on output; verify each claim has a supporting span in input using NLI model or human review

Format Compliance

Output is valid JSON matching [OUTPUT_SCHEMA] with all required fields present

JSON parse fails or required field is missing or wrong type

Validate output against JSON schema; reject on parse error or schema violation

Edge Case: Single Passage

When [INPUT_EVIDENCE] contains one passage, output returns it unchanged with empty merge notes

Single passage is altered, summarized, or dropped

Unit test with single-passage input; assert output passage equals input passage and merge notes array is empty

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a smaller evidence set and lighter validation. Remove the strict [OUTPUT_SCHEMA] requirement and ask for a simple JSON list of deduplicated passages with merge notes. Focus on whether the model correctly identifies near-duplicates before adding production guardrails.

Prompt modification

  • Replace [OUTPUT_SCHEMA] with: Return a JSON object with two fields: "kept_passages" (array of unique passage strings) and "removed_passages" (array of objects with "passage" and "reason" fields).
  • Drop the [TOKEN_SAVINGS_REPORT] section initially.
  • Use a small [EVIDENCE_SET] of 5-8 passages with obvious duplicates.

Watch for

  • Over-aggressive deduplication that merges passages with different supporting facts
  • Missing merge notes when two passages are combined
  • Model treating paraphrases as duplicates when they contain complementary information
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.