* fix(summarization): own the run model for compaction; bound failure With summarization.model_name: null the summary model resolved to config.models[0] while the executing model is selected per run; when they differ and models[0]'s provider is broken (expired key, quota, outage) compaction silently failed every triggered turn and context grew unbounded until the main provider 400s the run (#3103's shape), even though the run's own model was healthy. Model ownership is now sourced from the builders, not re-derived at runtime: - The lead, subagent, and manual /compact builders each pass the resolved run model into create_summarization_middleware(run_model_name=...). The middleware no longer reads runtime.context / get_config(), which do not carry a custom agent's or a subagent's resolved model, so a custom-agent lead run and a distinct-model subagent now summarize with their own model, not models[0] / the parent's. Runtime re-resolution and the per-name model cache are removed. - model_name: null summarizes with the run's own model; an explicitly configured summary model generates and falls back to the run model on failure. The fallback is built lazily after the primary fails and its construction is guarded, so a broken fallback cannot skip a healthy primary or escape the automatic failure boundary. Failure is bounded and side-effect-safe: - An empty or whitespace-only response is treated as a generation failure, not a valid summary, so compaction never removes all history for an empty replacement. - compact_state/acompact_state take raise_on_failure independent of force: the manual /compact path always surfaces a generation failure (even force=false) and routes it to the existing ContextCompactionFailed path (HTTP 500 -> frontend error toast) instead of an unconsumed response reason. The automatic path leaves compaction state unchanged. - before_summarization hooks fire only after a replacement summary exists. SummarizationConfig.model_name, config.example.yaml, and docs/summarization.md document the final lead/subagent/manual ownership rules. Part of RFC #4346 (section A). Evaluating fraction/triggers against the run model's profile (profile ownership) is a separate follow-up. * fix(summarization): manual /compact model ownership + fail-open construct/parse Manual /compact carried only agent_name, so it derived the run model from the custom-agent model or config.models[0] and missed the request-selected model the run path uses (request -> custom-agent -> default). Carry model_name through ThreadCompactRequest and the frontend compact call, resolve with the same precedence, and move the custom-agent config read off the event loop (asyncio .to_thread) with user_id so the strict blocking-IO gate is not bypassed by the broad except. Make one summary attempt own its full lifecycle so the fail-open boundary covers construction and response parsing, not just invocation: build each candidate model lazily and guarded (a raising constructor falls through to the healthy run model instead of breaking agent construction), build the model_name:null primary from the run model rather than config.models[0], and run response text extraction inside the invocation try so a failing .text accessor falls back instead of escaping compaction. Adds factory-level constructor-failure, response-extraction-failure (sync/async), and route-path model-ownership tests.
14 KiB
Conversation Summarization
DeerFlow includes automatic conversation summarization to handle long conversations that approach model token limits. When enabled, the system automatically condenses older messages while preserving recent context.
New checkpoints no longer use raw task-result or skill-read transcript content to derive durable context. The capture path consumes bounded structured metadata stamped on the corresponding ToolMessage.additional_kwargs; transcript text remains display/model content, not the state-capture protocol.
Overview
The summarization feature uses LangChain's SummarizationMiddleware to monitor conversation history and trigger summarization based on configurable thresholds. When activated, it:
- Monitors message token counts in real-time
- Triggers summarization when thresholds are met
- Keeps recent messages intact while summarizing older exchanges
- Maintains AI/Tool message pairs together for context continuity
- Stores the summary in
ThreadState.summary_textand projects it ephemerally through durable context data
Configuration
Summarization is configured in config.yaml under the summarization key:
summarization:
enabled: true
model_name: null # null = summarize with the run's own model (see below); or name a lightweight model
# Trigger conditions (OR logic - any condition triggers summarization)
trigger:
- type: tokens
value: 4000
# Additional triggers (optional)
# - type: messages
# value: 50
# - type: fraction
# value: 0.8 # 80% of model's max input tokens
# Context retention policy
keep:
type: messages
value: 20
# Token trimming for summarization call
trim_tokens_to_summarize: 4000
# Custom summary prompt (optional)
summary_prompt: null
# Tool names treated as skill file reads for the durable skill_context channel
skill_file_read_tool_names:
- read_file
- read
- view
- cat
Configuration Options
enabled
- Type: Boolean
- Default:
false - Description: Enable or disable automatic summarization
model_name
- Type: String or null
- Default:
null - Description: Model to use for generating summaries.
null(model ownership): summarize with the model the run actually executes with — the lead run's resolved model, a subagent's own model, or a thread's custom-agent model — notconfig.models[0]. This keeps compaction working on a run whose model is healthy even whenmodels[0]'s provider is broken (expired key, quota, outage).- Set to a model name: that model generates summaries. If its provider fails, compaction falls back to the run's own model so a broken summary provider cannot disable compaction while a working model is available. Recommended to use a lightweight, cost-effective model like
gpt-4o-minior equivalent. - Ownership applies to all three paths — automatic lead compaction, subagent compaction, and manual
/compact. Manual/compactresolves the run model with the same precedence as a normal run: the model selected for the request (POST /api/threads/{id}/compactbodymodel_name, sent by the frontend from the composer's current model) → the thread's custom-agent model → the default. A whitespace-only summary response is treated as a generation failure (it is never committed as a valid empty summary).
trigger
- Type: Single
ContextSizeor list ofContextSizeobjects - Required: At least one trigger must be specified when enabled
- Description: Thresholds that trigger summarization. Uses OR logic - summarization runs when ANY threshold is met.
ContextSize Types:
-
Token-based trigger: Activates when token count reaches the specified value
trigger: type: tokens value: 4000 -
Message-based trigger: Activates when message count reaches the specified value
trigger: type: messages value: 50 -
Fraction-based trigger: Activates when token usage reaches a percentage of the model's maximum input tokens
trigger: type: fraction value: 0.8 # 80% of max input tokens
Multiple Triggers:
trigger:
- type: tokens
value: 4000
- type: messages
value: 50
keep
- Type:
ContextSizeobject - Default:
{type: messages, value: 20} - Description: Specifies how much recent conversation history to preserve after summarization.
Examples:
# Keep most recent 20 messages
keep:
type: messages
value: 20
# Keep most recent 3000 tokens
keep:
type: tokens
value: 3000
# Keep most recent 30% of model's max input tokens
keep:
type: fraction
value: 0.3
trim_tokens_to_summarize
- Type: Integer or null
- Default:
4000 - Description: Maximum tokens to include when preparing messages for the summarization call itself. Set to
nullto skip trimming (not recommended for very long conversations).
summary_prompt
- Type: String or null
- Default:
null(uses LangChain's default prompt) - Description: Custom prompt template for generating summaries. The prompt should guide the model to extract the most important context.
skill_file_read_tool_names
- Type: List of strings
- Default:
["read_file", "read", "view", "cat"] - Description: Tool names treated as skill file reads when
DurableContextMiddlewarecaptures loaded skills into the checkpointedskill_contextchannel. A tool call is captured only when its name appears in this list and its target path is underskills.container_path. Set this list to[]to disable durable skill-reference capture.
Legacy preserve_recent_skill_* settings are no longer used. Loaded skill retention is handled by the durable skill_context reference channel instead of by preserving raw skill-read messages in the summarization window.
Default Prompt Behavior: The default LangChain prompt instructs the model to:
- Extract highest quality/most relevant context
- Focus on information critical to the overall goal
- Avoid repeating completed actions
- Return only the extracted context
How It Works
Summarization Flow
- Monitoring: Before each model call, the middleware counts tokens in the message history plus the existing
summary_text, because both are projected into the next model request - Trigger Check: If any configured threshold is met, summarization is triggered
- Message Partitioning: Messages are split into:
- Messages to summarize (older messages beyond the
keepthreshold) - Messages to preserve (recent messages within the
keepthreshold)
- Messages to summarize (older messages beyond the
- Summary Generation: The model generates a concise summary of the older messages
- Context Replacement: The message history is updated:
- All old messages are removed
- Recent messages are preserved
- The generated prose summary is stored in
summary_text
- AI/Tool Pair Protection: The system ensures AI messages and their corresponding tool messages stay together
- Skill context channel: Skill files read during the conversation (tool calls whose name is in
skill_file_read_tool_namesand whose path is underskills.container_path, narrowed to.../SKILL.md) are stamped withskill_context_entrymetadata at the read-tool boundary, then captured byDurableContextMiddlewareinto the checkpointedskill_contextchannel as references:name,path, a one-linedescriptionparsed in-memory from the file's frontmatter, andloaded_at, deduped by path. On every model call they are rendered into a hidden durable-context data message as a compact "active skills" reminder that points at eachSKILL.mdfor on-demand re-read, so which skills are active survives summarization without persisting or re-injecting the verbatim body. The channel keeps the most recently read skills (cap_SKILL_CONTEXT_MAX_ENTRIES; re-reading an existing skill refreshes its recency); sessions typically load only 1-3.
Token Counting
- Uses approximate token counting based on character count
- For Anthropic models: ~3.3 characters per token
- For other models: Uses LangChain's default estimation
- Can be customized with a custom
token_counterfunction
Message Preservation
The middleware intelligently preserves message context:
- Recent Messages: Always kept intact based on
keepconfiguration - AI/Tool Pairs: Never split - if a cutoff point falls within tool messages, the system adjusts to keep the entire AI + Tool message sequence together
- Summary Format: Summary prose is stored in
summary_textand rendered into an ephemeral hidden durable-context data message. Static handling rules live in a separate system message; summary text and other user/tool/model-derived values stay in the lower-authority data message.<durable_context_data> ## Conversation summary so far [Generated summary text] </durable_context_data>
Best Practices
Choosing Trigger Thresholds
-
Token-based triggers: Recommended for most use cases
- Set to 60-80% of your model's context window
- Example: For 8K context, use 4000-6000 tokens
-
Message-based triggers: Useful for controlling conversation length
- Good for applications with many short messages
- Example: 50-100 messages depending on average message length
-
Fraction-based triggers: Ideal when using multiple models
- Automatically adapts to each model's capacity
- Example: 0.8 (80% of model's max input tokens)
Choosing Retention Policy (keep)
-
Message-based retention: Best for most scenarios
- Preserves natural conversation flow
- Recommended: 15-25 messages
-
Token-based retention: Use when precise control is needed
- Good for managing exact token budgets
- Recommended: 2000-4000 tokens
-
Fraction-based retention: For multi-model setups
- Automatically scales with model capacity
- Recommended: 0.2-0.4 (20-40% of max input)
Model Selection
-
Recommended: Use a lightweight, cost-effective model for summaries
- Examples:
gpt-4o-mini,claude-haiku, or equivalent - Summaries don't require the most powerful models
- Significant cost savings on high-volume applications
- Examples:
-
Default: If
model_nameisnull, summarizes with the run's own model (notmodels[0])- Keeps compaction working when
models[0]'s provider is broken but the run's model is healthy - Good for simple setups; no separate summary provider to keep credentialed
- Keeps compaction working when
Optimization Tips
-
Balance triggers: Combine token and message triggers for robust handling
trigger: - type: tokens value: 4000 - type: messages value: 50 -
Conservative retention: Keep more messages initially, adjust based on performance
keep: type: messages value: 25 # Start higher, reduce if needed -
Trim strategically: Limit tokens sent to summarization model
trim_tokens_to_summarize: 4000 # Prevents expensive summarization calls -
Monitor and iterate: Track summary quality and adjust configuration
Troubleshooting
Summary Quality Issues
Problem: Summaries losing important context
Solutions:
- Increase
keepvalue to preserve more messages - Decrease trigger thresholds to summarize earlier
- Customize
summary_promptto emphasize key information - Use a more capable model for summarization
Performance Issues
Problem: Summarization calls taking too long
Solutions:
- Use a faster model for summaries (e.g.,
gpt-4o-mini) - Reduce
trim_tokens_to_summarizeto send less context - Increase trigger thresholds to summarize less frequently
Token Limit Errors
Problem: Still hitting token limits despite summarization
Solutions:
- Lower trigger thresholds to summarize earlier
- Reduce
keepvalue to preserve fewer messages - Check if individual messages are very large
- Consider using fraction-based triggers
Implementation Details
Code Structure
- Configuration:
packages/harness/deerflow/config/summarization_config.py - Integration:
packages/harness/deerflow/agents/lead_agent/agent.py - Middleware: Uses
langchain.agents.middleware.SummarizationMiddleware
Middleware Order
Durable context capture runs before summarization so task delegations and loaded skill references are recorded before their raw tool messages can be compacted. It records in-progress dispatches as well as terminal result summaries. Summarization then reduces message history before downstream middlewares such as title generation, memory queuing, and clarification:
- Runtime middlewares, including ThreadData and Sandbox initialization
- DynamicContextMiddleware
- SkillActivationMiddleware
- DurableContextMiddleware
- SummarizationMiddleware ← Runs here
- Downstream lead middlewares such as Title, Memory, and Clarification
State Management
- Summarization configuration is loaded from
config.yaml - Generated summaries are stored in
ThreadState.summary_text, not as regularmessages - The message reducer removes compacted raw messages while the checkpointer persists
summary_text - DurableContextMiddleware projects
summary_textback into later model calls as hidden durable context data
Example Configurations
Minimal Configuration
summarization:
enabled: true
trigger:
type: tokens
value: 4000
keep:
type: messages
value: 20
Production Configuration
summarization:
enabled: true
model_name: gpt-4o-mini # Lightweight model for cost efficiency
trigger:
- type: tokens
value: 6000
- type: messages
value: 75
keep:
type: messages
value: 25
trim_tokens_to_summarize: 5000
Multi-Model Configuration
summarization:
enabled: true
model_name: gpt-4o-mini
trigger:
type: fraction
value: 0.7 # 70% of model's max input
keep:
type: fraction
value: 0.3 # Keep 30% of max input
trim_tokens_to_summarize: 4000
Conservative Configuration (High Quality)
summarization:
enabled: true
model_name: gpt-4 # Use full model for high-quality summaries
trigger:
type: tokens
value: 8000
keep:
type: messages
value: 40 # Keep more context
trim_tokens_to_summarize: null # No trimming