产品介绍

Context compression

This page covers four things: long-message offloading, historical tool-argument trimming, automatic summarization, and context-overflow recovery. For other context sources see context and prompts; for how runtime state and business files are stored see state and storage and sessions and outputs.

Design and scope

During long conversations, earlier user questions, tool arguments, and tool results keep enlarging the model input. The runtime keeps recent work in view, summarizes older conversation content, and writes long bodies to session files for on-demand retrieval. When a model needs the details, it pages through the file with read_file using offset and limit.

The default Deep Agents root, standard declared subagents, and default general-purpose subagent all include filesystem and summarization middleware. Each Agent derives summarization thresholds from its own model's context information and uses that model to produce summaries. Compiled subagents and compiled entries selected by dataagent.entry own their graphs; their plugins determine internal context policies. See core graph assembly and execution.

Mechanism Target Trigger point What the model continues to see
Tool-result offloading Oversized tool-return text When the tool returns File path, beginning/end preview, and paginated-read instructions
Long-user-message offloading Text in the latest oversized user message Before a model call File path and beginning/end preview, retaining non-text content blocks
Historical tool-argument trimming Older write_file and edit_file arguments Before checking summarization Beginning of long strings and a truncation marker
Automatic summarization An older segment of the effective conversation Threshold reached or insufficient input budget Summary message, history-file path, and retained recent messages
Overflow recovery Consecutive tool results at the end of retained messages Input still exceeds the budget or the model explicitly reports overflow Shortened results and paths for recovering full bodies

Order within a model invocation

Filesystem middleware first handles long user messages requiring offloading. Summarization middleware then prepares the request in this order:

  1. Construct the effective message list using the previously saved summarization event.
  2. Check historical tool-argument trimming conditions and create shortened copies of long arguments before the retained window.
  3. Count effective input. System prompts participate; tool declarations also count when supported by the counter.
  4. Check summarization triggers and the input safety budget. When needed, separate old history from recent messages, save the old history, and generate a summary.
  5. Compose the request from summary and recent messages. If still oversized, try shortening trailing tool results and check whether the input fits.
  6. Call the model. An explicit model context-overflow error also enters recovery. Raise ContextOverflowError if recovery still cannot make the input fit.

Synchronous and asynchronous entry points use the same policy. Asynchronous automatic summarization saves history and generates its summary concurrently. See summarization middleware.

Automatic summarization triggers

compute_summarization_defaults selects defaults from the model object's profile.max_input_tokens.

Available model information Summarization trigger Recent messages retained after summarization Historical tool-argument trimming
Integer max_input_tokens in profile Approximately 85% of the model input limit Recent messages occupying approximately 10% of that limit Same 85% trigger and 10% retention window
No usable input limit A fixed fallback of approximately 170,000 tokens The latest six messages Once 20 messages accumulate, process arguments older than the latest 20

Runtime estimates can differ from provider token accounting. LangChain also checks usage on the latest AI message: matching the summarization model's provider and reported total_tokens reaching the threshold can trigger summarization. LangChain's summarization middleware selects valid cut points, and tool-call/reply boundaries affect the actual number retained. The latest six messages count message objects.

Product YAML supplies model names and connection addresses. Thresholds depend on the profile actually carried by the model object. With custom OpenAI-compatible services, check whether that object includes input-limit information. A provider with a smaller context window and missing profile can overflow before the fixed threshold, then enter recovery.

Summarization adds model calls, and those calls can retry and increase latency. The default factory sets trim_tokens_to_summarize to None; the history volume processed before summarization also affects latency. See execution for call-limit and host-deadline scope.

Input safety budget

In addition to normal summarization triggers, models with a known input limit have a budget check:

Input safety budget = floor(max_input_tokens × 0.95) − configured output-token reservation

The output reservation is the largest valid max_tokens, max_completion_tokens, or max_output_tokens value from request settings or the model object. Estimated input exceeding the budget causes earlier summarization or tool-result clipping. Missing profiles skip this preliminary budget check.

For example, suppose the actual model profile reports max_input_tokens=128000 and max_tokens=4096 is configured.

Quantity Result
Normal summarization trigger Approximately 108,800 tokens
Recent-message retention target Approximately 12,800 tokens
Input safety budget 121,600 − 4,096 = 117,504 tokens

These numbers illustrate that assumption. System prompts, tool declarations, and retained messages still consume space, so the budget is checked again after summarization.

Messages and checkpoints after summarization

Automatic summarization records where the model should continue reading in private state. Principal fields are:

State field Contents
_summarization_event.cutoff_index End position covered by the summary in the original message list
_summarization_event.summary_message Generated summary message marked lc_source=summarization
_summarization_event.file_path Saved history-body path, or None on saving failure
_summarization_session_id Internal identifier for this summary's history file

Default automatic summarization preserves the original messages list, using these private fields to construct subsequent model requests as summary plus messages after the cut point. Hosts with persistent checkpointers save these fields as graph state. Internal summary-event identity is managed separately from user threadId.

For example, assume original state contains m1 through m20, with this invocation selecting a cut point after the first 14 messages.

State messages       m1 … m14 | m15 … m20
Saved history        m1 … m14 → conversation_history/<internal-summary-id>.md
Current model input  Summary and history path | m15 … m20
Subsequent messages  Append to state; the next request reuses the summary event

History for one summarization instance accumulates in the same Markdown file, divided by Summarized at timestamps. History writing filters out earlier summary messages. Another summarization includes the previous summary and new history in its summary input, then maps its cut point back into the original message-list positions.

Long tool results, long user messages, and overflow recovery modify their corresponding messages separately, as described below. Preserve checkpoints, bindings, and referenced files together for recovery. State and storage

Long bodies and historical arguments

Tool results and user messages

Filesystem middleware estimates length from text characters, using approximately four characters per token.

Content Default offloading threshold Location
Eligible tool-return text Above approximately 20,000 tokens, or 80,000 characters artifacts/large_tool_results/<tool_call_id>
Latest user-message text Above approximately 50,000 tokens, or 200,000 characters artifacts/conversation_history/<UUID>.md

An ordinary offloaded preview keeps the first five and last five lines, capped at roughly 1,000 characters each. It also carries the full path and a hint to page through the file with read_file. Non-text content blocks remain in the message.

ls, glob, grep, read_file, edit_file, write_file, and delete are excluded from ordinary tool-result offloading. File-reading tools use their own pagination and display limits. See the following section for emergency handling of trailing tool results at the input budget.

After successfully saving long user content, state marks the original message with an lc_evicted_to path; a preview is constructed when sending it to the model. Ordinary large tool results replace the returned tool message with path and preview after successful writing. A reported write failure preserves the original message. See filesystem middleware and tool-result offloading.

Historical tool arguments

write_file and edit_file arguments can contain entire file bodies. After reaching the trimming condition in the summarization-trigger table, middleware inspects only calls before the retained window.

By default it checks string argument values. Values longer than 2,000 characters retain their first 20 characters plus ...(argument truncated) in the copy sent to the model. Other tools and calls in the recent window retain their values. Only copies of historical arguments in messages are affected; completed file writes do not execute again.

Recovering from context overflow

When estimated input exceeds the budget before a model call, or the model explicitly reports overflow, summarization middleware attempts further reduction. A provider error must be ContextOverflowError, or have status 400, 413, or 422 with a recognized context-overflow marker, to enter this path.

If retained messages end with consecutive ToolMessage objects, recovery handles them according to their original tool calls:

  • read_file output keeps the first 4,000 characters, appending the original file path and paginated-read instructions.
  • Other trailing tool results attempt saving under large_tool_results/, replacing the body with a preview.

Request size is counted again afterward. Recovery raises ContextOverflowError if the input remains above a known budget, fails to shrink, or the recovered model call reports overflow again. The path has a bounded number of attempts. Oversized system prompts, tool declarations, or latest user content may not be fixable by clipping trailing tool results.

This mechanism is independent of HTTP client max_retries. Recovery shortens already completed tool results before retrying the model request. See summarization middleware and trailing-tool clipping for exact conditions.

File locations and diagnosis

Default directories follow this layout. <user> defaults to default; <thread> is the session ID.

<home>/outputs/<user>/<thread>/artifacts/
  conversation_history/
    <internal-summary-id>.md
    <long-user-message-UUID>.md
    media/<content-hash>.<extension>
  large_tool_results/<tool-call-ID>

dataagent.output_root or SDK output_dir changes output placement. Session bindings determine the actual directory, and artifacts/ follows that session's output directory. Inline data-URL media encountered before summarization is saved by content hash under conversation_history/media/ when possible, with references carried into history and summaries. Output-directory rules

TUI /outputs and REST output listing skip artifacts/conversation_history and artifacts/large_tool_results. Diagnose compression in the backend machine's actual session output directory or inspect summarization events in graph state. Saving these files supports retrieving original details by path, and cleanup must account for file references in historical messages. Path resolution and session bindings

For default Home and output root, run the following on the backend machine, replacing the session ID:

thread_id=replace-with-thread-id
session_outputs="${DATAAGENT_HOME:-$HOME/.dataagent}/outputs/default/$thread_id"
find "$session_outputs/artifacts/conversation_history" -type f
find "$session_outputs/artifacts/large_tool_results" -type f
Symptom Inspection
Model answer references a summary or history file Inspect event file_path, history body, and retained messages
/outputs omits history bodies Inspect artifacts/ in the actual output directory; listing filters these internal files
Summarization becomes much slower Inspect model traces and backend logs, history length, and provider latency
Context still overflows Check the actual model profile, output-token reservation, system prompt, tool declarations, and latest input size
Files were not saved Check output-directory permissions and backend history-offloading warnings

History-saving failure logs a warning, but summarization can still succeed and execution continue without a recoverable body path in the summary message. Inline-media saving failure leaves a failure marker and warning. Automatic summarization model-call exceptions propagate to the caller. Detailed successful-write records use DEBUG; at the default INFO level, combine files, graph state, and traces. See observability and execution traces for log locations and trace inspection.

Configuration and plugin boundaries

Product config.yaml currently influences execution indirectly through models, execution limits, and extension selection. Core graph construction sets summarization thresholds, retention windows, and offloading thresholds. These values describe the current implementation. Changes to underlying middleware must also check configuration models and graph assembly. Product configuration fields

Core also provides SummarizationToolMiddleware and create_summarization_tool_middleware to explicitly register a compact_conversation tool. The default product graph installs automatic summarization middleware. Using that tool requires explicit tool-middleware assembly in a custom graph; its eligibility and error responses follow the implementation. Tool-based summarization

The standard nl2sql-react subagent uses host standard-subagent context handling. Its Hook additionally bounds initial schema and sample-data prefetch with dbexplore.max_context_chars. Its internal db_explore Agent has a separate business-character budget. These budgets limit collected business material; see the plugin README and context-prefetch Hook.

Verification entry points

Existing integration tests use controlled models and temporary session directories. They cover continuing after a summary is saved, recovering offloaded tool results with read_file, and keeping summary files separate per session when reusing one SDK Agent. Run them in the prepared project environment:

uv run --no-sync pytest -q tests/test_native_context.py tests/test_shared_agent.py::test_shared_summary_history_uses_current_artifacts

See context integration tests and shared-Agent session tests. Ownership and recovery also depend on session bindings. Traces store execution observations; see execution traces for their purpose.