For translation, open lesson in new tab and use Chrome translate

Summarization and Context Offloading

Offloading and Summarization in 5 minutes
Lesson Video Walkthrough

The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.

Summarization: old messages below the keep cutoff are replaced by a Σ Summary block in the context window. Offloading: large Tool Result and Human Message inputs are intercepted by FilesystemMiddleware, stored on the filesystem, and replaced with a preview pointer in the context window.


Long-running agents build up long message histories, and Deep Agents handles this in two ways. Summarization condenses older messages once the context window fills up. Offloading catches large tool results and human messages before they reach the model, saves the full content to the filesystem, and leaves a short pointer in its place.


Summarization

How the context window fills up

Think of the context window like a thermometer. Every new message adds tokens and the level rises. When it crosses 85% of the model's limit, by default, the middleware fires.

Note: in Python deepagents 0.7.0, the version the Python labs pin, this file is named /conversation_history/{thread_id}.md. Newer Python versions and the TypeScript SDK name it by session ID instead.


What the summary contains

The middleware makes a separate LLM call to generate the summary. It uses a structured prompt that asks the model to extract:

The resulting text is injected as a single HumanMessage at the top of the preserved recent messages. The middleware also embeds a link to the saved older sections, so the agent can retrieve them with read_file if it needs the detail.


Seeing it in action

Lesson Video Walkthrough

The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.

The default trigger is 85% of the model's real context window: 170,000 tokens for Claude Haiku 4.5.

As of deepagents 0.7:

To observe the default in a demo we set the model's reported context window to a small value so the threshold is hit after a few turns:

# python/m3/m3.1_summarization.py
from models import model

# Lower the reported context window so summarization fires at ~595 tokens
# (85% of 700) instead of the real threshold. Must pass model object, not string.
model.profile = {**model.profile, "max_input_tokens": 700}

agent = create_deep_agent(
    model=model,
    checkpointer=MemorySaver(),
    system_prompt="You are a helpful assistant. Keep every response to one sentence.",
)

Because this demo uses separate ainvoke() calls, it relies on the runtime pattern from Module 1: a checkpointer plus the same thread_id lets message history accumulate across turns. Without either piece, there would be much less history to summarize.

From the repo root:

cd python
uv run python m3/m3.1_summarization.py
// typescript/m3/m3.1_summarization.ts
import { createDeepAgent } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";

import { model } from "../models.js";

// Shrink the reported context window so summarization triggers at ~340 tokens
// (85% of 400) instead of the real threshold. Must use model object, not string.
Object.defineProperty(model, "profile", {
  value: { ...model.profile, maxInputTokens: 400 },
  configurable: true,
});

const agent = createDeepAgent({
  model,
  checkpointer: new MemorySaver(),
  systemPrompt: "You are a helpful assistant. Keep every response to one sentence.",
});

Because this demo uses separate agent.invoke() calls, it relies on the runtime pattern from Module 1: a checkpointer plus the same thread_id lets message history accumulate across turns. Without either piece, there would be much less history to summarize.

From the repo root:

cd typescript
pnpm tsx ./m3/m3.1_summarization.ts

Expected output:

──────────────────────────────────────────────────
Turn 1  User:  My name is Alex. I work at Acme Corp.
Turn 1  Agent: Hello Alex, it's nice to meet you - welcome from Acme Corp!
  stored : 2 message(s) (raw history, never trimmed)

──────────────────────────────────────────────────
Turn 2  User:  What is 2 + 2?
Turn 2  Agent: 2 + 2 equals 4.
  stored : 4 message(s) (raw history, never trimmed)

──────────────────────────────────────────────────
Turn 3  User:  I have been building a distributed cache for three months.
Turn 3  Agent: That sounds like a substantial project - distributed caches are complex but rewarding to build!
  stored : 6 message(s) (raw history, never trimmed)
  model saw : summary + messages[4:]  [SUMMARIZED]

──────────────────────────────────────────────────
Turn 4  User:  What is the capital of France?
Turn 4  Agent: The capital of France is Paris.
  stored : 8 message(s) (raw history, never trimmed)
  model saw : summary + messages[4:]  [SUMMARIZED]

──────────────────────────────────────────────────
Turn 5  User:  What do you remember about me?
Turn 5  Agent: You mentioned your name is Alex, you work at Acme Corp, and you've been building a distributed cache for three months.
  stored : 10 message(s) (raw history, never trimmed)
  model saw : summary + messages[4:]  [SUMMARIZED]

Passing model not MODEL. Notice create_deep_agent(model=model, ...) receives the model object, not the string "anthropic:claude-haiku-4-5". Passing the string would re-initialize the model internally and ignore the profile override.

Passing model not MODEL. Notice createDeepAgent({ model, ... }) receives the model object, not the string "anthropic:claude-haiku-4-5". Passing the string would re-initialize the model internally and ignore the Object.defineProperty override above.

When summarization fires, a private _summarization_event key appears in the agent's state. In the normal summarization path, the raw state["messages"] history is not replaced by the summary; summarization changes what gets sent to the model each turn.

When summarization fires, a private _summarizationEvent key appears in the agent's state. In the normal summarization path, the raw state.messages history is not replaced by the summary; summarization changes what gets sent to the model each turn.


Offloading

Lesson Video Walkthrough

The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.

Summarization compacts messages that have already accumulated in context. Offloading handles a different case: a single large input. Instead of letting it land in context, FilesystemMiddleware intercepts oversized content before it reaches the model. It writes the full data to the filesystem and leaves behind a short preview plus a file path. The agent reads the full content with read_file only when it needs it.

Two kinds of data are offloaded this way: large tool results and large human messages.

Tool result offloading

A single tool call can return a large result, such as a full database export, hundreds of search matches, or a long code generation output. Storing it inline would use a large share of the context window at once.

FilesystemMiddleware handles this automatically with tool result offloading. When a tool returns a result that exceeds roughly 20,000 tokens, the middleware:

  1. Writes the full result to /large_tool_results/<tool_call_id> on the agent's filesystem
  2. Replaces the inline ToolMessage with a short preview (first and last 5 lines) and a file reference

The message the model actually sees looks like this:

Tool result too large, the result of this tool call <id> was saved in the
filesystem at this path: /large_tool_results/<tool_call_id>

You can read the result from the filesystem by using the read_file tool,
but make sure to only read part of the result at a time.

Here is a preview showing the head and tail of the result:

     1  | SELECT id, name, email FROM users WHERE ...
     2  | 1, Alice, alice@example.com
     3  | 2, Bob, bob@example.com
     4  | 3, Carol, carol@example.com
     5  | 4, Dave, dave@example.com
... [1 823 lines truncated] ...
  1828  | 1827, Zara, zara@example.com
  1829  | 1828, Zoe, zoe@example.com
  1830  | 1829, ...

The agent can then call read_file with offset and limit to page through the full result on demand - reading only the portion that is relevant rather than loading everything into context at once.

The tools ls, glob, grep, read_file, edit_file, and write_file are excluded from offloading. They either have their own built-in truncation, return minimal confirmation text, or (for read_file) re-reading a truncated file would not help.

Human message offloading

The same mechanism applies when a user message is very large, for example pasting in a long document or transcript. When a human message exceeds roughly 50,000 tokens, FilesystemMiddleware writes the full text to /conversation_history/ and replaces it in the model's view with a preview and a file reference. The agent can read_file that path to retrieve the full message on demand.

The behavior the agent sees, a preview plus a pointer, is identical to a tool result. Only the threshold (50k vs 20k tokens) and the storage location differ.

Offloaded tool results and conversation history are written through whatever backend= the agent already has. The default StateBackend keeps them thread-scoped; route default= to a real disk or store backend via CompositeBackend to share them across threads.

LangChain

LangChain Blog

How Harmonic rebuilt Scout on Deep Agents

Harmonic rebuilt its Scout agent on filesystem-based context offloading, writing large results to disk and paging them back in on demand. Week one-to-four retention jumped 4x, and average session length increased 10x.

Optional: want to go deeper?

Optional: Context Retrieval and Memory for Agents (video)

This video is optional. It goes deeper on information retrieval: how an agent decides what reaches its context window in the first place, before summarization or offloading are needed. You don't need it for this lesson's lab or homework.


Recap

Next

Complete the Quiz above, then continue to the next lesson on skills: how to package reusable agent behaviours so the model can load them on demand.


References

Documentation:

Go deeper: read the source (optional)

The lesson shows how to use this. To see how it's implemented, start with these files:

Documentation:

Go deeper: read the source (optional)

The lesson shows how to use this. To see how it's implemented, start with these files:

Check your understanding

Question: Your model's profile reports max_input_tokens = 200,000 and you keep the default summarization settings. Around what total does summarization first fire?
A) About 100,000 tokens
B) About 200,000 tokens
C) After 20 messages
D) About 170,000 tokens
Question: How is the summary itself generated when SummarizationMiddleware fires?
A) By truncating the oldest messages until the token count drops below the limit
B) By a fixed template that extracts the first sentence of each message
C) By a separate LLM call using the same model as the agent
D) By the agent model as part of generating its next response
Question: Where does the generated summary appear in what the model receives?
A) Appended to the system prompt as an extra instruction block
B) As an AIMessage the agent writes to itself before continuing
C) As a ToolMessage returned by a built-in summarize tool
D) As a HumanMessage placed ahead of the kept recent messages
Question: Summarization has fired twice on a thread. You inspect the raw state["messages"] list. What do you expect to find?
A) Only the latest summary message followed by the kept recent messages
B) Every original message; only what is sent to the model changes
C) Only the kept recent messages, with the summary in the system prompt
D) Two summary messages, one per firing, followed by the recent messages
Question: You set model.profile["max_input_tokens"] to 700 on a model object, then call create_deep_agent(model="anthropic:claude-haiku-4-5"). Summarization never fires in your short demo. Why?
A) Profile overrides only take effect after summarization fires once on its own
B) Summarization only reads the profile when you pass a trigger argument too
C) The string builds a fresh model instance, so your edited object is unused
D) The string form turns off SummarizationMiddleware for Anthropic models
Question: After summarization, the agent needs an exact detail from early in the conversation that the summary left out. What can it do?
A) Nothing; evicted messages are dropped once the summary replaces them
B) Ask the checkpointer to replay the thread from its very first message
C) Call read_file on the conversation history file named in the summary
D) Call a built-in expand_summary tool to regenerate the full summary
Question: Your model's profile reports maxInputTokens = 200,000 and you keep the default summarization settings. Around what total does summarization first fire?
A) About 100,000 tokens
B) About 200,000 tokens
C) After 20 messages
D) About 170,000 tokens
Question: How is the summary itself generated when SummarizationMiddleware fires?
A) By truncating the oldest messages until the token count drops below the limit
B) By a fixed template that extracts the first sentence of each message
C) By a separate LLM call using the same model as the agent
D) By the agent model as part of generating its next response
Question: Where does the generated summary appear in what the model receives?
A) Appended to the system prompt as an extra instruction block
B) As an AIMessage the agent writes to itself before continuing
C) As a ToolMessage returned by a built-in summarize tool
D) As a HumanMessage placed ahead of the kept recent messages
Question: Summarization has fired twice on a thread. You inspect the raw state.messages list. What do you expect to find?
A) Only the latest summary message followed by the kept recent messages
B) Every original message; only what is sent to the model changes
C) Only the kept recent messages, with the summary in the system prompt
D) Two summary messages, one per firing, followed by the recent messages
Question: You override the model object's profile with Object.defineProperty so maxInputTokens is 400, then call createDeepAgent({ model: "anthropic:claude-haiku-4-5" }). Summarization never fires in your short demo. Why?
A) Profile overrides only take effect after summarization fires once on its own
B) Summarization only reads the profile when you pass a trigger argument too
C) The string builds a fresh model instance, so your edited object is unused
D) The string form turns off SummarizationMiddleware for Anthropic models
Question: After summarization, the agent needs an exact detail from early in the conversation that the summary left out. What can it do?
A) Nothing; evicted messages are dropped once the summary replaces them
B) Ask the checkpointer to replay the thread from its very first message
C) Call read_file on the conversation history file named in the summary
D) Call a built-in expand_summary tool to regenerate the full summary

Trigger Chained Summarization

In the lesson, SummarizationMiddleware compressed a short demo conversation once the context window filled past 85%. On a long enough conversation, it fires again and again. Each new summary builds on the previous one, and every evicted message is added to a single backend file, /conversation_history/{thread_id}.md.

In this homework, you'll write a conversation long enough to trigger summarization at least twice. Then check two things: the model can still recall a detail from your very first turn, and the conversation history file has more than one "Summarized at ..." section.

Open python/m3/m3.1_homework.py.

  1. TODO 1: write your own list of at least 8 user turns about a topic you pick. Put a concrete detail in one of your first two turns, keep talking about the topic for several more turns, then end with a turn that asks the agent to recall that early detail.
  2. TODO 2: choose model.profile["max_input_tokens"] so that summarization fires at least twice before your last turn, not just once. Keep it in the low thousands (the reference copy uses 3000 for ten turns). If you set it much lower, summarization fires on nearly every turn. Each summary then gets compacted away before the next one lands, and the final recall question fails.

Note: a "Summarized at ..." heading can sometimes appear with nothing under it. Before saving, the middleware leaves out the previous summary, because the messages it summarized are already in the file. If summarization fires again before any new messages have built up, for example with a low max_input_tokens or two summarizations in one turn, that previous summary is all there is to save, so the new section is empty. A duplicated section can also appear if the agent reads its own history file with read_file. Neither means something is wrong with your code.

The script's event count and the number of "Summarized at ..." sections can differ. Each summarization writes one section, but the script only checks for a new event once per turn, so two summarizations inside the same turn are counted as one. Treat the event count as a lower bound rather than an exact tally.

Run it

cd python
uv run ./m3/m3.1_homework.py

Stuck, or want to see the finished shape before you start? m3.1_homework_filled.py is a reference copy with every TODO filled in (using a backyard-vegetable-garden planning conversation); run it the same way to see what "done" looks like end to end.

Try to avoid peeking unless you're really stuck. You'll get more out of this by working through the TODOs yourself first.

Trigger Chained Summarization

In the lesson, SummarizationMiddleware compressed a short demo conversation once the context window filled past 85%. On a long enough conversation, it fires again and again. Each new summary builds on the previous one, and every evicted message is added to a single backend file, /conversation_history/{session_id}.md.

In this homework, you'll write a conversation long enough to trigger summarization at least twice. Then check two things: the model can still recall a detail from your very first turn, and the conversation history file has more than one "Summarized at ..." section.

Open typescript/m3/m3.1_homework.ts.

  1. TODO 1: write your own list of at least 8 user turns about a topic you pick. Put a concrete detail in one of your first two turns, keep talking about the topic for several more turns, then end with a turn that asks the agent to recall that early detail.
  2. TODO 2: choose model.profile.maxInputTokens (set with Object.defineProperty) so that summarization fires at least twice before your last turn, not just once. Keep it in the low thousands (the reference copy uses 3000 for ten turns). If you set it much lower, summarization fires on nearly every turn. Each summary then gets compacted away before the next one lands, and the final recall question fails.

Note: a "Summarized at ..." heading can sometimes appear with nothing under it. Before saving, the middleware leaves out the previous summary, because the messages it summarized are already in the file. If summarization fires again before any new messages have built up, for example with a low max_input_tokens or two summarizations in one turn, that previous summary is all there is to save, so the new section is empty. A duplicated section can also appear if the agent reads its own history file with read_file. Neither means something is wrong with your code.

The script's event count and the number of "Summarized at ..." sections can differ. Each summarization writes one section, but the script only checks for a new event once per turn, so two summarizations inside the same turn are counted as one. Treat the event count as a lower bound rather than an exact tally.

Run it

cd typescript
pnpm tsx ./m3/m3.1_homework.ts

Stuck, or want to see the finished shape before you start? m3.1_homework_filled.ts is a reference copy with every TODO filled in (using a backyard-vegetable-garden planning conversation); run it the same way to see what "done" looks like end to end.

Try to avoid peeking unless you're really stuck. You'll get more out of this by working through the TODOs yourself first.