Skip to content
AI360Xpert

Memory Systems in Agents

Agent memory systems extend the limited context window with persistent storage — enabling agents to remember past interactions, accumulate knowledge, and maintain state across long-running tasks that span multiple sessions.

Agent memory systems extend the limited context window with persistent storage — enabling agents to remember past interactions, accumulate knowledge, and maintain state across long-running tasks that span multiple sessions.
Agent memory systems extend the limited context window with persistent storage — enabling agents to remember past interactions, accumulate knowledge, and maintain state across long-running tasks that span multiple sessions.

Why Does This Exist?

An LLM's context window is finite — typically 8K to 200K tokens. For a task that spans hours or days (writing a research report, managing a project, serving a repeat customer), the context window fills up and older information gets dropped. Memory systems solve this by selectively persisting important information outside the context window and retrieving it when needed.

Without memory, every agent interaction starts from zero. With memory, agents can accumulate knowledge, learn user preferences, reference past decisions, and maintain coherence across long tasks.

Think of It Like This

A researcher's system of notes, notebooks, and habits

A researcher has several types of memory: their immediate working memory (what they're thinking about right now), their lab notebook (a written record of past experiments), their accumulated domain knowledge (years of reading papers), and their practiced experimental techniques (procedural skill). Agent memory systems map directly to these: working memory = context window; episodic = conversation history; semantic = knowledge base; procedural = learned strategies.

How It Actually Works

The four memory types

1. Working memory (in-context) The current context window — the agent's immediate awareness. Everything in the context window is "active" but limited to the window size. Efficiently managing what goes into working memory (via summarization and selection) is the core challenge.

2. Episodic memory A log of past interactions, observations, and decisions. Stored externally (database, file system) and retrieved by recency or semantic similarity. Enables the agent to say "When I encountered this situation last week, here's what I tried and what happened."

3. Semantic memory A knowledge base of facts, documents, and domain knowledge. Typically implemented as a vector store with embedding-based retrieval (RAG). The agent queries this when it needs information it doesn't have in-context.

4. Procedural memory Learned action patterns — successful strategies and workflows the agent has used before. Stored as prompt templates, few-shot examples, or even fine-tuned model weights.

Memory retrieval strategies

StrategyWhen to useMechanism
RecencyNeed recent historySliding window over time-ordered events
Semantic similarityNeed relevant past experiencesEmbedding cosine similarity via vector DB
Exact lookupNeed specific factKey-value store with deterministic keys
HybridComplex queriesCombine semantic search + recency filter

Memory management: what to store

Not everything is worth storing. Selection criteria:

  • Surprise/novelty: New information that contradicts or extends existing knowledge
  • Goal relevance: Information directly relevant to the current or future task
  • User feedback: Explicit corrections and preferences
  • Failure cases: What went wrong and why (the most valuable for improvement)

Code

from langchain_openai import OpenAIEmbeddings, ChatOpenAIfrom langchain_community.vectorstores import FAISSfrom langchain.memory import ConversationSummaryBufferMemoryfrom langchain.schema import Documentimport json, time
# ── 1. Working memory: conversation summary buffer ────────────────────────────llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Keeps recent messages in full; summarizes older messages to save tokensworking_memory = ConversationSummaryBufferMemory(    llm=llm,    max_token_limit=1000,    memory_key="chat_history",    return_messages=True,)
# Simulate adding conversation turnsworking_memory.save_context(    {"input": "What is the capital of France?"},    {"output": "Paris is the capital of France."})working_memory.save_context(    {"input": "What is its population?"},    {"output": "Paris has approximately 2.1 million people in the city proper."})
print("Working memory contents:")print(working_memory.load_memory_variables({})["chat_history"])
# ── 2. Semantic memory: vector store (RAG) ────────────────────────────────────embeddings = OpenAIEmbeddings()
# Build knowledge base from documentsknowledge_docs = [    Document(page_content="Python was created by Guido van Rossum in 1991.", metadata={"source": "history"}),    Document(page_content="The Eiffel Tower is 330 meters tall.", metadata={"source": "facts"}),    Document(page_content="FAISS is a library for efficient similarity search.", metadata={"source": "tech"}),]
vectorstore = FAISS.from_documents(knowledge_docs, embeddings)
def retrieve_memories(query: str, k: int = 2) -> list[str]:    """Retrieve semantically similar memories."""    docs = vectorstore.similarity_search(query, k=k)    return [doc.page_content for doc in docs]
memories = retrieve_memories("Who invented Python?")print(f"\nRetrieved memories for 'Who invented Python?':")for m in memories:    print(f"  - {m}")
# ── 3. Episodic memory: persistent event log ──────────────────────────────────class EpisodicMemory:    """Simple episodic memory: stores events with timestamps."""    def __init__(self):        self.episodes = []        def record(self, event_type: str, content: dict):        self.episodes.append({            "timestamp": time.time(),            "type": event_type,            "content": content,        })        def recall_recent(self, n: int = 5) -> list:        return self.episodes[-n:]        def recall_by_type(self, event_type: str) -> list:        return [e for e in self.episodes if e["type"] == event_type]
episodic = EpisodicMemory()episodic.record("user_feedback", {"rating": 4, "comment": "Good answer but too verbose"})episodic.record("tool_call", {"tool": "search", "query": "FAISS", "success": True})episodic.record("task_completed", {"task": "research report", "duration_min": 15})
print(f"\nRecent episodes:")for episode in episodic.recall_recent(3):    print(f"  {episode['type']}: {episode['content']}")

Watch Out For

Retrieval hallucination from irrelevant memories

Semantic similarity retrieval can surface memories that are superficially similar but contextually irrelevant — contaminating the agent's context with misleading information. Always include the retrieved memory's source and timestamp so the agent can reason about relevance. Filter retrieved memories through a relevance check before injecting them into the context.

Memory bloat and retrieval latency

Episodic memory that records every token exchanged grows rapidly. After thousands of interactions, retrieval becomes slow and results degrade as the signal is diluted by noise. Implement memory pruning: score old memories by a combination of recency, access frequency, and relevance to current goals, and archive or delete low-scoring entries.

The Quick Version

  • Agent memory extends the finite context window with persistent external storage.
  • Four types: working memory (context window), episodic (interaction log), semantic (knowledge base via RAG), procedural (learned strategies).
  • Retrieval strategies: recency (sliding window), semantic similarity (vector DB), exact lookup (key-value), hybrid.
  • Store selectively: prioritize novel, goal-relevant, and failure-case information.
  • Manage memory size with summarization and pruning — raw episode logs don't scale.