For translation, open lesson in new tab and use Chrome translate
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.
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.
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.
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.
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:
trigger=("fraction", 0.5) to SummarizationMiddleware sets the threshold to 50% instead of the default 85% (you can swap in any fraction you want).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.
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.
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:
/large_tool_results/<tool_call_id> on the agent's filesystemToolMessage with a short preview (first and last 5 lines) and a file referenceThe 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.
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 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?
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.
wrap_model_call; it runs before the model sees any messagesmax_input_tokens (the default; configurable via trigger), old messages are partitioned at the keep cutoff and replaced with a summarystate["messages"] is preserved and summarization is tracked in a private _summarization_event fieldmodel.profile["max_input_tokens"] overrides the threshold, making it practical to demo/large_tool_results/ and replacing them with a preview + file reference/conversation_history/ with a preview + file referencewrapModelCall; it runs before the model sees any messagesmaxInputTokens (the default; configurable via trigger), old messages are partitioned at the keep cutoff and replaced with a summarystate.messages is preserved and summarization is tracked in a private _summarizationEvent fieldmodel.profile with Object.defineProperty (a plain assignment won't work) lets you lower the threshold, making it practical to demo/large_tool_results/ and replacing them with a preview + file reference/conversation_history/ with a preview + file referenceComplete 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.
Documentation:
Go deeper: read the source (optional)
The lesson shows how to use this. To see how it's implemented, start with these files:
middleware/summarization.py: summarization, and offloading the summarized historymiddleware/filesystem.py: offloading large tool results and human messagesDocumentation:
Go deeper: read the source (optional)
The lesson shows how to use this. To see how it's implemented, start with these files:
middleware/summarization.ts: summarization, and offloading the summarized historymiddleware/fs.ts: offloading large tool results and human messagesIn 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.
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.
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.
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.
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.
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.