Autonomous context compression: the agent decides when to forget

Autonomous context compression: the agent decides when to forget
85%of the context limit: when Deep Agents compacts by default
10%of the context: the recent messages kept when summarizing
5situations when compacting makes sense
0autonomous compactions in Terminal Bench 2
Your AI agent should decide when to forget: LangChain's autonomous context compression
I also cover it in this seven-minute video on my Articulator EN channel.

What context compression islink

An agent works with a limited memory: its context window, which holds the instructions, the conversation, the tool results and everything it has read. Compressing the context means replacing older messages with a summary of the work so far that keeps only what matters for the task.

It's needed for two reasons. The first is obvious: context windows are finite, and a long task eventually fills them. The second is less obvious: the fuller the window gets, the worse the model works with it. This is known as context rot.

Two reasons: a full context window marked as finite, and a curve where the model's quality drops as more context is used.
The window is finite, and the fuller it gets, the worse the model works.

The fixed-threshold problemlink

Usually the harness, the software that wraps the model, controls compression with a fixed token threshold. Deep Agents, for example, uses model profiles to compact once it reaches 85% of each model's context limit.

A gauge reaching 85% of the context limit, Deep Agents' fixed threshold, with the window already summarized next to it.
Deep Agents compacts at 85% of each model's limit.

The article explains why that isn't ideal: there are good times and bad times to compact, and a threshold can't tell them apart.

  • Bad time: in the middle of a complex refactor. The agent loses the details exactly when it needs them most.
  • Good time: when starting a new task, or when the earlier context is about to stop being useful.

A tool for the agentlink

Many agentic coding tools have a /compact command so the user can compress the context by hand when it seems right. LangChain goes one step further: it gives the agent a tool to trigger compression itself.

The advantage is that it compacts at the right moment without your application's users needing to know the context is finite, or to type any command.

A robot that calls the compact_conversation tool and leaves its context summarized, next to a user typing /compact by hand.
From typing /compact by hand to a tool the agent calls on its own.

There's a bigger idea behind it. LangChain believes the harness should get out of the way whenever it can and take advantage of models that keep reasoning better. It's the well-known bitter lesson: instead of tuning the harness by hand with ever finer rules, give the agent more control over its own context.

When to compact: five situationslink

If the agent decides, when should it do it? The article groups the good moments into five situations:

1. When switching tasks

The user moves on to something for which the earlier context is probably useless, or the agent finishes a deliverable and the user accepts it.

2. After extracting a result

The agent has obtained a fact, a conclusion or a summary by consuming a lot of context, as in a research task.

3. Before a lot of new context

It's about to write a long draft or read many documents.

4. Before a long process

It's about to start a refactor, a migration, a multi-file edit or an incident response; for example, once it has the plan and is about to execute it.

5. A decision changes everything

New requirements arrive that invalidate the earlier context, or there are many tangents and dead ends that fit in a summary.

The five situations in a row and, below, the fifth: new requirements that make the conversation obsolete, plus tangents and dead ends.
The five situations; below, the fifth, when a decision supersedes everything before it.

Listing every case isn't practical, but according to LangChain, people and language models can recognize them. That's why they explain these criteria to the model in the tool's instructions. And compacting in time has an extra benefit: it avoids having to do it by force later, when the window is about to fill up.

What happens when the tool is calledlink

The tool works just like the automatic summarization Deep Agents already had, with the same parameters:

  • Recent messages are kept: 10% of the available context. They include the tool call itself and its response.
  • Everything before is summarized: it all becomes a single summary message.
  • Nothing is lost: the original messages are saved to a file, /conversation_history/{thread_id}.md, in the agent's virtual filesystem.
  • The summary carries a pointer: the context keeps the summary with a reference to that file, in case the agent needs to go back to the details.
The compaction diamond saves the originals to a folder, and the context keeps the summary with a pointer, the query, the tool call, its result and the response.
Summary with a pointer on top, recent messages below and the originals in the filesystem.

It's my favorite part of the design: summarizing isn't forgetting, it's storing things somewhere else.

How to use itlink

In the Deep Agents command line tool (Deep Agents CLI) it's already turned on. In the Python library it's opt-in: it's a separate middleware you add to the middleware list when creating the agent. This is the article's example:

from deepagents import create_deep_agent
from deepagents.backends import StateBackend
from deepagents.middleware.summarization import (
    create_summarization_tool_middleware,
)

backend = StateBackend  # if using default backend
model = "openai:gpt-5.4"
agent = create_deep_agent(
    model=model,
    middleware=[
        create_summarization_tool_middleware(model, backend),
    ],
)

And in the command line tool you can also type /compact yourself whenever you want to trim the context or switch tasks.

On the left, the Deep Agents terminal with compact_conversation enabled; on the right, the Python code with the opt-in middleware.
Enabled in the command line tool, opt-in in the library.

How they tested itlink

LangChain tuned the tool to be conservative. Deep Agents keeps the full history, so context can be recovered after summarizing, but a compression at the wrong moment disrupts the work. They tested it three ways:

  1. Their own evaluation suite: on real conversations, taken from their LangSmith traces, they injected follow-up prompts; some called for compaction and some didn't.
  2. Terminal Bench 2: a benchmark of terminal tasks, where the agent never compacted on its own, not even once.
  3. Their own coding tasks with the Deep Agents command line tool.
Three cards: the custom evaluation suite with conversations that did and didn't call for compaction, Terminal Bench 2 with zero autonomous compactions, and the coding tasks.
Three tests; in Terminal Bench 2, zero autonomous compactions.

The result? Agents are cautious and compact rarely. But when they do, they tend to pick moments where the workflow clearly improves.

Is it a bad sign that it never compacted?link

That zero in Terminal Bench caught my attention. If you let the model decide when to compact and it never does, at first sight it looks like bad news. The article doesn't explain it, so I checked it against the Deep Agents code, and I think it's not necessarily a bad sign, for two reasons.

First: those moments never come. The tool is meant for clear moments, such as when the user switches tasks or when the agent already has the result it was after. In Terminal Bench, each test is a single task, from start to finish, with no change of topic. And compressing in the middle of a task is exactly the mistake they wanted to avoid.

The two clear moments on top and, below, the bar of a Terminal Bench test broken in red by a mid-task compression.
Each test is a single task: compressing mid-task would be the mistake they wanted to avoid.

Second: not compacting doesn't mean overflowing. In the code, the tool won't even agree to compress until the conversation reaches half the threshold; before that it replies "Nothing to compact yet". And the tool is added to automatic summarization, not a replacement for it: create_deep_agent always includes it, so when the window fills up, the automatic summarization at 85% keeps working as a safety net.

A context window gauge with the half-threshold mark, the compact_conversation call available and automatic summarization at 85% as a safety net.
The tool requires half the threshold; automatic summarization at 85% is still there.

What the article doesn't give is numbers: we don't know how many times the agent should have compacted and didn't. So the zero doesn't prove the tool works, but it doesn't prove it fails either.

A broader directionlink

Autonomous context compression is a small feature, but it points to a broader direction in agent design: giving models more control over their own working memory and fewer rigid, hand-tuned rules in the harness.

A brain with more control over its working memory next to a ring with hand-written rules crossed out.
More control for the model, fewer hand-tuned rules in the harness.
In one sentence

Instead of always compacting at 85%, the agent decides when to summarize its context and picks the moments when it helps.

Would you let your agent decide when to forget?

Sourceslink

Continue reading

Last posts -->

Have you seen these projects?

Gymnasia

Gymnasia Gymnasia
Expo
React Native
TypeScript
OpenAI
Anthropic

Fitness app with two agents that run entirely on the device, with no backend, so the user's data never leaves the phone. A BYOK conversational coach with local tools and a remote system prompt with offline fallback, plus a food estimator that pulls macronutrients out of a photo of the plate, with barcode scanning against OpenFoodFacts.

LangGraph Deep Researcher

LangGraph Deep Researcher LangGraph Deep Researcher
Python
LangGraph
FastAPI
React
TypeScript
Docker

Multi-agent research system built with LangGraph. A supervisor breaks your question down into topics and launches search sub-agents in parallel; each one compresses its findings before handing them to a writer agent that produces the final sourced markdown report. Live streaming over WebSockets, a configurable model per role and bring-your-own API keys that are never persisted server-side.

Tau

Tau Tau
Python
LangChain

Multi-agent tutoring system for secondary school students, with one agent per subject and course material written and validated by a team of teachers. It was used with real students at a private school in Spain and at a secondary school in Colombia.

View all projects -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to watch any talk?

Last talks -->

Do you want to improve with these tips?

Last tips -->

Use this locally

Hugging Face spaces allow us to run models with very simple demos, but what if the demo breaks? Or if the user deletes it? That's why I've created docker containers with some interesting spaces, to be able to use them locally, whatever happens. In fact, if you click on any project view button, it may take you to a space that doesn't work.

Flow edit

Flow edit Flow edit

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
View all containers -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to train your model with these datasets?

short-jokes-dataset

HuggingFace

Dataset with jokes in English

Use: Fine-tuning text generation models for humor

231K rows 2 columns 45 MB
View on HuggingFace →

opus100

HuggingFace

Dataset with translations from English to Spanish

Use: Training English-Spanish translation models

1M rows 2 columns 210 MB
View on HuggingFace →

netflix_titles

HuggingFace

Dataset with Netflix movies and series

Use: Netflix catalog analysis and recommendation systems

8.8K rows 12 columns 3.5 MB
View on HuggingFace →
View more datasets -->