Every developer building an AI agent starts with the same naive pattern: whenever a user sends a message, they fetch the last 20 messages from the database and shove them into the system prompt.
As long as conversations are short, this works fine. But as conversations span weeks and months, the approach collapses:
- Context stuffing degrades reasoning: LLMs exhibit "lost-in-the-middle" attention degradation when reading massive conversation logs.
- Cost and latency explode: Reprocessing thousands of tokens on every single turn burns API budgets and increases time-to-first-token.
- Contradictions cause hallucinations: If a user said "I live in Bangalore" in June and "I moved to Pune" in October, an LLM reading both raw messages often produces confused, conflicting output.
A conversation history is a stream of raw text. Memory is an evolving state of facts.
Here is how to design a real, living memory architecture for AI agents.
The Three Layers of Agent Memory
A robust memory system separates storage into three distinct categories:
- Short-Term Memory: The active conversation window (the current session's immediate back-and-forth).
- Semantic Knowledge: Static reference material, company documentation, and external knowledge bases (handled via standard RAG).
- Living Episodic Memory: Evolving structured facts about the user, their preferences, constraints, and project state.
Phase 1: Fact Extraction from User Turns
Rather than storing whole paragraphs, an agent should run background fact extraction after each significant exchange.
An extraction pipeline evaluates the conversation turn and extracts atomic declarative facts:
[
{
"subject": "User",
"predicate": "prefers_editor",
"object": "Cursor / VS Code",
"confidence": 0.95
},
{
"subject": "User",
"predicate": "primary_programming_language",
"object": "TypeScript",
"confidence": 0.98
}
]
By reducing sprawling chat logs into concise, structured assertions, you compress thousands of tokens into a few lightweight records.
Phase 2: Resolving Contradictions with Temporal Versioning
The hardest problem in long-term memory is fact evolution. Human beliefs, locations, and software stacks change.
When a new fact is extracted, the memory engine must execute contradiction detection before writing to storage:
- Embed the candidate fact and run a similarity search against existing active memories for this user.
- If semantic overlap is high, pass both facts to a small, fast model (like Claude 3.5 Haiku or Gemini 1.5 Flash) with an evaluation prompt:
- Are Fact A and Fact B complementary, or do they directly contradict each other?
- If they contradict, do not delete the old fact. Instead, apply temporal versioning:
- Set the old fact's status to
supersededwith a timestampvalid_until. - Insert the new fact with
valid_from: now()and referencesupersedes_id: old_fact.id.
- Set the old fact's status to
CREATE TABLE agent_memories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL,
fact TEXT NOT NULL,
embedding VECTOR(1536),
is_active BOOLEAN DEFAULT TRUE,
valid_from TIMESTAMPTZ DEFAULT NOW(),
valid_until TIMESTAMPTZ,
superseded_by UUID REFERENCES agent_memories(id)
);
This prevents the agent from forgetting historical context ("You previously used macOS until October") while ensuring active reasoning always uses current reality ("You currently use Linux").
Phase 3: Dynamic Context Injection
When the user asks a question, the agent retrieves only the facts relevant to the current conversation turn:
- Embed the user's incoming message.
- Query
agent_memoriesfiltering foris_active = true. - Format the top 5–10 relevant facts into a concise memory block injected into the system prompt:
<user_memory>
- Prefers TypeScript for backend services.
- Based in Pune, India (timezone: Asia/Kolkata).
- Uses PostgreSQL with pgvector for vector storage.
</user_memory>
The model receives clean, high-signal, up-to-date context in less than 200 tokens.
Conclusion
Stop treating raw conversation logs as memory. By decomposing dialogue into atomic facts, detecting contradictions, and maintaining temporal version history, you give AI agents true persistent memory that scales indefinitely across time.