Agent Memory: Context Engineering for AI Agents

By on

A language model remembers nothing between calls. Whatever an agent appears to know at any step is the text in its context window at that moment: the instructions, the tool definitions, the conversation so far and whatever was fetched along the way. Agent memory is everything you build around the model to decide what that text is.

The name for that work is context engineering. Andrej Karpathy described it in June 2025 as "the delicate art and science of filling the context window with just the right information for the next step". Anthropic's engineering team states the goal as "finding the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome".

This article explains why the window needs managing, which kinds of memory an agent has, and three techniques that do most of the work.

Why a larger context window is not the answer

Context windows have grown to a million tokens and more, so it is tempting to keep everything. Two results say why that fails.

Models use the middle of a long input worse than its ends. In Lost in the Middle (2023), Liu and colleagues found that performance is often highest when the relevant information sits at the beginning or the end of the context, and that it "significantly degrades" when the model has to find it in the middle.

Reliability drops as the input grows. Chroma's Context Rot report (July 2025) tested 18 models from Anthropic, OpenAI, Google and Alibaba and found that performance "grows increasingly unreliable as input length grows". Irrelevant but similar text made it worse: "Even a single distractor reduces performance relative to the baseline." In the report's conversational memory test, every model did significantly better on a focused prompt holding only the relevant parts than on the full history.

Anthropic uses the same term, context rot, and describes context as an "attention budget" that the model draws on. There is a plainer cost as well: an agent sends its whole window to the model at every step, so a long history is paid for again on each one.

The aim, then, is to have the right things in the window at each step, and little else.

The kinds of memory an agent has

The CoALA framework (Sumers, Yao, Narasimhan and Griffiths, 2023) borrows its vocabulary from cognitive science: a working memory, and three kinds of long-term memory. They map roughly onto what you build in practice.

MemoryWhat it holdsWhere it lives in an agent
WorkingWhat the agent is using right nowThe context window
EpisodicWhat happened beforeConversation logs, past runs, summaries
SemanticFacts about the world and the userDocuments, a knowledge base, saved preferences
ProceduralHow to do thingsThe system prompt, instruction files, the agent's code

The model only ever sees working memory. Everything else has to be brought into the window before it has any effect. Memory design comes down to two decisions: what to write out of the window, and what to read back in, and when.


flowchart LR
  subgraph Window["Context window"]
      direction TB
      I[Instructions and tools]
      H[Summary of older turns]
      R[Recent messages]
      F[Fetched notes and documents]
  end
  S[("Notes, logs,<br/>knowledge base")]
  R -->|compact| H
  R -->|write| S
  S -->|read on demand| F
  style Window fill:#eef2fc,stroke:#1b3fbf,color:#10204f
  style S fill:#ffffff,stroke:#10204f,color:#10204f

Three techniques that do most of the work

1. Compaction

When a conversation approaches the limit, summarise the older part and carry on with the summary and the most recent messages.

interface Message {
  role: 'system' | 'user' | 'assistant' | 'tool';
  content: string;
}

// A rough estimate, about four characters per token in English. Use your
// provider's token counter where the number matters.
const estimateTokens = (messages: Message[]) =>
  Math.ceil(messages.reduce((total, m) => total + m.content.length, 0) / 4);

// One model call that turns old messages into a short summary.
type Summarize = (messages: Message[]) => Promise<string>;

export async function compact(
  messages: Message[],
  summarize: Summarize,
  { limit = 100_000, keepRecent = 10 } = {},
): Promise<Message[]> {
  if (estimateTokens(messages) < limit) return messages;

  const [system, ...rest] = messages;
  const older = rest.slice(0, -keepRecent);
  const recent = rest.slice(-keepRecent);
  if (older.length === 0) return messages;

  const summary = await summarize(older);

  return [
    system,
    { role: 'user', content: `Summary of the work so far:\n${summary}` },
    ...recent,
  ];
}

The code is the easy part. Three things decide whether compaction works:

  • The summary prompt says what must survive. Decisions made, tasks still open, and exact identifiers such as file names, order numbers and error messages. A summary that says "we discussed the invoice problem" has lost the invoice number.
  • The cut falls on a turn boundary. Most model APIs reject a tool result whose tool call has been summarised away, so keep each call and its result on the same side of the cut.
  • The system prompt stays out of it. Instructions are kept as they are, never summarised.

There is a lighter step to try first: drop old tool results. Raw tool output is usually the bulk of a long conversation and is rarely needed twice. Anthropic reported that clearing stale tool results improved its agents' performance by 29% over the baseline in its own evaluation, and by 39% when combined with a file-based memory tool. In a 100-turn web search test, it cut token use by 84%.

2. Notes outside the window

The agent writes down what it will need later in a place that outlives the conversation, and reads it back when it matters. Anthropic calls this structured note-taking. Its example is Claude playing Pokémon, which keeps tallies across thousands of steps ("for the last 1,234 steps I've been training my Pokémon in Route 1, Pikachu has gained 8 levels toward the target of 10") and picks the game up again after its context is reset.

Notes can be as simple as files in a folder:

import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';

const NOTES_DIR = 'agent-notes';

// Notes are plain files, so a person can read them and correct them.
const notePath = (name: string) =>
  path.join(NOTES_DIR, `${name.replace(/[^a-z0-9-]/gi, '-')}.md`);

export async function saveNote(name: string, content: string) {
  await mkdir(NOTES_DIR, { recursive: true });
  await writeFile(notePath(name), content, 'utf8');
  return `Saved the note "${name}".`;
}

export async function readNote(name: string) {
  return readFile(notePath(name), 'utf8');
}

export async function listNotes() {
  await mkdir(NOTES_DIR, { recursive: true });
  const files = await readdir(NOTES_DIR);
  return files.map((file) => path.basename(file, '.md'));
}

Give the agent these three functions as tools, and put only the list of note names in its instructions. The names cost a few tokens. The contents are loaded when the agent decides it needs them.

3. Just-in-time retrieval

Loading every document up front fills the window with text that is mostly irrelevant to the current step. The alternative is to keep lightweight references in the window, such as file paths, URLs, record identifiers and saved queries, and give the agent tools to load what they point to.

People work the same way. Nobody memorises the filing cabinet; they know which drawer to open.

Retrieval by search belongs here too. Whether it uses keywords or embeddings, retrieval-augmented generation (RAG) is one way of choosing what to bring into the window.

The trade-off is speed and coverage. Each lookup is another step, and an agent cannot fetch what it does not know exists. A mix usually works best: load the small things that are always relevant up front, such as a project's conventions or a user's preferences, and fetch the rest on demand.

What goes wrong with memory

  • The summary drops the one thing that mattered. Test compaction on real transcripts. Run a long task, compact it halfway, and check that the agent can still finish.
  • Old notes are treated as current. A price, a person's role and the state of a ticket all change. Date every note, and have the agent verify anything it is about to act on.
  • Memory carries an attack forward. If an agent saves text from a web page or an email into its notes, an instruction hidden in that text is read again in every later session. Stored content is data, the same as a tool result, and only trusted sources should write to the memory that holds instructions.
  • Memory about people is personal data. If an agent remembers things about its users, they need a way to see it and delete it. In the EU, the GDPR's rights of access and erasure apply to that store as they do to any other.

Where to start

  1. Log the token count of every step and look at what the window is made of. It is usually tool output.
  2. Trim tool results where they are produced.
  3. Clear old tool results, then add compaction with a summary prompt written for your task.
  4. Add notes when the work spans sessions or outgrows one window.
  5. Add retrieval when the knowledge is too large to load.