AI Agent Memory Systems: Short-Term, Long-Term, and Episodic Patterns

Introduction
Memory is what separates a stateless chatbot from a capable AI agent. Without memory, every interaction starts from scratch. With the right memory architecture, an agent can recall a conversation from last week, draw on accumulated domain knowledge, and learn from past failures.
There is no single "memory" solution — production agents combine multiple memory types, each with different latency, capacity, and persistence characteristics. This guide breaks them down and shows how to wire them together.
The Four Memory Types
1. In-Context Memory (Working Memory)
In-context memory is whatever fits in the model's active context window. It is the fastest and simplest: no extra infrastructure, zero latency overhead, and the model has direct attention across every token.
Its limits are hard: context windows top out (even 200k tokens fills up in long agentic sessions), cost scales linearly with tokens, and nothing persists across sessions.
Use in-context memory for: the current session's message history, tool call results, and any documents retrieved for the immediate task.
2. External Memory (Long-Term Storage)
External memory lives outside the model — in databases, file systems, or object stores. The agent fetches relevant pieces at query time rather than loading everything at once.
This is the pattern most commonly called RAG (Retrieval-Augmented Generation). A retrieval step selects the most relevant chunks from a large corpus and injects them into the context for the current turn.
async function retrieveMemories(query: string, topK = 5): Promise {
const queryEmbedding = await embedder.embed(query)
const results = await vectorStore.query({
vector: queryEmbedding,
topK,
filter: { userId: currentUser.id }
})
return results.map(r => r.metadata.text)
}
// Before each LLM call:
const memories = await retrieveMemories(userMessage)
const systemPrompt = buildSystemPrompt({ memories }) 3. Episodic Memory (Session Summaries)
Episodic memory stores summaries of past sessions rather than raw transcripts. After each conversation ends, a summarization step condenses the key facts, decisions, and outcomes into a compact record tied to the user or task.
At the start of a new session, the agent retrieves recent episode summaries and injects them into the system prompt. This gives continuity without blowing up the context with unedited history.
async function summarizeSession(messages: Message[]): Promise {
const summary = await llm.invoke([
{ role: "system", content: "Extract key facts, decisions, and action items from this conversation. Be concise." },
{ role: "user", content: formatMessages(messages) }
])
return {
id: uuid(),
userId: currentUser.id,
createdAt: new Date(),
summary: summary.content,
embedding: await embedder.embed(summary.content)
}
} 4. Semantic Memory (Knowledge Graphs and Structured Facts)
Semantic memory stores structured, factual knowledge: user preferences, project parameters, entity relationships. Unlike episodic summaries (narrative), semantic memory is a queryable knowledge graph or key-value store of facts the agent should always know about a user or domain.
A CRM-integrated support agent might maintain semantic memory of each customer's plan tier, past issues, and product usage patterns — updated incrementally as new interactions occur.
Memory Write Patterns
When should an agent write to memory? The two common approaches are:
- Synchronous (in-turn): The agent writes to memory as part of its tool-use loop. Simple but adds latency to every turn.
- Asynchronous (post-turn): Memory writing happens after the user-facing response is returned. Lower latency but introduces a brief consistency window where the new memory isn't available yet.
For most applications, asynchronous writes are the right call. Write a brief immediate summary to in-context state, then kick off an async job to update vector storage and episode records.
Forgetting: Why It Matters
Unbounded memory accumulation degrades retrieval quality — irrelevant old records score above fresh ones. Build retention policies:
- TTL-based expiry for low-value episodic summaries
- Importance scoring to prioritize high-signal memories during retrieval
- User-triggered deletion to satisfy privacy obligations (GDPR right to erasure)
Reference Architecture
A production memory stack for an agent looks like this:
- In-context: Last 20 messages + retrieved chunks, managed by the agent loop
- Episodic store: PostgreSQL table with a pgvector column, summarized nightly
- Semantic store: Redis hash per user for structured facts, updated on relevant tool calls
- Document store: Pinecone or Weaviate for large knowledge bases, retrieved by semantic similarity
Conclusion
Memory is not one thing — it is a layered system where each tier has a different cost, capacity, and persistence trade-off. Start with in-context memory and episodic summaries; add vector retrieval when the knowledge base outgrows the context window; introduce semantic memory when the agent needs to track evolving structured facts.
Build forgetting into the design from the start. An agent that accumulates noise forever performs worse over time, not better.
Building a memory-enabled AI agent?
Mickiesoft's AI team designs and builds production agent systems with robust memory architectures for enterprise applications.
Let's TalkFrequently Asked Questions
Find answers to common questions about our services, process, and capabilities.