Blog·Learning

Context memory in AI: the context window and agent memory architecture

By Shardul Mane·11 min read

A blurred, grainy photo of glowing dandelion seed heads against a blue sky, with the supermemory logo and the headline Designing an agent memory architecture.

Context memory in AI is everything a model can draw on when it answers: the context window it reads on this call, plus memory an application saves outside the model and loads back in. The context window is short-term and empties when the session ends. Agent memory is the long-term part, and it decides what from earlier work gets back into the window.

This guide covers both halves: where the term comes from, how the context window works as working memory, why long contexts lose detail, what AI agent memory is, and how to design an agent memory architecture. If you're new to the topic, how AI memory actually works is a gentler start.

What is context memory?

In AI, context memory has two layers:

  • The context window. This is all the text a model can reference while it writes a response, including the response itself. Anthropic's docs describe it as a "working memory" for the model, separate from the data it was trained on (Anthropic).
  • Memory outside the model. These are the facts, preferences, decisions and past events an application stores and retrieves. The model can only use them after they're loaded back into the window.

Models don't keep anything between calls on their own. Anthropic's Messages API is stateless, so your app sends the full conversation every time, and OpenAI describes each text generation request as independent and stateless. Anything a model seems to remember is context that something put back in front of it.

People search for this as context memory, contextual memory and context as memory. They mean the same thing: what the model can use depends on what's in its context.

Where the term comes from: context-dependent memory

In psychology, context-dependent memory means people recall information better when the setting at recall matches the setting where they learned it. In a 1975 study, divers learned word lists on land and underwater. Lists learned underwater were best recalled underwater, and lists learned on land were best recalled on land (Godden and Baddeley, British Journal of Psychology).

State-dependent memory is the same idea for your internal state. In a 1969 study, volunteers who learned while intoxicated recalled more when they were tested intoxicated again, while recognition wasn't affected (Goodwin et al., Science).

The idea carries over to AI as a design rule: retrieval works better when the cues match. For an agent, the cues are who is asking, which project they're in and when something happened. A memory system that keeps those cues can narrow a search to one user's recent decisions. One that stores bare text can't tell them apart.

Context window vs memory: what's the difference?

The context window is what the model reads right now. Memory is what survives after the window is cleared.

Context window Agent memory
What it is The tokens the model reads on one call Information saved outside the model
How long it lasts One request, or one session if your app resends the history Across sessions, until it's updated or deleted
How big it is Fixed by the model, about 1M tokens on current frontier models (October 2026) Limited by storage, not by the model
What fills it System prompt, messages, tool definitions, tool results, retrieved context Facts, preferences, decisions, events, documents
How it fails Overflow, and weaker recall as it fills Missing, stale, wrongly scoped or badly retrieved memories
Who controls it Whoever builds the request Your app's rules for saving, recalling and deleting

A bigger window helps inside one session. It carries nothing to the next one, and filling it has a cost, as the next sections show. Memory decides what earns a place in the window at all.

How does the context window work as AI working memory?

Everything in a request counts toward the window: the system prompt, every message (including tool results, images and documents), the tool definitions and the output the model generates (Anthropic). OpenAI defines it the same way, as the maximum tokens for one request, counting input, output and reasoning tokens (OpenAI).

Windows are large now. As of October 16, 2026, current Claude models have a 1M-token window (Anthropic), GPT-6 Astra has 1,050,000 tokens (OpenAI) and Gemini 4 Argon has 1,048,576 tokens shared between input and output (Google). The full table, and what to do when you run out, is in our guide to LLM context windows.

What happens at the limit depends on the product:

  • APIs refuse. If the input alone is larger than the window, Claude's API returns a "prompt is too long" error (Anthropic).
  • Chat apps drop old turns. Interfaces like claude.ai can manage the window first in, first out, so the oldest messages go first (Anthropic).
  • Coding agents compact. Claude Code replaces the conversation with a structured summary and reloads its instruction files (Claude Code docs).

Each of these keeps the session going. None of them keeps anything for the next session.

Why do long contexts lose information?

Two effects are well measured, and they explain why "put everything in the window" doesn't work as memory.

  • Lost in the middle. Models use information at the start or end of a long input more reliably than information in the middle, even models built for long contexts (Liu et al., 2023).
  • Context rot. As the token count grows, accuracy and recall degrade. Anthropic calls this context rot (Anthropic). In the NoLiMa benchmark, where the question and the answer share few words, 11 of 13 models fell below half of their short-context score at 32K tokens (Modarressi et al., 2025).

Memory across sessions shows the same pattern. LongMemEval, a benchmark of 500 questions about long chat histories, found that commercial chat assistants and long-context models showed a 30% accuracy drop when they had to remember information across sustained interactions (Wu et al., 2024).

So the window is a limited space, and stuffing it is both expensive and unreliable. Choosing what goes into it is the job of context engineering, and agent memory is where most of that material comes from.

What is AI agent memory?

AI agent memory is the part of an agent that saves what it learns (facts, preferences, decisions and past events) outside the model and loads the relevant pieces back into the context window when a later task needs them.

Researchers describe it with the same words used for human memory. The CoALA framework splits a language agent's memory into short-term working memory and three long-term stores: episodic, semantic and procedural (Sumers et al., 2023).

Memory type What it holds Example The question it answers
Working What the current step needs The open task and the last tool result What does the next model call need to see?
Episodic Events from earlier work "On Sep 10 the customer asked to postpone the rollout" What happened, when, and who said it?
Semantic Facts about the world and the user "The customer prefers email updates" What's true now, and what supports it?
Procedural How to do things A release checklist, or the rules in the agent's prompt and code Which way of working is approved?

These are design categories, and you don't need a separate database for each. They help decide how much authority a record gets. "A retry worked once" is an event. "This endpoint rejects expired tokens" is a fact. "Refresh the token before retrying" is a procedure, and in CoALA's terms procedures also live in the model's weights and the agent's code. A workaround that helped once should stay an event until someone reviews it and promotes it to a rule.

Agent memory architecture: how memory moves in and out of context

Every agent memory system runs the same loop. CoALA names the steps retrieval (read from long-term memory), reasoning (update working memory) and learning (write to long-term memory). Microsoft's Agent Framework builds the loop into context providers, which "add context before execution and process data after execution" (Microsoft Learn).

Write: save what a future task needs

Save something when a later task will need it. Good triggers are an explicit preference, a confirmed decision, an accepted correction and the outcome of a finished task. A model's suggested plan isn't an accepted plan, and a drafted email isn't a sent one.

Keep the scope. Take "Use Python for this migration, but TypeScript remains our default." Saving only "prefers Python" changes the meaning. A useful record keeps the project exception and the general default apart, each tied to the message it came from. Your application can represent the exception like this:

{
  "id": "decision-104",
  "tenantId": "acme",
  "subjectId": "migration-project",
  "kind": "decision",
  "statement": "Use Python for the migration worker",
  "scope": "migration-project",
  "sourceId": "meeting-37#turn-18",
  "observedAt": "2026-09-10T15:00:00Z",
  "status": "active",
  "supersedes": null
}

Your database can enforce required fields and allowed status values. The extraction model can't grant itself access to a tenant or turn a project decision into a company policy. Those are application rules.

Recall: select, don't dump

A practical read path:

  1. Authenticate the request and work out which scopes the caller may read.
  2. Identify the entity, time frame and task in the question.
  3. Retrieve permitted candidates from the relevant sources.
  4. Resolve or flag conflicting versions.
  5. Pick a small evidence set and keep its sources.
  6. Answer, and say so when the evidence is incomplete.

Similarity is one input to that selection. It can't establish permission, freshness, or whether an old preference should override what the user just asked for. For a shipping address, a past conversation might explain an earlier problem while the order system holds the current address. Returning both without labels produces a confident wrong answer.

Update: corrections replace, history stays

When someone says "I now prefer email," current answers should use email. When they ask what was true last month, the older value may still matter. Keep event time apart from import time: a document uploaded today can describe something that happened last year, and it shouldn't overwrite yesterday's correction just because it arrived later.

Forget: deletion has to reach the copies

One source can produce chunks, embeddings, a summary and extracted facts. Give each derived record a path back to its source version. Otherwise a deleted document survives as an orphaned summary, or a corrected fact lives on in a cached profile.

Test each operation on its own

Operation What to prove
Write Repeating an event doesn't create duplicates
Read Only permitted, relevant evidence reaches the answer
Correct Current questions use the correction; history questions still work
Expire Expired context stops showing up where it shouldn't
Delete The source, derived records and caches all follow the deletion
Export Records keep their identity, source and version

The isolation guide covers the permission side, and the memory lifecycle guide covers corrections, retention and deletion.

How much architecture do you need?

Start with the smallest thing that passes your tests. A relational table or a versioned file is enough when the facts are few and exact lookup works. Add vector or hybrid retrieval when people ask the same thing in different words. Add graph relationships when explicit links between facts solve a problem you've seen.

Three ways to add long-term memory compares saved records, a custom retrieval layer and a managed API. Whichever you pick, test one full lifecycle before adding more: capture a decision, recall it in another session, correct it, check that another user can't see it, and delete it.

Context memory in supermemory

supermemory is context infrastructure for agents: memory, retrieval and user profiles through one API (docs). The loop above becomes a few calls per turn. A namespace is the boundary, usually one per user, and the user's profile plus the memories that match the message go into the context window:

import { Supermemory } from "supermemory" // npm i supermemory

const memory = new Supermemory({ apiKey: process.env.SUPERMEMORY_API_KEY })
const user = "user_4f8a" // one namespace per user

// Long-term memory going back into the context window
const { profile } = await memory.profile(user)
const related = await memory.search(user, {
  query: "Which database did we pick for reporting?",
  searchMode: "memories",
  limit: 5,
})

After the model answers, you save the turn with memory.add, and the facts in it become memories in the background. The quickstart shows the whole loop, the graph memory docs explain how facts connect and update, and the product page shows how memories get inferred, updated and forgotten.

Common questions

Is a bigger context window the same as memory?

No. A bigger window holds more of one session, and nothing in it carries over to the next. Filling it also makes recall worse, as the context rot and LongMemEval results above show.

What's the difference between context-dependent and state-dependent memory?

Both come from psychology. Context-dependent memory is recall cued by the outside setting, like the divers who remembered best in the place they learned. State-dependent memory is recall cued by your internal state, like the 1969 alcohol study. In AI terms, retrieval cues (user, project, time) play the first role, and a user profile plays something like the second.

Do I need a vector database for agent memory?

Not for a handful of preferences. A table keyed by user can hold those. Semantic search starts to matter when there are many memories and people describe the same thing in different words. What is long-term memory in AI? goes through when plain records are enough.

How do I test whether context memory works?

Use a fact the model can't guess, like a made-up project codename. Save it, start a fresh session and ask a question that needs it. Then change it, ask again, and ask as a different user who shouldn't see it. If a step fails, the memory debugging guide shows where facts usually get lost.

For framework-specific setups, see the guides for LangChain, LangGraph, Microsoft Agent Framework and CrewAI.

  1. How AI memory actually works. A beginner's guideHow AI apps remember things between chats, why a bigger context window doesn't solve it, and the parts every memory system shares.
  2. We're open sourcing the company brain. Here's how we designed the multiplayer harnessCompany Brain is now open source. A walkthrough of the multiplayer harness behind its Slack experience, from proactivity and memory boundaries to approvals and recovery.
  3. Jev changes a lot in memory & context engineering. Here's exactly how.We tested Jev across reranking, chunking, observation, and harness decisions. Here is where fast decision models help memory systems, where they cost more, and where they still fall short.
  4. I reverse-engineered Instinct's memory. Here's exactly how it worksInstinct keeps its memory as git-tracked markdown files, found with grep rather than vectors. Here is the whole system as far as black-box probing can reconstruct it, and how to rebuild it on supermemory in about 60 lines.
  5. An update to supermemoryWe've discontinued the supermemory company brain and Nova. Everyone who was charged has been refunded, our MCP and plugins continue to run, and we're going all in on the memory engine.
  6. Scaling Conversations: How Adapta Grew Usage Without Losing ContextAdapta added Supermemory as a persistent memory layer so every conversation keeps its context — letting the team scale usage without losing the thread.
  7. How Chatarmin Ditched RAG and Went Memory-Only with SupermemoryChatarmin replaced a heavy RAG pipeline with Supermemory's memory layer — cutting average AI response time from 40s to 12s and token usage by 40–50%.
  8. SMFS: making agentic retrieval 55% cheaper AND more accurateWe launched SMFS.ai (Supermemory Filesystem) a few weeks ago, with a simple bet: We can redesign the filesystem specifically for agents, with special files, structures, and commands that it can use for it's tasks. Today, SMFS is used by hundreds of companies to power their agents.
  9. Introducing Dynamic Dreaming: supermemory now connects the dots, for you.Dreaming is magical. TLDR: We're launching Dynamic Dreaming in supermemory today, which automatically works if you're using supermemory in any way - API, OpenClaw, Hermes agent, etc.
  10. Dear reader, we just made supermemory insanely cheap... the Context CloudWhen I first started building supermemory, I had one goal: To build the best memory system for AI. I would talk to customers, and find out that memory was not the only thing they needed - They were all setting up 7-8 different vendors at the same time.
  11. Introducing @supermemory/tools v2.0.0Today we're releasing v2.0.0. This release unifies the API across all agents sdk integrations from AI SDK to Mastra, makes conversation identity a first-class concept, and ships with memory saving on by default.
  12. Solving the Precision-Recall Tradeoff: Search Result AggregationWhen you're building memory for AI, search is your foundational layer. The way search generally works is straightforward: the user defines a query, and then sets a limit (top-K) on how many search results they want returned. Usually, this is set to 10 or 20.
  13. OpenClaw Memory Problems: Why It Forgets and How to Fix It (2026)OpenClaw remembers by writing Markdown files in its workspace, so it forgets anything the agent didn't save. Why that breaks down, how the supermemory plugin recalls and saves on every turn instead, and how to install it, free on every plan.
  14. Stateful Coding Agents with Memory: Build Long-Running Agents (2026)We built a plugin for Claude Code and OpenCode that gives your coding agent persistent memory. It remembers your preferences, learns your codebase, and never loses context mid-conversation. The result is an agent you can run for months without starting over.
  15. Clawd / Molt bot's memory SUCKS. We gave it supermemory.I'm the founder of supermemory. Clawd/Molt bot is blowing up right now, with many, many use cases. I set it up, too, and have been using it through telegram. TLDR: just go to https://supermemory.ai/docs/integrations/clawdbot to set up supermemory for your clawd bot.
  16. Catch up with our UNFORGETTABLE Launch WeekOver the last year, one belief has guided almost everything we’ve built at Supermemory AI becomes meaningfully useful only when it remembers. Memory shouldn’t be something developers rebuild from scratch. It shouldn’t be fragile, expensive, or trapped inside a single tool.
  17. Empowering the Next Generation of Founders: Supermemory Startup ProgramIf there’s one thing we’ve learned while building Supermemory, it’s that most startups don’t fail because they didn't build features; they fail when infrastructure slows them down, or they built too slow.
  18. Building code-chunk: AST Aware Code ChunkingAt Supermemory, we're building context engineering infrastructure for AI. A huge part of that is dealing with code: ingesting repos, understanding structure, and making it searchable. The problem is that most code chunking solutions are terrible. We built code-chunk to fix this.
  19. Supermemory raises $3 million with the best memory engine for LLMsToday, I am excited to announce our first funding round to accelerate our mission of building an interoperable, scalable and reliable memory for LLMs and agents. Memory is one of the hardest challenges in AI right now.
  20. Mem0 vs Supermemory: Why Scira SwitchedScira AI moved its production memory layer from Mem0 to Supermemory. This is what failed, what improved, and how the team evaluated the two systems.
  21. Never Record Again: How Montra Uses Supermemory to Rethink Video CreationCampbell Baron, the founder of Montra, has been making videos since he was twelve. By thirteen, he was already doing brand work. Today, he’s betting on a very different future for creators: a world where recording is the exception, and most videos are generated from scratch.
  22. Unified Memory That Works Where You Work: Your Second Brain With SupermemoryHi everyone, I’m Dhravya, the founder of Supermemory. I want to start with a little story behind why this product means so much to me. You can also skip straight to what it is and how it works below.
  23. Supermemory just got faster on PlanetScaleWhat is Supermemory? Supermemory completes the missing part of the LLM puzzle: memory. Just as memory is crucial for human intelligence, it's essential for truly intelligent AI systems.
  24. Faster, smarter, reliable infinite chat: Supermemory IS context engineering.People are obsessed with prompts and prompt engineering. Sure, what you say is important, but what the model knows when you say it is the difference between a stateless text generator and an intelligent AI system. In short, context is the most crucial component.
  25. We solved AI API interoperabilityOne API to rule them all, One spec to find them, One library to bring them all and in the TypeScript, bind them. When we were building the Infinite Chat API, initially, we only supported the OpenAI format. This was fine, until a lot of our customers started asking for more.
  26. The Wow Factor of Memory - How Flow Used Supermemory To Build Smarter, Stickier ProductsOverview: Flow is a note-taking app built around a bold vision: to create a more personal, context-aware writing experience powered by AI. At the heart of this mission is memory.
  27. The UX and technicalities of awesome MCPsLast month, we launched the Supermemory MCP, mostly to test our own infrastructure and get some initial traction. It blew up. To my absolute surprise, the initial launch itself got half a million impressions (!!!). Then, we launched and got #2 on ProductHunt too.
  28. Architecting a memory engine inspired by the human brainLanguage is at the heart of intelligence, but what truly powers meaningful interaction is memory — the ability to accumulate, recall, and contextualize information over time. Large Language Models (LLMs) have mastered language, but memory remains their Achilles’ heel.
YOUR PRIVACY

Change or withdraw any time via Cookie settings in the footer. Read our cookie notice.