AI Agent Memory and Context Management Explained
How AI agents remember: the context window, short-term thread state, long-term stores and vector search, plus compaction, note-taking and the MemGPT model.
AI agent memory is the set of techniques that let an agent keep useful information beyond a single model call. A language model only "knows" what is in its context window, so an agent's memory system decides what goes into that window, what gets summarized or dropped, what is saved to outside storage, and how saved information is found again later. Good memory design is less about storing everything and more about keeping the context small, relevant and current.
Our agentic AI guide introduces memory as one building block of an agent. This piece goes deeper on how the tiers work and how to manage them.
Why the context window isn't enough
Every model call starts fresh. What the model can use is whatever text (tokens) the application sends: instructions, conversation history, tool definitions, tool results and retrieved documents. That window has a hard size limit, and filling it has a cost even before you hit the limit.
Anthropic describes the problem as context rot: as the number of tokens grows, "the model's ability to accurately recall information from that context decreases" [2]. It compares the model's attention to a budget that every extra token draws down, and sets a goal for agent builders: find "the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome" [2]. Anthropic calls this discipline context engineering, which it describes as "the natural progression of prompt engineering" [2].
Agents make the problem worse than chat does. Each tool call adds output, and long tasks run for dozens or hundreds of steps. Anthropic's own research system saves its plan to an external memory because "if the context window exceeds 200,000 tokens it will be truncated" [7].
The memory tiers
It helps to think of agent memory like a computer's memory hierarchy, which is the analogy the MemGPT paper made explicit. MemGPT (Packer et al., 2023) proposed "virtual context management, a technique drawing inspiration from hierarchical memory systems in traditional operating systems," moving data between fast and slow tiers to give the illusion of a larger memory [1].
1. The context window (working memory)
This is everything the model sees on the current call. In MemGPT's design, the prompt is split into three parts: read-only system instructions, a fixed-size "working context" the model can edit only through function calls, and a first-in-first-out queue of recent messages whose first entry is a running summary of older ones [1]. Most production agents follow a similar layout even if they don't use those names.
2. Short-term memory (the thread scratchpad)
Short-term memory holds the state of one task or conversation: messages so far, intermediate results, the current plan. It lives outside the model so it survives between calls and can be reloaded.
LangGraph is a clear example. It keeps short-term memory in the agent's state and persists that state through thread-scoped checkpoints [3]. A checkpointer saves a snapshot of the graph's state at each step, organized by thread ID, so a conversation can resume later or recover after a failure [4]. The OpenAI Agents SDK offers sessions that retrieve conversation history before each run and store new messages after it [8].
3. Long-term memory (the store)
Long-term memory persists across conversations and tasks: user preferences, learned facts, past outcomes. It usually lives in a database, often with vector search so the agent can find items by meaning rather than exact keywords (see how vector databases work and embedding models explained).
In LangGraph, long-term memories are saved in custom "namespaces" (like folders) under keys (like file names) and can be recalled from any thread; the store supports semantic search and content filtering [3]. MemGPT splits this tier in two: recall storage, a database of every past message, and archival storage, "a read/write database storing arbitrary length text objects" [1].
What kinds of things get remembered
LangGraph's documentation borrows three categories from cognitive science [3]:
Memory type | What it stores | Typical implementation |
|---|---|---|
Semantic | Facts about the user, domain or world | A profile document or a searchable collection of facts |
Episodic | Past experiences, how a task was done before | Few-shot examples drawn from earlier runs |
Procedural | How to behave | The system prompt, sometimes revised by the agent itself |
Reflexion is a well-known episodic example: after a failed attempt, the agent writes a lesson into an "episodic memory buffer" and reads it on the next try [6].
How information moves: write and retrieval paths
Memory isn't static storage; it's traffic between tiers. Two directions matter.
Writing out of the context
- Agent-directed notes. The model decides to save something. Anthropic calls this structured note-taking or agentic memory: "the agent regularly writes notes" outside the context window, such as a to-do list or a
NOTES.mdfile, and pulls them back in later [2]. In MemGPT, memory edits are "entirely self-directed," made through function calls the model chooses [1]. - Automatic extraction. The framework does it. With CrewAI's memory enabled, the crew extracts facts from each task's output and stores them after the task finishes, using an LLM to analyze content as it saves [5].
- Eviction. When the window fills, old messages are pushed out but kept. MemGPT warns the model at a "warning token count" (the paper's example is 70% of the window) so it can save what matters, then flushes messages at a "flush token count" (example: 100%), writing a new recursive summary and keeping the evicted messages in recall storage [1].
LangGraph's docs describe a timing choice for writes. Saving "in the hot path" makes new memories available immediately but adds latency; saving in a background task removes that latency, though "infrequent updates may leave other threads without new context" [3].
Retrieving back into the context
- Search on demand. The agent calls a memory or search tool when it needs something. MemGPT pages through archival search results so retrieval itself can't overflow the window [1].
- Automatic recall. The framework injects relevant memories before each step. In CrewAI, "before each task, the agent recalls relevant context from memory and injects it into the task prompt" [5]. Its default ranking blends semantic similarity, recency and importance with weights of 0.5, 0.3 and 0.2 [5].
- Just-in-time loading. Rather than pre-loading data, the agent holds lightweight references (file paths, saved queries, links) and loads content with tools when needed. Anthropic cites Claude Code using glob and grep this way [2].
Retrieval into memory is closely related to retrieval-augmented generation. The difference is the source: RAG usually searches a fixed document corpus, while agent memory searches what the agent itself has written or observed. Our agentic RAG explainer covers agents that do both.
Managing the context window
Four techniques do most of the work.
- Compaction. Summarize a conversation that's nearing the limit and start a fresh window with the summary [2]. Anthropic says Claude Code keeps decisions such as architecture choices and unresolved bugs, plus the five most recently accessed files [2].
- Tool-result clearing. Anthropic calls this "one of the safest lightest touch forms of compaction": once a tool's raw output has been used, drop it from history [2].
- Lean tool outputs. Design tools to return less. Anthropic recommends "some combination of pagination, range selection, filtering, and/or truncation with sensible default parameter values," and notes Claude Code limits tool responses to 25,000 tokens by default [9].
- Sub-agents with clean windows. Hand a focused job to a sub-agent with its own context and take back only a condensed summary, often 1,000 to 2,000 tokens [2]. See multi-agent systems for the trade-offs.
How frameworks implement memory (as of November 2026)
Framework | Short-term | Long-term | Notes |
|---|---|---|---|
LangGraph | Thread state saved by a checkpointer at each step [4] | Store with namespaces, semantic search and filters [3] | Checkpointer backends include in-memory, SQLite, Postgres and MongoDB [4] |
CrewAI | Task outputs passed as context | Unified | LLM-chosen hierarchical scopes; recall ranks by similarity, recency, importance [5] |
OpenAI Agents SDK | Sessions store and reload history per run [8] | Not a built-in long-term store on the pages reviewed | Can also use server-managed conversation IDs [8] |
MemGPT (research design) | FIFO queue with recursive summary [1] | Recall storage and archival storage [1] | Model manages its own memory via function calls [1] |
Risks and limitations
- Bad memories persist. A wrong fact written to long-term memory keeps coming back. Reflexion-style lessons are only as good as the feedback that produced them [6].
- Memory poisoning. If an agent saves content from untrusted sources, an attacker's instruction can be stored and replayed later. Treat memory writes like any other untrusted input; see RAG security and AI agent security and governance.
- Privacy. Long-term memory is personal data. Scope it per user or tenant (LangGraph namespaces and CrewAI scopes both support this [3][5]) and give users a way to see and delete it.
- Summaries lose detail. Compaction is lossy by design. Whatever the summary drops is gone from the model's view, which is why Claude Code's compaction explicitly preserves items like architectural decisions and unresolved bugs [2].
- Growth and cost. Checkpoints accumulate over long conversations; LangGraph's checkpointer interface includes an optional method for pruning a thread's history [4].
How to design an agent's memory
- Start with the window. Trim tool outputs and clear stale results before adding any database [2][9].
- Add thread persistence so a task can pause, resume and recover [4].
- Externalize the plan as notes or a to-do list for long tasks [2].
- Add long-term memory only for information that is reused across sessions, and decide who can read and write each namespace.
- Choose hot-path or background writes based on whether other threads need the memory immediately [3].
- Log what was retrieved on every step, so you can debug why the agent "remembered" something.
Outlook
Larger context windows don't make memory design obsolete; Anthropic's context-rot finding suggests the opposite, since more tokens dilute attention [2]. Expect frameworks to keep adding built-in compaction, scoped memory and retrieval tuning, and expect debate about how much an always-remembering agent should retain. For one high-profile take on where long context and autonomous agents are heading, see our report on Eric Schmidt's warning about infinite context and autonomous agents. For how memory interacts with planning, read our companion explainer on agent planning and reasoning.
Frequently asked questions
Do AI agents remember past conversations?
Only if the application saves them. The model itself starts each call fresh. Frameworks add short-term memory by saving thread state between calls [4][8] and long-term memory by writing facts to a store that later conversations can search [3][5].
What is the difference between short-term and long-term agent memory?
Short-term memory belongs to one conversation or task and is reloaded when that thread continues [3]. Long-term memory is shared across threads, such as user preferences or learned facts, and is usually found by search rather than reloaded in full [3].
Is a vector database the same as agent memory?
No. A vector database is one common storage layer for long-term memory, useful for finding items by meaning. Agent memory also includes what's in the context window, the thread state, and the rules for what to write and when to retrieve it.
What is context engineering?
Anthropic defines it as strategies "for curating and maintaining the optimal set of tokens" during inference [2]. It covers instructions, tools, retrieved data and history, not just the prompt text.
What did MemGPT contribute?
MemGPT treated the context window like a computer's main memory and outside databases like disk, with the model moving data between them through function calls [1]. The authors evaluated it on analyzing documents larger than the context window and on multi-session chat where the agent retains memory over time [1].
Sources
- Packer et al., "MemGPT: Towards LLMs as Operating Systems," arXiv. https://arxiv.org/abs/2310.08560
- Anthropic, "Effective context engineering for AI agents." https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
- LangGraph documentation, "Memory overview." https://docs.langchain.com/oss/python/langgraph/memory
- LangGraph documentation, "Checkpointers." https://docs.langchain.com/oss/python/langgraph/checkpointers
- CrewAI documentation, "Memory." https://docs.crewai.com/en/concepts/memory
- Shinn et al., "Reflexion: Language Agents with Verbal Reinforcement Learning," arXiv. https://arxiv.org/abs/2303.11366
- Anthropic, "How we built our multi-agent research system." https://www.anthropic.com/engineering/multi-agent-research-system
- OpenAI Agents SDK documentation, "Running agents." https://openai.github.io/openai-agents-python/running_agents/
- Anthropic, "Writing effective tools for agents โ with agents." https://www.anthropic.com/engineering/writing-tools-for-agents