跪拜 Guibai
← Back to the summary

DeepAgents Memory: Long-Term Files, Session Messages, and Summaries Are Three Different Things

From MemoryMiddleware to SummarizationMiddleware, this clears up the relationship between messages, files, and context archiving.

Recently, while learning and using DeepAgents, I wrote two demos that look similar but are actually not the same thing:

At first I thought that as long as the Agent writes content into a document, it no longer needs to pass old messages later. After digging deeper, I found that there are actually three completely different concepts:

Long-term memory files
Current session messages
Historical message archive

Many of the "I already wrote it to a file, why does the Agent still forget" problems are essentially about mixing these three together.

This article is based on [email protected], and with two pieces of actual code, it explains how MemoryMiddleware and SummarizationMiddleware work in DeepAgents, and the pitfalls you're likely to hit in practice.

Conclusion first

DeepAgents has at least three kinds of "memory":

Type Main carrier Problem it solves Auto-written?
Long-term memory AGENTS.md, preferences.md Keeps project facts and user preferences across sessions No, the Agent needs to call file tools
Session context messages Where the current task is, what tools returned Maintained by the Agent runtime
Summary archive conversation_history/*.md Offline saving and traceability of the full conversation Written automatically by the summarization middleware

The relationship between them can be represented simply as:

Long-term memory files
  → read at startup
  → injected into system prompt

Current messages
  → passed on every turn
  → compressed into a summary when necessary

Old messages
  → archived as-is into history files
  → replaced by a summary message as active context

MemoryMiddleware injects selected long-term memory into the prompt, and SummarizationMiddleware controls session context length. The two middlewares are not substitutes for each other.


1. Long-term memory: writing content into a file does not mean the model automatically knows

First, the core configuration of the first demo:

const workspaceDir = path.join(__dirname, "workspace-memory");

const projectMemoryPath = "/AGENTS.md";
const preferencesMemoryPath = "/memory/preferences.md";

const backend = new FilesystemBackend({
  rootDir: workspaceDir,
  virtualMode: true,
});

const agent = createAgent({
  model,
  tools: [],
  systemPrompt: [
    "You are the project assistant. The workspace root is /. You can use ls, read_file, write_file, edit_file.",
    "When the user asks you to remember, you must update the memory file immediately.",
    `- ${projectMemoryPath}: project description, tech stack, architecture, repository conventions`,
    `- ${preferencesMemoryPath}: user preferences, e.g., language, package manager, response style`,
    "Pay attention to categorization: project facts go to AGENTS.md, not preferences; personal preferences go to preferences.md, not AGENTS.md.",
  ].join("\n"),
  middleware: [
    createFilesystemMiddleware({ backend }),
    createMemoryMiddleware({
      backend,
      sources: [
        projectMemoryPath,
        preferencesMemoryPath,
      ],
    }),
  ],
});

Because virtualMode: true is enabled, these paths eventually map to local files:

/AGENTS.md
→ workspace-memory/AGENTS.md

/memory/preferences.md
→ workspace-memory/memory/preferences.md

What MemoryMiddleware actually does

Every time agent.invoke() starts, createMemoryMiddleware does two things.

First, it reads the files configured in sources:

AGENTS.md
preferences.md

Second, it wraps the file contents into a structure like this and appends it to the system prompt:

<agent_memory>
/AGENTS.md

# Project memory
- This project is a demo for the DeepAgents memory module

/memory/preferences.md

# User preferences
- Preferred package manager is pnpm
</agent_memory>

Note that MemoryMiddleware only reads and injects. It does not proactively analyze what the user said, nor does it create or update files.

What actually writes the files is still the Agent calling:

read_file
write_file
edit_file

So the full chain for "long-term memory" is:

User asks to remember
  → Agent calls file tools
  → content is written into Markdown
  → next invoke
  → MemoryMiddleware reads again
  → content enters the system prompt

Writing and reading are two independent steps.

Why the first run may have no memory

The first prompt in the original code is:

"Based on the memory, what is this project about? Answer in one sentence."

But if workspace-memory is an empty directory, there is no project description yet, so of course the model has no basis.

If it still answers as if it knows, there are usually two possibilities:

  1. The model is guessing;
  2. You reused a working directory left over from a previous run.

For easy reproduction, you can create only missing files at startup, without overwriting existing content:

const projectFile = path.join(workspaceDir, "AGENTS.md");
const preferencesFile = path.join(
  workspaceDir,
  "memory/preferences.md"
);

fs.mkdirSync(path.join(workspaceDir, "memory"), {
  recursive: true,
});

if (!fs.existsSync(projectFile)) {
  fs.writeFileSync(projectFile, "# Project memory\n\n", "utf8");
}

if (!fs.existsSync(preferencesFile)) {
  fs.writeFileSync(preferencesFile, "# User preferences\n\n", "utf8");
}

Creating headings in advance has a benefit: later you can let edit_file append content directly after the heading.

write_file and edit_file cannot be mixed casually

These two tools have completely different semantics.

write_file creates or overwrites the entire file:

write_file("/memory/preferences.md", "I like concise answers")

The original content is completely replaced.

edit_file is a partial string replacement:

old_string: "# User preferences"
new_string: "# User preferences\n- Preferred package manager is pnpm"

Existing content is preserved.

So a safer memory write rule is:

File does not exist → use write_file to create
File exists → first read_file, then use edit_file to update

The corresponding system prompt can be written as:

"When the memory file does not exist, use write_file to create it.",
"When the memory file already exists, never overwrite it with write_file.",
"Read the file before updating, and use edit_file to append or modify the corresponding content.",

If you rely entirely on the model choosing tools on its own, accidental overwrites can still happen. In production, a deterministic memory tool is more appropriate, for example:

appendMemory({
  type: "preference",
  text: "Preferred package manager is pnpm",
});

Let the tool internally handle "read old content + merge + write back", and don't leave all the judgment to natural-language instructions.

Using the same session to answer a question does not prove long-term memory works

The last prompt in the original code runs right after the earlier prompts:

messages: [
  ...messages,
  new HumanMessage({ content: prompt }),
]

In this case, the model can directly see the earlier pnpm and entry-script information from the chat history. Even if MemoryMiddleware completely broke, it might still answer correctly.

To really verify long-term memory, you should simulate a new session:

const rememberPrompts = [
  "Please remember: my preferred package manager is pnpm.",
  "Please remember: the main entry script of this repository is src/deepagents/memory-agent.mjs.",
];

for (const prompt of rememberPrompts) {
  const result = await agent.invoke({
    messages: [new HumanMessage({ content: prompt })],
  });

  console.log("Write result:", result.messages.at(-1)?.content);
}

const freshResult = await agent.invoke({
  messages: [
    new HumanMessage({
      content:
        "What package manager do I prefer? What is the main entry script path of this demo? Answer each in one line.",
    }),
  ],
});

console.log("New session answer:", freshResult.messages.at(-1)?.content);

Here each call passes only a single current message. If the second new session still answers correctly, that shows the content was indeed reloaded from the memory files.


2. Summary memory: compressing session context, not responsible for long-term facts

The second demo uses createSummarizationMiddleware:

const agent = createAgent({
  model,
  tools: [],
  systemPrompt:
    "You are a session assistant. Remember key facts the user mentions, and answer briefly in Chinese.",
  middleware: [
    createSummarizationMiddleware({
      model,
      backend,
      historyPathPrefix: "/conversation_history",
      summaryPrompt,
      trigger: {
        type: "messages",
        value: 8,
      },
      keep: {
        type: "messages",
        value: 4,
      },
    }),
  ],
});

The configuration here means:

Since each normal conversation turn produces one HumanMessage and one AIMessage, the actual process is as follows:

Turn Messages before model call Summarized?
User says the cat is called Little Orange 1 No
User says they live in Beijing 3 No
User says they like lattes 5 No
User says their birthday 7 No
Final question 9 Yes

After the first four turns are done, the state already has 8 messages, but there is no next model call yet. When the fifth user question is added, it becomes 9, and summarization triggers.

Old messages are not actually deleted from state

This is the part of SummarizationMiddleware that is often misunderstood.

It does not directly clear the entire messages array. Instead it:

  1. Archives the old raw messages to Markdown;
  2. Generates a summary HumanMessage;
  3. Records _summarizationEvent in the state, containing the cutoff and the summary message;
  4. On the next model call, constructs only "summary + messages after the cutoff" as the model input.

You can think of it as:

Full state.messages
  = old messages + recent messages + this turn's AI reply

Actual messages sent to the model
  = summaryMessage + recent messages after the cutoff

So when you print after summarization:

console.log(messages.length);

You still see the number of messages in the full state, not the compressed model input. With the configuration above, after the fifth turn ends, the full message count continues to grow, but the context the model actually sees has been compressed.

What history files, summary messages, and long-term memory each handle

After summarization completes, you get an archive file like this:

workspace-summarization/conversation_history/session_xxx.md

The file stores the original raw conversation, suitable for on-demand tracing.

Meanwhile, the summarization middleware adds a message to the current session like this:

The earlier conversation has been summarized.

Full history is saved at:
/conversation_history/session_xxx.md

Summary:
The user is maintaining a DeepAgents demo.
The user asked to remember the pet's name, city, drink preference, and birthday in sequence.

Do not confuse these three objects:

conversation_history files
→ complete, but not automatically injected into the current prompt

summaryMessage
→ automatically enters the current model input, keeps task continuity with fewer tokens

AGENTS.md / preferences.md
→ cross-session long-term facts, actively injected by MemoryMiddleware

Summary files are not long-term memory files. They do not automatically appear in future new sessions just because they exist on disk.

If you want the Agent to read the full history on demand after summarization, you also need to add file-system tools:

middleware: [
  createSummarizationMiddleware({
    // ...
  }),
  createFilesystemMiddleware({ backend }),
],

Otherwise the summary message tells the model "full history is saved to such path", but the model has no read_file tool and actually cannot read it.

Don't persist only messages as the session state

The original code updates the session like this:

let messages = [];

for (const prompt of prompts) {
  const result = await agent.invoke({
    messages: [
      ...messages,
      new HumanMessage(prompt),
    ],
  });

  messages = result.messages;
}

But the summarization middleware also writes, besides messages:

_summarizationEvent
_summarizationSessionId

If each time you only pass messages back, the summarization cutoff event is lost. Subsequent calls may treat the full history as unsummarized content again, causing repeated summarization and repeated archiving.

Without a checkpointer, you can preserve the full state:

let state = {
  messages: [],
};

for (const prompt of prompts) {
  state = await agent.invoke({
    ...state,
    messages: [
      ...state.messages,
      new HumanMessage(prompt),
    ],
  });
}

A better approach is to use the LangGraph checkpointer and maintain session state through a fixed thread_id:

const config = {
  configurable: {
    thread_id: "deepagents-memory-demo",
  },
};

await agent.invoke(
  {
    messages: [new HumanMessage(prompt)],
  },
  config
);

3. Why the Agent still needs messages even after writing documents

This question can be broken into two sentences:

Documents store persistent data; messages store the context visible to the current model call.

The model does not automatically traverse the disk and find all relevant Markdown. It can only see the current request's:

system prompt
messages
tools

MemoryMiddleware actively reads the configured sources, so those files can enter the system prompt.

But files usually hold only a small amount of long-term facts, such as:

- User prefers pnpm
- Project entry is src/deepagents/memory-agent.mjs

Real tasks also need to know:

- Which file is currently being modified
- Which commands were just run
- Which test failed
- What tools returned
- What temporary constraints the user just added
- What the next step is

These don't necessarily all belong in AGENTS.md, but they matter a lot for the current task.

If you rely only on the Agent writing long-term memory, two outcomes are possible:

  1. The user didn't explicitly say "please remember", so the Agent didn't write;
  2. The Agent writes too much temporary information, and long-term memory inflates quickly.

The summarization middleware fills this gap: it automatically preserves the current working context without requiring every piece of information to become permanent memory.

So:

MemoryMiddleware
→ handles "facts that will be used later"

SummarizationMiddleware
→ handles "context that the current task still needs"

4. Several pitfalls when actually using it

1. When a long-term memory file doesn't exist, edit_file fails

edit_file cannot be used to create a new file. The first write must use write_file, or you have to create an empty file with headings in advance.

2. Using write_file to update existing memory overwrites old content

Memory file merging should prefer edit_file, or merge old content inside a custom tool and write back.

3. Keeping old messages globally can mask memory test results

If the final query and the writes happen in the same session, the model may simply see the answer from chat history. To verify persistent memory, use a new session.

4. Summary archives are not long-term memory

Summarized history is not automatically injected into new sessions. It needs file tools to read on demand, or needs to be processed into structured long-term memory by a program.

5. After summarization, don't manually rebuild a half state that lost events

When using the summarization middleware, either keep the full LangGraph state or use a checkpointer with thread_id. Saving only messages loses the summary cutoff and session ID.

6. Don't treat everything as long-term memory

It is recommended to layer as follows:

Content Recommended location
User language, response style, package manager preferences.md
Project stack, directory structure, repo conventions AGENTS.md
Current task steps, tool return values active messages
Full conversation history conversation_history/*.md
Temporary verification codes, access tokens, passwords do not write to any memory file

Long-term memory also needs version management and human review. Especially for multi-user Agents, don't let the model write arbitrary content into permanent instructions without limits.


Summary

After studying the DeepAgents memory module this time, the biggest takeaway for me is not how the API is called, but first distinguishing the layers of "memory":

Long-term facts go to files
Current context goes to messages
Full history goes to archives
Summarize when context gets too long

MemoryMiddleware injects long-term files into the prompt at the right time, but doesn't write files for the Agent.

SummarizationMiddleware archives old messages and compresses them into a summary, but the history files it saves are not automatically effective long-term memory.

As for "why the Agent still needs old messages after it has already written documents", the answer is actually simple:

Documents persist information; messages make information visible to the model in the current inference.

The two solve different problems.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

用户6962308367965

Learned something, now I have a preliminary understanding.