Every agent framework that runs long enough hits the same wall. The context window fills up. The model starts drifting. It forgets what the user asked three turns ago. It repeats actions it already tried. It hallucinates facts that contradict earlier results.

The standard fix is to compact at a fixed threshold. When context hits 85% of the window, summarize everything before the last few turns. Tidy. Predictable. Wrong.

LangChain's Deep Agents SDK just shipped a different approach: give the model a tool that lets it compact its own context when it decides the time is right. The feature is called autonomous context compression, and it represents a fundamental shift in how we think about agent memory management.

The Problem With Fixed Thresholds

Most agent harnesses compact context at a fixed token threshold. Deep Agents itself used to do this at 85% of the model's context window. The logic is straightforward: when context gets too long, summarize the old stuff and keep recent messages.

But timing matters. A lot.

Compacting in the middle of a complex refactor is destructive. The model loses the chain of reasoning it was following. It forgets which files it has already modified and which ones still need changes. It cannot pick up where it left off because "where it left off" just got summarized into a vague paragraph.

Compacting at a clean task boundary is ideal. The user says "now do something else." The previous task's context is largely irrelevant. A summary preserves the key outcomes while freeing 90% of the tokens.

The problem is that a fixed threshold does not distinguish between these situations. It fires at 85% whether the agent is mid-refactor or between tasks. The result is either premature compaction that destroys useful context, or delayed compaction that lets the agent drift.

This is what LangChain calls "the bitter lesson" of agent harnesses: hand-tuned rules that look clever in testing underperform giving the model more control over its own behavior. The fixed threshold is a hand-tuned rule. The model can make a better decision about when to compact because the model has local knowledge about what it is doing right now.

How Autonomous Compression Works

The Deep Agents SDK exposes a tool called the summarization tool. It is implemented as middleware that the agent can call like any other tool. When the model decides the context needs compression, it calls this tool. The middleware then:

  1. Retains the most recent 10% of the conversation as-is.
  2. Summarizes everything before that into a structured summary that includes session intent, artifacts created, and next steps.
  3. Preserves the complete original conversation history in the filesystem, so nothing is truly lost.

The model sees a much shorter context. The agent can still retrieve specific details from the filesystem if needed. The compression is lossy in the working memory but lossless in the persistent store.

This is not theoretical. LangChain tested it in three ways:

A custom evaluation suite that injects follow-up prompts into threads that do and do not warrant compaction. This tests whether the model correctly identifies compaction moments.

Terminal-bench-2, where no autonomous compaction events were observed. The model was conservative about triggering compression, which is the right default for a general coding agent.

Internal coding tasks in the Deep Agents CLI, where agents did compress at natural task boundaries.

The key finding: models are conservative about triggering compaction. They do not compact randomly or eagerly. When they do compact, they choose moments that clearly improve the workflow.

When the Model Chooses to Compact

LangChain identified five categories of situations where compaction makes sense.

Clean task boundaries. The user signals they are moving on. "Now refactor the authentication module" after finishing a feature. The previous task's detailed context is no longer needed.

After extracting results. A research task consumed 50,000 tokens of documents to find a specific statistic. The statistic is what matters now. The raw documents can be summarized away.

Before consuming large new context. The agent is about to read a 30,000-token file or generate a long draft. Compacting first ensures there is room for the new content.

Before a complex multi-step process. The agent has produced a plan and is about to execute it. The planning discussion is less relevant than the plan itself. Compacting preserves the plan while freeing space for execution context.

When context becomes stale. New requirements have come to light that invalidate previous context. There are tangents and dead ends that can be collapsed into a summary.

None of these are triggered by a token count. They are triggered by semantic understanding of the task flow. The model recognizes them because the model is the one doing the task.

The Bitter Lesson Applied

Rich Sutton's "bitter lesson" in AI research is that methods that leverage computation and search ultimately outperform methods that rely on human knowledge and hand-crafted heuristics. Applied to agent design, this means: stop building harnesses with hand-tuned rules about when to compact, how much to keep, and what to summarize. Give the model the tools to manage its own context and let the improving reasoning capabilities of frontier models figure out the rest.

This does not mean removing all guardrails. The autonomous compression tool is tuned conservatively. The model does not get to decide what information is preserved in the summary. The summarization prompt is deterministic and structured. The original conversation history is always recoverable from the filesystem.

What the model decides is when to compress. The how and what remain engineered. This is the right balance: the model has local information about task state that no harness rule can replicate, but the compression mechanism itself is deterministic and auditable.

The Three Layers of Context Management in Deep Agents

Autonomous compression is the newest layer, but it sits on top of two existing mechanisms that Deep Agents already uses.

Tool result offloading. When a tool response exceeds 20,000 tokens, Deep Agents automatically saves the full response to the filesystem and replaces it in context with a file path reference and a preview of the first 10 lines. This fires immediately and unconditionally. No model decision needed.

Tool input offloading. When context crosses 85% of the model's window, old file write and edit arguments are evicted from the conversation history. Since this content is already persisted to the filesystem, the agent can re-read it if needed. This is a mechanical threshold-based operation.

Summarization. When offloading is no longer sufficient, the summarization middleware compresses the full conversation history into a structured summary. Previously, this fired only at the 85% threshold. Now, the model can trigger it at any time through the autonomous compression tool.

These three mechanisms compose. Offloading handles the large atomic payloads. Tool input eviction handles redundant persisted content. Summarization handles accumulated conversation history. Autonomous compression lets the model decide when summarization happens instead of waiting for a threshold.

What JetBrains Research Found

Independent research supports this approach. JetBrains Research ran experiments on SWE-bench Verified in December 2025 with several context management strategies.

Their observation masking approach, which keeps only the last N tool results and replaces older ones with placeholders, achieved 50%+ cost savings. For Qwen3-Coder 480B, it achieved a 2.6% higher solve rate at 52% lower cost compared to full-context approaches.

But they also found that LLM summarization can paradoxically lengthen trajectories by 13-15%. Summaries obscure natural stopping signals, causing agents to keep attempting past their optimal stopping point. Summarization costs exceeded 7% of total per-instance expenses in their study.

This is important nuance. Compression is not free. Summarization costs tokens. Poorly timed summarization can extend task duration. The JetBrains finding reinforces why model-triggered compaction matters: if you compact at the wrong time, you pay for the summarization and you pay again for the extended trajectory. The model is in the best position to choose the right time.

The JetBrains recommendation matches what Deep Agents implements: use mechanical clearing as the primary mechanism, reserve summarization for when you need to preserve reasoning across long dialogues, and let the model decide when that moment has arrived.

Context Rot Is the Real Enemy

Context rot is the measurable performance degradation that LLMs experience as input length grows. Chroma tested 18 frontier models in 2025, including Claude Sonnet 4, GPT-4.1, and Gemini 2.5. Every single model degraded. Accuracy on multi-document retrieval tasks dropped 30% or more when relevant content sat in the middle of the window.

GPT-4's accuracy drops from 98.1% to 64.1% based solely on where information is positioned in the context. This is not a token limit problem. The model has room. It just cannot attend to the right information anymore.

Forrester research shows that 65% of enterprise AI failures trace back to context drift or memory loss during multi-step reasoning, not raw token exhaustion. The model keeps running. It keeps generating output. But it is subtly wrong, and getting wronger.

The compounding effect is brutal. At 95% per-step reliability over a 20-step workflow, combined success drops to 36%. A 2% misalignment introduced early, because a critical instruction was lost in growing history, compounds into a 40% failure rate by the end.

Fixed-threshold compaction addresses token exhaustion. It does not address context rot. Context rot starts degrading performance long before the threshold fires. Model-triggered compaction can fire earlier, at natural boundaries, before rot sets in.

Practical Setup

To enable autonomous context compression in the Deep Agents SDK:

from deepagents import create_deep_agent
from deepagents.backends import StateBackend
from deepagents.middleware.summarization import create_summarization_tool_middleware

backend = StateBackend
model = "openai:gpt-5.4"

agent = create_deep_agent(
    model=model,
    middleware=[
        create_summarization_tool_middleware(model, backend),
    ],
)

In the CLI, use /compact to trigger compression manually. The model can also trigger it autonomously during execution.

The feature is opt-in in the SDK and enabled by default in the CLI. LangChain explicitly chose conservative defaults. The model triggers compression only when it identifies a clear compaction opportunity, not proactively.

You can read the full system prompt guidance that tells the model when compaction is appropriate in the Deep Agents GitHub repository at libs/deepagents/deepagents/middleware/summarization.py. The prompt instructs the model to consider compacting at task boundaries, after extracting results, before consuming large new context, before complex multi-step processes, and when context becomes stale.

What This Means for Agent Builders

Autonomous context compression is a small feature with big implications.

It is the first mainstream agent framework to explicitly reject fixed-threshold compaction in favor of model-triggered compaction. This is a design philosophy shift: the harness should get out of the way and let the model manage its own working memory.

It pairs naturally with other context engineering patterns. Phase-specific compilation (like contextweaver) decides what goes into context at each step. Progressive disclosure (like Anthropic's agent skills) loads information on demand. Autonomous compression decides when to remove context that is no longer needed. Together, they cover the full lifecycle: what enters, what stays, and what leaves.

It is conservative by default, which is the right call for a first release. The model does not compact aggressively. It does not compact at all in most benchmark runs. When it does compact, it chooses clearly beneficial moments. This builds trust: developers can enable the feature without worrying about premature context destruction.

The recovery story matters. Deep Agents preserves all conversation history in the filesystem. Compaction is lossy in working memory but lossless in persistent storage. The model can re-read compressed-away context if needed. This is a safety net that makes autonomous compression much less risky than it sounds.

When Not to Use It

Autonomous compression is not appropriate for every agent.

Short-session agents. If your agent completes tasks in under 10 turns, context management is not your problem. Adding a compaction tool is unnecessary complexity.

Agents with strict audit requirements. Compaction modifies the conversation history in working memory. Even though the full history is preserved on disk, some compliance frameworks require immutable in-context logs. Check your requirements.

Agents where every detail matters. If your use case requires the model to recall every specific number, date, and identifier from earlier in the conversation without re-reading files, summarization of any kind is a risk. The summary preserves intent and outcomes, not granular details.

Multi-agent systems with shared context. If multiple agents share the same context window, autonomous compaction by one agent can destroy context that another agent needs. Coordinate compaction at the orchestrator level instead.

The Bigger Picture

The shift from fixed-threshold to model-triggered compaction is part of a broader movement in agent design. The old approach treats context management as infrastructure: a harness problem solved with thresholds, heuristics, and hand-tuned rules. The new approach treats context management as a reasoning problem: something the model can handle itself with the right tools.

This mirrors what happened with tool use. Early agent frameworks hard-coded which tools to call and when. Modern frameworks give the model a set of tools and let it decide. The results are better because the model has local information about the task that no harness rule can replicate.

The same logic applies to context. The model knows when it is between tasks. The model knows when it has extracted the key finding from a research step. The model knows when it is about to consume a massive amount of new context. A harness rule that counts tokens does not know any of this.

LangChain's autonomous context compression is the first step. Expect every major agent framework to follow. The bitter lesson keeps winning.


Suggested Title: Let the Model Decide When to Forget

Word Count: 2,054

Citations:

Fact-Check Notes:

  1. The GPT-4 accuracy drop from 98.1% to 64.1% comes from the Tian Pan article citing Forrester research. I was unable to verify the specific study that produced these numbers. The general finding that accuracy degrades based on position in context is well-supported by multiple studies.
  2. The "65% of enterprise AI failures" figure comes from Forrester research cited in the Tian Pan article. I was unable to locate the original Forrester report. Treat this as an industry claim rather than a verified statistic.
  3. The JetBrains Research findings (13-15% trajectory lengthening, 7% summarization costs, 50%+ cost savings with observation masking) come from SWE-bench Verified experiments in December 2025, cited in the Tian Pan article. I was unable to find the original JetBrains paper.
  4. LangChain's autonomous compression feature was released March 11, 2026. The SDK feature is opt-in; the CLI feature is enabled by default. This is confirmed by the official blog post and documentation.
  5. The 10% retention during summarization and 20,000-token tool result offloading threshold are from the official LangChain blog posts and documentation.
  6. The "bitter lesson" framing is LangChain's own analogy in their blog post, not my interpretation.