Contradiction Detection: When Your AI Agent Learns Conflicting Information
Your AI agent has been chatting with a user for weeks. It knows they prefer Python. It's recommended Python libraries, suggested Python-based architectures, and built entire workflows around this preference. Then one day, the user says: "I've switched to Rust for all new projects."
What happens next determines whether your agent is trustworthy or dangerously unreliable.
Without contradiction detection, your agent now holds two conflicting beliefs simultaneously: the user prefers Python and the user prefers Rust. Depending on which memory surfaces first during retrieval, the agent might recommend Python libraries for a Rust project — or worse, silently act on outdated information without the user ever knowing.
This is the contradiction problem, and it's one of the hardest challenges in AI agent memory systems. Let's break down how it works, why it matters, and how to solve it.
Why Contradictions Are Inevitable
If your agent remembers anything at all, contradictions will happen. Here's why:
- People change. Preferences evolve. A user who loved React last year might be all-in on Svelte today.
- Context shifts. "Use PostgreSQL" might be true for the analytics project but not for the mobile app.
- Corrections happen. Users misspeak, then correct themselves. "I'm in New York — actually, I moved to Austin last month."
- Multiple sources conflict. In multi-agent systems, Agent A might learn one thing while Agent B learns the opposite.
- Implicit vs. explicit. Behavior might contradict stated preferences. A user says they prefer email but always responds on Slack first.
The question isn't whether your memory system will encounter contradictions — it's whether it can handle them gracefully when they appear.
The Anatomy of a Memory Contradiction
A contradiction occurs when two or more stored memories make mutually exclusive claims about the same entity or relationship. Formally, we can define it as:
Two memories M₁ and M₂ are contradictory when they assert incompatible values for the same attribute of the same entity within overlapping temporal or contextual scopes.
Let's look at concrete examples:
Direct Contradictions
- M₁: "User's favorite language is Python" (stored Jan 15)
- M₂: "User's favorite language is Rust" (stored Mar 10)
Contextual Contradictions
- M₁: "Deploy to AWS for all projects" (stored for Project Alpha)
- M₂: "Use GCP exclusively" (stored for Project Beta, but missing project scope)
Temporal Contradictions
- M₁: "Meeting with Sarah is at 2pm" (stored Monday)
- M₂: "Meeting with Sarah moved to 4pm" (stored Tuesday, but M₁ not invalidated)
Detection Algorithms
There are three primary approaches to detecting contradictions in agent memory. Each has trade-offs between accuracy, speed, and complexity.
1. Semantic Similarity + Polarity Check
The most common approach: when a new memory is stored, compute its semantic similarity against existing memories. For high-similarity pairs, check whether they assert the same or opposite things.
# Python — Contradiction detection with 0Latency
import requests
def store_with_contradiction_check(api_key, memory_text, agent_id="default"):
"""Store a memory and check for contradictions automatically."""
# 0Latency handles contradiction detection server-side
response = requests.post(
"https://api.0latency.ai/memories/extract",
headers={"X-API-Key": api_key},
json={
"agent_id": agent_id,
"content": memory_text,
"metadata": {
"check_contradictions": True,
"resolution_strategy": "flag_and_keep_latest"
}
}
)
result = response.json()
# Check if contradictions were detected
if result.get("contradictions"):
for c in result["contradictions"]:
print(f"⚠️ Conflict detected:")
print(f" Existing: {c['existing_memory']}")
print(f" New: {c['new_memory']}")
print(f" Confidence: {c['confidence']:.0%}")
print(f" Resolution: {c['resolution']}")
return result
# Example usage
store_with_contradiction_check(
api_key="your-api-key",
memory_text="User's preferred programming language is Rust"
)
# ⚠️ Conflict detected:
# Existing: User's preferred programming language is Python
# New: User's preferred programming language is Rust
# Confidence: 94%
# Resolution: Kept latest, marked previous as superseded
2. Entity-Attribute Tracking
A more structured approach: extract entities and attributes from each memory, then check for conflicting attribute values on the same entity.
// JavaScript — Entity-based contradiction detection
const response = await fetch('https://api.0latency.ai/memories/extract', {
method: 'POST',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
agent_id: 'support-agent',
content: 'Customer prefers email communication',
metadata: {
entity_extraction: true, // Extract entities automatically
contradiction_mode: 'entity_attribute'
}
})
});
const result = await response.json();
// 0Latency automatically extracts:
// Entity: "Customer" | Attribute: "communication_preference" | Value: "email"
// And checks against existing entity-attribute pairs
3. Temporal Windowing
Some contradictions are only contradictions within the same time window. "User is in New York" and "User is in Austin" aren't contradictory if they're months apart — they represent a move. Temporal windowing groups memories by time periods and only flags contradictions within the same window.
Resolution Strategies
Detecting a contradiction is only half the battle. You also need a strategy for resolving it. Here are the four most common approaches:
1. Last Write Wins (LWW)
The simplest strategy: the most recent memory supersedes older conflicting memories. This works well for preferences and states that genuinely change over time. It's the default for most use cases.
2. Confidence Scoring
Each memory carries a confidence score based on how explicitly it was stated. "I use Python" (explicit, high confidence) beats "seems to like Python" (inferred, lower confidence), regardless of recency.
3. Source Priority
In multi-agent or multi-source systems, some sources are more authoritative. A user's direct statement outranks an inference from behavior. An admin's configuration outranks an agent's guess.
4. Flag and Ask
When confidence is low or the stakes are high, the best strategy is to surface the contradiction to the user: "I previously noted you prefer Python, but you just mentioned Rust. Which should I use going forward?"
Why This Matters for Trust
Memory contradictions are a trust issue. When an agent acts on outdated or conflicting information, users notice — and they lose confidence fast.
Consider a customer support agent that remembers a customer's old address and ships a replacement product to the wrong location. Or a coding assistant that suggests a deprecated library because it remembers an old conversation but missed the correction. These aren't just bugs — they're trust-destroying moments.
Contradiction detection is what separates a memory system from a reliable memory system. It's the difference between an agent that remembers everything and an agent that remembers correctly.
This is why we built contradiction detection directly into the 0Latency memory API. Every memory stored is automatically checked against existing memories for conflicts. You configure the resolution strategy once — last-write-wins, confidence-based, or flag-and-ask — and the system handles the rest.
Implementation Best Practices
- Always timestamp memories. Without timestamps, temporal resolution is impossible. 0Latency adds these automatically.
- Attach context metadata. Project name, conversation ID, user session — the more context, the fewer false positives in contradiction detection.
- Use scoped memories. "Prefers dark mode" might be true for the IDE but not the website. Scoping memories to contexts prevents cross-context contradictions.
- Log contradiction events. Track how often contradictions occur, what types are most common, and how they're resolved. This data helps you tune your resolution strategy.
- Don't delete — supersede. Keep old memories marked as superseded rather than deleting them. The history of changes is itself valuable context.
Real-World Example: Preference Evolution
# Python — Tracking preference evolution over time
import requests
API_KEY = "your-api-key"
BASE = "https://api.0latency.ai"
# Store initial preference
requests.post(f"{BASE}/memories/extract", headers={"X-API-Key": API_KEY},
json={"content": "User prefers Python for backend development",
"agent_id": "assistant"})
# Weeks later, user's preference evolves
requests.post(f"{BASE}/memories/extract", headers={"X-API-Key": API_KEY},
json={"content": "User now prefers Rust for backend development",
"agent_id": "assistant",
"metadata": {"check_contradictions": True}})
# Query with contradiction awareness
response = requests.post(f"{BASE}/recall",
headers={"X-API-Key": API_KEY},
json={"query": "What language does the user prefer for backend?",
"agent_id": "assistant"})
result = response.json()
# Returns the latest (Rust), with history showing the evolution:
# [
# {"content": "User now prefers Rust for backend", "status": "active"},
# {"content": "User prefers Python for backend", "status": "superseded"}
# ]
With 0Latency, this entire flow — detection, resolution, and history tracking — happens automatically. You store memories, we handle the consistency. Learn more about how it works in our case study, or check pricing to get started.
Frequently Asked Questions
How does AI memory contradiction detection work?
Contradiction detection compares newly stored memories against existing ones using semantic similarity and entity-attribute analysis. When two memories make conflicting claims about the same subject, the system flags the contradiction and applies a resolution strategy — such as keeping the most recent memory or asking the user to clarify.
What happens when an AI agent has conflicting information?
Without contradiction detection, the agent may randomly surface either version, leading to inconsistent and unreliable behavior. With proper detection, conflicts are identified at storage time, and the system applies a configurable resolution strategy to maintain memory consistency.
Can 0Latency detect contradictions automatically?
Yes. 0Latency checks every stored memory against existing memories for semantic conflicts. You configure the resolution strategy (last-write-wins, confidence-based, or flag-and-ask) and the system handles detection and resolution automatically.
What's the difference between a contradiction and a preference change?
Temporal context is the key differentiator. A preference change is a valid evolution over time ("I switched from Python to Rust"). A contradiction is two conflicting claims within the same time window or context. Proper memory systems use timestamps and context to distinguish the two.
How should I handle contradictions in multi-agent systems?
Use source priority as your primary resolution strategy. Define which agents or data sources are most authoritative for different types of information, and configure your memory system to prefer higher-authority sources when conflicts arise.
Build Reliable Agent Memory
Contradiction detection, automatic resolution, and persistent cross-session memory — all included in the free tier.
Get your free API key →