This prompt is designed for knowledge engineers and infrastructure teams maintaining shared fact stores, blackboard systems, or agent-accessible memory across multi-agent systems. The core job-to-be-done is cleaning a structured memory store of redundant, near-duplicate, or semantically equivalent facts that accumulate when multiple agents write independently. It is not a general-purpose deduplication tool for unstructured text or document corpora. It assumes facts are already extracted and stored as structured entries with source attribution, a confidence score, and a unique identifier. The ideal user is an AI platform engineer or knowledge infrastructure operator who needs to reduce memory bloat, prevent conflicting beliefs, and maintain a single source of truth for downstream agents.
Prompt
Memory Deduplication Prompt for Redundant Facts

When to Use This Prompt
Identifies the specific job-to-be-done, the ideal user, required context, and clear boundaries for when this prompt should and should not be applied.
Use this prompt when your fact store exhibits symptoms of redundancy: multiple entries asserting the same core claim with minor wording differences, facts from different sources that are logically equivalent, or outdated entries that should be merged into a newer, higher-confidence version. The prompt produces structured merge or delete operations with explicit equivalence justifications, source provenance tracking, and confidence scores. It is designed to be wired into an automated pipeline where a batch of candidate facts is periodically reviewed for deduplication. The output is a set of deterministic operations—merge, delete, or keep—that can be applied programmatically to your store. A critical implementation detail is that this prompt requires a pre-filtered candidate set; feeding it the entire memory store at once will degrade performance and increase the risk of false merges. Instead, use a retrieval step to group facts by entity or topic before invoking this prompt.
Do not use this prompt for deduplicating raw documents, user-generated text, or conversational logs. It is not designed for fuzzy string matching across paragraphs of prose. It will fail if the input facts lack structured fields like fact_id, source_agent, confidence, or timestamp. It is also inappropriate for real-time, latency-sensitive agent loops; this is a batch hygiene operation, not a synchronous step in an agent's critical path. If your system requires real-time deduplication on write, implement a deterministic hash-based or embedding-distance check at ingestion time and reserve this prompt for periodic deep cleaning. Finally, this prompt does not resolve contradictory facts where both claims are plausible but incompatible—for that, use the Agent Belief Revision Prompt on Conflicting Evidence. The next step after understanding this boundary is to prepare your candidate fact set and review the prompt template for required placeholders.
Use Case Fit
Where the Memory Deduplication Prompt for Redundant Facts delivers value and where it introduces risk. Use these cards to decide if this prompt fits your shared memory pipeline before integrating it into production.
Good Fit: High-Volume Fact Ingestion
Use when: multiple agents or pipelines independently insert facts into a shared store, creating near-duplicate entries with minor wording differences. Guardrail: Run deduplication as a batch or streaming post-ingestion step with a confidence threshold before auto-merging.
Bad Fit: Single-Agent, Low-Volume Memory
Avoid when: only one agent writes to memory and fact volume is low. The overhead of running a deduplication prompt outweighs the benefit. Guardrail: Use simple exact-match or hash-based deduplication at the application layer instead.
Required Inputs: Source-Attributed Facts
Risk: deduplication without source provenance can merge facts from different origins, losing auditability. Guardrail: Require each fact entry to carry a source citation and ingestion timestamp before running deduplication. The prompt must output merge decisions with preserved provenance.
Operational Risk: False Merges
Risk: the model incorrectly merges two distinct facts that share surface-level similarity, creating a single inaccurate entry. Guardrail: Set a high similarity threshold for auto-merge. Route borderline cases to a human review queue with both original entries and the proposed merge justification.
Operational Risk: Stale Fact Propagation
Risk: deduplication merges a newer, corrected fact into an older, outdated entry, losing the correction. Guardrail: Always compare timestamps. The prompt must prefer the most recent fact as the merge target and flag timestamp conflicts for review.
Scale Limit: Batch Size and Latency
Risk: pairwise comparison of all facts in a large store is computationally expensive and slow. Guardrail: Use blocking keys or embedding similarity pre-filters to reduce the candidate pair set before invoking the LLM deduplication prompt. Set a maximum batch size and timeout.
Copy-Ready Prompt Template
A reusable prompt template for deduplicating redundant facts in shared agent memory stores, ready to paste into your memory maintenance workflow.
This prompt template is designed to be dropped directly into an agent memory maintenance pipeline. It expects a batch of fact entries from your shared memory store and produces a set of merge or delete operations for redundant or near-duplicate facts. The template uses square-bracket placeholders that you must replace with your actual data, schemas, and constraints before execution. Every placeholder is documented so you can wire it into your existing memory store API, validation layer, and audit trail.
textYou are a memory deduplication agent responsible for cleaning a shared agent memory store. Your task is to identify redundant, duplicate, or near-duplicate fact entries and produce merge or delete operations with clear equivalence justifications. ## INPUT You will receive a batch of fact entries from the shared memory store. Each entry has a unique ID, a fact statement, source attribution, a confidence score, and a timestamp. [INPUT] ## OUTPUT SCHEMA Return a JSON object with an "operations" array. Each operation must conform to this schema: { "operations": [ { "action": "merge" | "delete" | "keep", "primary_id": "string (the surviving fact ID for merge, or the fact ID for delete/keep)", "duplicate_ids": ["string (list of IDs to merge into primary or to delete)"], "merged_fact": "string (the consolidated fact statement, required for merge actions)", "equivalence_justification": "string (explain why these facts are equivalent, citing semantic overlap, contradiction, or temporal supersession)", "confidence_impact": "string (how the merge or delete affects overall confidence in the surviving fact: increased, decreased, unchanged)" } ], "unchanged_ids": ["string (list of fact IDs that require no action)"] } ## CONSTRAINTS [CONSTRAINTS] ## EXAMPLES [EXAMPLES] ## INSTRUCTIONS 1. Compare all facts pairwise for semantic equivalence, not just string similarity. Two facts are equivalent if they convey the same information even with different wording. 2. A fact is a near-duplicate if it adds no new information beyond what another fact already states, even if the wording differs. 3. When merging, produce a consolidated fact that preserves all unique information from the merged entries. Do not drop details that appear in only one of the duplicates. 4. If two facts contradict each other, flag the contradiction in the equivalence justification and prefer the fact with the higher confidence score and more recent timestamp. Do not silently merge contradictory facts. 5. If confidence scores differ across duplicates, the merged fact should reflect the highest confidence score and note the discrepancy. 6. If you are uncertain whether two facts are truly equivalent, default to "keep" for both and explain your uncertainty in the justification. 7. Source attributions must be preserved in the merged fact. If multiple sources contributed, list all of them. 8. Do not merge facts that refer to different entities, time periods, or contexts, even if the surface wording is similar. ## RISK LEVEL [RISK_LEVEL]
To adapt this template, replace each square-bracket placeholder with your actual data and rules. [INPUT] should contain your batch of fact entries serialized as JSON, with fields matching your memory store schema. [CONSTRAINTS] should specify domain-specific rules such as maximum batch size, forbidden merge categories, or required confidence thresholds. [EXAMPLES] should include 2–4 few-shot examples showing correct merge, delete, and keep decisions with justifications that match your domain's equivalence standards. [RISK_LEVEL] should be set to high, medium, or low to control whether the system requires human review before applying operations. For high-risk domains such as healthcare or finance, always set RISK_LEVEL to high and route all merge and delete operations to a human approval queue before writing back to the memory store. Validate the output against the schema before applying any operation, and log every deduplication decision with the original input batch ID for auditability.
Prompt Variables
Required inputs for the Memory Deduplication Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check correctness programmatically.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[MEMORY_ENTRIES] | Array of memory objects to scan for duplicates. Each object must include an id, content, and source. | [{"id": "mem-001", "content": "User prefers dark mode", "source": "settings_agent", "timestamp": "2024-01-15T10:00:00Z"}] | Validate JSON array structure. Each entry must have non-empty id and content fields. Reject if array is empty or contains malformed objects. |
[DEDUP_THRESHOLD] | Similarity score between 0.0 and 1.0 above which two entries are considered duplicates. | 0.85 | Must be a float between 0.0 and 1.0. Values below 0.7 risk false positives; values above 0.95 risk missed duplicates. Default 0.85 if not specified. |
[MERGE_STRATEGY] | Instruction for how to combine duplicate entries: keep_newest, keep_oldest, merge_content, or flag_for_review. | merge_content | Must match one of the allowed enum values. Invalid strategies should cause prompt rejection before execution. Use keep_newest for time-sensitive facts; flag_for_review for high-stakes domains. |
[OUTPUT_SCHEMA] | Expected JSON schema for the deduplication result, including operations array and justification fields. | {"operations": [{"action": "merge", "primary_id": "mem-001", "duplicate_ids": ["mem-045"], "merged_content": "...", "confidence": 0.92, "justification": "..."}]} | Validate against JSON Schema before sending. Required fields: action, primary_id, duplicate_ids, confidence, justification. Action must be one of merge, delete, keep_separate. |
[SOURCE_WEIGHTS] | Optional object mapping source names to reliability weights for conflict resolution during merges. | {"settings_agent": 0.9, "user_input": 1.0, "inference_agent": 0.6} | If provided, values must be floats between 0.0 and 1.0. Missing sources default to 0.5. Null allowed if no source weighting is needed. |
[MAX_DUP_GROUP_SIZE] | Maximum number of entries allowed in a single duplicate group before forcing human review. | 5 | Must be a positive integer. Groups exceeding this size should be split or escalated. Prevents runaway merges from collapsing too many distinct facts. |
[REQUIRE_CITATION] | Boolean flag indicating whether merge justifications must cite specific overlapping phrases or facts from source entries. | Must be true or false. When true, the eval harness checks that every justification field contains at least one quoted substring from each source entry involved in the merge. |
Implementation Harness Notes
How to wire the memory deduplication prompt into a production agent memory pipeline with validation, retries, and human review gates.
This prompt is designed to be called as a batch deduplication step within a shared memory maintenance pipeline, not as a real-time user-facing operation. The typical integration pattern is a scheduled job or a trigger fired after a configurable number of new memory writes. The caller assembles a batch of candidate memory entries—usually those sharing overlapping entity keys, time windows, or embedding clusters—and passes them as [MEMORY_ENTRIES]. The prompt returns a structured list of merge or delete operations, each with an equivalence justification. The application layer should never auto-apply these operations without validation.
Validation and safety checks are mandatory. Before applying any merge or delete operation, validate that the returned entry_ids exist in the current memory store and that no entry has been modified since the batch was assembled (optimistic concurrency check). Reject any operation where the equivalence_justification is empty, fewer than 10 words, or contains only generic phrases like 'they are the same.' For high-stakes knowledge bases, route all merge operations with confidence below 0.85 to a human review queue and auto-apply only delete operations where the target entry is a strict substring or older timestamp duplicate of the surviving entry. Log every applied and rejected operation with the full prompt payload, model response, validator results, and reviewer identity for auditability.
Model choice and retry strategy matter here. Use a model with strong structured output support (GPT-4o, Claude 3.5 Sonnet, or equivalent) and enforce the [OUTPUT_SCHEMA] via constrained generation or strict JSON mode. Set temperature=0 to minimize variance in equivalence judgments. If the response fails schema validation, retry once with the validation errors injected into [CONSTRAINTS] as explicit prohibitions. If the second attempt also fails, log the failure and escalate the entire batch to human review rather than silently dropping entries. For large memory stores, partition batches by entity cluster (e.g., same entity_id or document_source) and process partitions in parallel with a merge worker that resolves cross-partition conflicts by preferring the operation with the higher confidence score.
What to avoid: Do not use this prompt on memory entries that represent fundamentally different fact types (e.g., a user preference and a document summary) even if they share keywords—the prompt's similarity detection is semantic, not taxonomic, and will produce false merges. Do not run deduplication on actively written memory without a lock or lease on the affected entries. Do not treat the model's confidence score as a calibrated probability; use it only for relative ranking within a batch. Finally, always retain the original entries for at least one retention period after a merge so that incorrect deduplications can be rolled back with a state versioning and rollback prompt.
Expected Output Contract
Validated output fields for the memory deduplication prompt. Each field must pass the listed validation rule before the merge or delete operation is accepted by the downstream state store.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
operations | Array of objects | Must be a non-empty array. Each element must conform to the operation schema below. | |
operations[].action | Enum: merge | delete | Must be exactly 'merge' or 'delete'. No other values allowed. | |
operations[].primary_id | String (UUID) | Must match the canonical fact ID to retain. For delete actions, this is the surviving reference. Must exist in the input fact set. | |
operations[].duplicate_ids | Array of strings (UUIDs) | Must contain at least one ID. All IDs must exist in the input fact set. No ID may equal primary_id. | |
operations[].equivalence_justification | String | Must be 1-3 sentences explaining semantic equivalence. Cannot be empty or generic placeholder text like 'they are the same'. | |
operations[].confidence | Number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Operations with confidence below 0.7 must be flagged for human review before execution. | |
operations[].source_citations | Array of strings | If present, each citation must reference a source ID from the input context. Null or empty array is allowed only when no source evidence exists. | |
unmatched_fact_ids | Array of strings (UUIDs) | Must list all input fact IDs not referenced in any operation. Used to verify no facts were silently dropped. Can be empty if all facts are matched. |
Common Failure Modes
Memory deduplication prompts fail in predictable ways. These are the most common production failure modes and the specific guardrails that prevent them.
False Merges of Semantically Distinct Facts
What to watch: The prompt merges two facts that share surface-level similarity but represent different entities, time periods, or contexts. For example, 'Acme Corp revenue was $10M in Q1' and 'Acme Corp revenue was $10M in Q3' are distinct facts that should not be merged. Guardrail: Require the prompt to output an equivalence justification with explicit entity disambiguation fields. Add a pre-merge check that compares entity IDs, temporal scopes, and source documents before allowing a merge operation.
Duplicate Retention Due to Overly Conservative Thresholds
What to watch: The prompt fails to identify true duplicates because the similarity threshold is set too high or the prompt overweights minor surface differences like punctuation, whitespace, or synonym variation. The memory store accumulates redundant entries that degrade retrieval quality. Guardrail: Calibrate deduplication sensitivity with a labeled validation set of known duplicates and known distinct pairs. Implement a two-pass approach: first pass flags candidates with loose similarity, second pass applies stricter equivalence criteria with justification required only for merge decisions.
Source Provenance Loss After Merge
What to watch: When two facts are merged, the resulting entry loses track of which source documents originally contributed each piece of information. Downstream agents can no longer trace claims back to evidence. Guardrail: Require the prompt output to include a merged source list with per-fact provenance tracking. The merge operation must preserve all source IDs, timestamps, and confidence scores from the original entries rather than selecting a single 'winning' source.
Confidence Score Collapse on Merged Entries
What to watch: The prompt naively averages or takes the maximum confidence score when merging entries, producing a misleading confidence value. Two low-confidence duplicate observations should not combine into a high-confidence fact without additional evidence. Guardrail: Define explicit confidence aggregation rules in the prompt template. Require the output to explain how the merged confidence score was derived and flag cases where confidence should decrease due to source disagreement rather than increase due to corroboration.
Temporal Scope Erasure During Deduplication
What to watch: Facts that are true at different times are incorrectly merged into a single timeless assertion. 'CEO was Jane Smith' and 'CEO was John Doe' are both true but at different periods. The deduplication prompt treats them as conflicting rather than temporally scoped. Guardrail: Include temporal validity fields in the deduplication schema. The prompt must compare effective dates, expiration dates, and observation timestamps before declaring equivalence. Flag temporally adjacent facts for human review rather than automated merge.
Batch Boundary Inconsistency
What to watch: When deduplication runs across batches, facts near batch boundaries may be merged in one batch but not recognized as duplicates of entries in adjacent batches. This creates inconsistent deduplication results that depend on arbitrary batch splits. Guardrail: Implement overlapping batch windows where boundary entries are re-evaluated against the adjacent batch. Add a post-deduplication consistency check that scans for remaining near-duplicates across the full store and flags them for a second pass.
Evaluation Rubric
Use this rubric to evaluate the quality of deduplication outputs before integrating the prompt into a production memory pipeline. Each criterion targets a specific failure mode common in fact deduplication.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
True Duplicate Recall | All fact pairs with semantic equivalence are identified for merge | Output misses a pair of facts that express the same information with different wording | Run against a golden set of 50 known duplicate pairs; require 100% recall |
False Merge Precision | No non-equivalent facts are flagged for merge | Output proposes merging facts that differ in subject, predicate, object, qualifier, or temporal scope | Run against a golden set of 50 known distinct pairs; require 0% false merges |
Merge Operation Validity | Every proposed merge includes a valid [MERGE_OPERATION] with source fact IDs, target fact ID, and resolved value | Merge operation is missing required fields, references non-existent fact IDs, or produces a self-referential merge | Schema validation against the output contract; check all referenced IDs exist in [INPUT_FACTS] |
Equivalence Justification Quality | Every merge includes a [JUSTIFICATION] that explains which fields match and why differences are non-conflicting | Justification is empty, circular, or contradicts the merge decision | LLM-as-judge evaluation on 20 samples; require score >= 4/5 on justification clarity and accuracy |
Delete Operation Safety | Proposed [DELETE_OPERATION] entries target only fully subsumed facts with no unique information | Delete operation removes a fact that contains unique field values not present in the retained fact | Manual review of 10 delete proposals; require 0 cases where deleted fact has unique information |
Confidence Score Calibration | [CONFIDENCE] scores >= 0.9 for exact matches, 0.7-0.9 for near-duplicates with minor differences, < 0.7 for uncertain cases | Confidence score is 0.95+ for a pair with conflicting temporal qualifiers or different named entities | Correlation check: confidence scores should monotonically decrease as semantic distance increases across 30 graded pairs |
Output Completeness | Output addresses every fact in [INPUT_FACTS] either in a merge, delete, or keep decision | One or more input facts are absent from the output with no explicit keep decision | Count unique fact IDs in output decisions; compare against input fact ID count; require exact match |
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
Use the base prompt with a small batch of 10-20 fact pairs. Skip strict schema enforcement and rely on manual review of merge/delete decisions. Replace [OUTPUT_SCHEMA] with a simple JSON array of {action, fact_ids, merged_fact, justification}. Run on a single model without fallback logic.
Watch for
- Near-duplicate facts with different surface forms being missed (e.g., "Acme Corp HQ in Boston" vs "Acme headquarters located in Boston, MA")
- Overly aggressive merging of facts that are related but distinct (e.g., merging revenue figures from different quarters)
- Missing equivalence justifications that make audit impossible

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