Skip to content

feat: summarize older messages near the model's input limit - #118

Merged
gopaljigaur merged 5 commits into
mainfrom
feat/compaction
Oct 15, 2026
Merged

gopaljigaur merged 5 commits into
mainfrom
feat/compaction

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

Keeps a run's requests within the model's context window.

What changed

  • AgentConfig.compaction (a new Compaction model, off by default). Before each completion the run counts the request with litellm.token_counter against litellm.get_model_info(...)["max_input_tokens"]. Once it reaches threshold (0.8) of that limit, a separate completion summarizes the older messages, and the summary replaces them as one user message ("Here is a summary of the conversation to date:"). model picks another summarizing model and prompt the instruction.
  • What is kept. The system prompt, and the most recent messages up to keep (0.2) of the limit. The last message is always kept. A cut that lands among tool results moves back to the assistant message that made the calls, as LangChain's SummarizationMiddleware does, so a call and its results stay together.
  • Counting once. The system prompt and tools are counted when they change (again when a search loads deferred tools), and each transcript message once, when first seen (cyclops/core/compaction.py, _ContextWindow).
  • Router. The deployment with the smallest max_input_tokens sets the limit, through Router.get_router_model_info, so deployment model_info overrides count.
  • Unknown limits. With compaction set, a model (or summarizing model) LiteLLM has no max_input_tokens for raises ValueError at the run's first step and from compact(), as LangChain does, with the litellm.register_model hint.
  • The summarizing request. It carries the older messages as a plain text transcript. Its own max_tokens is keep of the window, capped at the summarizing model's output limit, so the summary fits where the summarized messages were. It is sent without the agent's thinking or reasoning_effort, whose budget that limit could fall under. The transcript gets the rest of the summarizing model's window: the oldest messages are dropped first, with a note of how many, and a window with no room for any of it raises RuntimeError. It goes through _acompletion (retries, on_llm_start/on_llm_end/on_llm_error). Its usage counts in the run's usage, max_total_tokens and max_cost, and it is not a step. An empty, cut or filtered summary raises RuntimeError and leaves the transcript as it was.
  • No repeated compaction. An earlier summary is never summarized on its own. A compaction that leaves the request past the threshold logs one warning, and the run does not compact again.
  • Autosave. After a compaction the run calls the session saver's rewritten(), so the next save stores the whole session.
  • Compacted event (summary, replaced_messages, tokens_before, tokens_after) and an on_compaction(summary, tokens_before, tokens_after) hook.
  • Manual compaction: Agent.compact(session) / acompact(session) use config.compaction or the defaults and count the tools a run starts with. They add the summary's usage to the session and return False when only an earlier summary would be summarized. Like session.truncate(), they don't save: the next run's first save stores the whole session.
  • AgentConfig.max_tool_output_chars (off by default): a longer tool result keeps its start and end, half the limit each, around [N characters omitted]. Images are kept. The model, ToolCallFinished.result and RunResult.tool_calls get the cut text; hooks and middleware see the whole result.
  • Naive fallback. It now restores the transcript as a whole, since a compaction before the failed first completion also replaced earlier messages. The undone compaction still emitted its event and spent its summary, and the naive attempt compacts again; that costs one extra summary, once per agent.

Decisions

  • Opt-in. LangChain's SummarizationMiddleware, Pydantic AI's history processors and the OpenAI Agents SDK's OpenAIResponsesCompactionSession are all opt-in: compaction costs an extra completion and replaces what the model saw.
  • A plain text transcript in one user message, as LangChain does, so the summarizing request carries no tool calls, images or reasoning blocks that a provider could reject without tools.
  • Own trimming instead of litellm.trim_messages. That function recounts the growing list for each message it adds, shortens from the middle, and returns its input unchanged on any error. Here the per message counts are already cached.
  • Characters for the tool output limit, like common command-output limits: cheap and exact, with no encode and decode round trip.
  • Server-side context management. LiteLLM 1.105.1 passes Anthropic's context_management through, so clear_tool_uses_20250919 works from completion_kwargs. Its compact_20260112 edit returns a compaction block in provider_specific_fields that has to be sent back, which the transcript does not keep, so this compaction is provider independent instead.
  • Prompt caching. Compaction changes the start of the conversation; the next request reads only the system prompt and tools from the cache. Documented.

Tests

tests/test_compaction.py uses LiteLLM's real token_counter and mock_response, with a model registered with a 400 token limit. It covers:

  • the threshold, and nothing happening below it or with compaction off;
  • the last message always kept, tool call groups kept whole, and a second step after a compaction;
  • no re-summarizing of a lone summary, and the warning once;
  • the summary input trimmed to a smaller summarizing model, a model whose output limit equals its input limit, and a summarizing window with no room;
  • empty, cut and failing summaries;
  • unknown limits raising, and the router minimum;
  • usage and budget, and the summary model override;
  • the summary persisted in a saved session, and autosave storing the compacted session;
  • the naive fallback restore;
  • deferred tools counted once loaded, and manual compaction (including counting only the tools a run starts with);
  • the event and the hook;
  • the tool output limit, with hooks and middleware seeing the whole output and images kept.

uv run pytest, uv run pre-commit run --all-files and uv run mypy cyclops pass.

Docs: a Context window section in the agents guide, plus the hooks, streaming, sessions and API reference pages, in docs/ and the website.

Closes #54

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed f37b258. pytest passes on 3.14 and 3.10 (469 passed), mypy and pre-commit are clean, CI is green, the confidentiality grep and the dash check find nothing in the title, body, commit or added lines.

Findings, each in its thread:

  1. #115 overlap: with both merged, the append-only saver stores the uncompacted log and drops the summary and the messages after it (reproduced). Proposed interface: compaction makes the saver's next save a full save.
  2. The newest message, the user's request included, can be summarized away; LangChain always keeps the last message and moves the cut back to keep a tool group.
  3. A summary that leaves the request past the threshold is redone every step (3 compactions in 3 steps in a probe).
  4. The summary request can overflow the summarizing model (smaller Compaction.model, or a session already past the window).
  5. An empty or cut summary replaces the messages.
  6. Compaction on a model with unknown limits silently does nothing; LangChain raises.
  7. Not on top of main: conflicts with #110, and the fixed token count ignores tools loaded mid run.
  8. Naive fallback after a compaction reports and pays for a compaction it undoes.
  9. Test gaps.

Checked and fine: token counting (count_response_tokens=True per message plus one call for system prompt, tools and reply priming matches LiteLLM's accounting; images use the default count, no fetch), the router minimum through get_router_model_info, parallel tool calls in one group, the summary failing (it raises before touching the transcript), saved sessions keep the summary, prompt caching markers are reapplied per request, and #87's frame clearing covers the new frames. Efficiency: on a 500 message session the first count takes about 25 ms per run, each later step 0.1 ms against 5 ms for a full recount, and the cache is one int per message (about 4 KB), freed with the run.

Conventions: opt-in, keep, the summary as a user message with LangChain's exact prefix, and tool pairs kept together all match LangChain's SummarizationMiddleware; Pydantic AI's history_processors and the OpenAI Agents SDK's OpenAIResponsesCompactionSession are opt-in too. threshold is LangChain's trigger as a plain fraction, which reads fine. Characters for max_tool_output_chars are a reasonable unit: cheap, exact and model independent.

Comment thread cyclops/core/run.py Resolved
Comment thread cyclops/core/compaction.py Resolved
Comment thread cyclops/core/compaction.py Resolved
Comment thread cyclops/core/compaction.py Resolved
Comment thread cyclops/core/compaction.py Resolved
Comment thread cyclops/core/compaction.py Resolved
Comment thread cyclops/core/compaction.py Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread tests/test_compaction.py Resolved
@gopaljigaur
gopaljigaur force-pushed the feat/compaction branch 2 times, most recently from 90ded7b to 081b684 Compare October 15, 2026 05:00

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 081b684 (fixes in 2e4284a). pytest passes on 3.14 and 3.10 (518 passed), mypy and pre-commit are clean, and CI is green on 3.10 to 3.12. The confidentiality grep and the dash check find nothing in the title, body, commits or added lines.

Still not on top of main. git merge-base --is-ancestor origin/main origin/feat/compaction fails because main has since merged #109, #121 and #119. The merge is clean, and #120's suite passes on a local merge with main (542 passed). Main's CI now also tests 3.13 and 3.14, which this PR's CI hasn't run, so it needs a rebase.

New finding (thread): for models whose output limit equals their input limit, the summary input budget is not positive. The whole history is then replaced by a summary of nothing (reproduced).

Earlier threads:

  1. Autosave: fixed. _save now sets _saved when the save is scheduled, so rewritten() can't be undone by a pending write. My probe with #115 on main stores exactly the in-memory session in both sync and async mode.
  2. Newest message: fixed for the last message and for tool groups. I accept the decision not to protect an earlier user question. In a single-run tool loop (one question, then many tool steps) the question is summarized once the loop passes keep, and that is realistic. LangChain's _find_token_based_cutoff doesn't protect it either; it keeps only the newest messages within the budget plus the tool pair. The default prompt asks the summary to keep the user's goals and instructions.
  3. Repeated compaction: fixed. I accept stopping for the rest of the run. With the summary-only guard, resuming would compact every step whenever the summary, tools and system prompt sit near the threshold, which was the original waste. #120's overflow path calls compact directly and ignores the flag, so a stuck run still recovers once it overflows.
  4. Summary input: the author's reasons for not using trim_messages check out in LiteLLM 1.105.1. process_messages calls token_counter on the whole accumulated list for each message, so it is quadratic. shorten_message_to_fit_limit removes characters from the middle. trim_messages catches every exception and returns the original messages. The hand-rolled _trimmed reuses the cached counts and is short. The budget has the bug above.
  5. Empty or cut summary: fixed. It raises before the transcript changes.
  6. Unknown limits: fixed. It raises ValueError at run start and from acompact.
  7. Deferred tools: fixed. request() recounts when the tools change, and acompact counts only the tools a run starts with.
  8. Naive fallback: I accept leaving it. The extra summary happens at most once per agent, since the detected mode is cached, the transcript ends up right, and test_the_naive_fallback_restores_the_transcript_before_compaction pins it.
  9. Test gaps: covered.

Probes:

  • The newest message is kept.
  • The long-summary case compacts once and warns.
  • A router with an unserved Compaction.model raises ValueError at the start.
  • On a 500-message session the first count takes 31 ms per run and each later step 0.04 ms.

Comment thread cyclops/core/compaction.py Resolved

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed d51822c. pytest passes on 3.14 and 3.10 (531 passed), mypy and pre-commit are clean, and CI is green on 3.10 to 3.14. The confidentiality grep and the dash check find nothing.

Not on top of main again. git merge-base --is-ancestor origin/main origin/feat/compaction fails: main merged #96 (soak tests) after this rebase. The merge is clean.

Equal limits fix: verified. The summary now sets its own max_tokens = keep * window, capped at the output limit, and an empty trimmed input raises before any request.

  • On a 400/400 model the summary went out with max_tokens=80, the newest messages that fit and an omitted note.
  • On mistral/mistral-large-latest's real limits (262144 / 262144, 55 pairs of about 2000 words) it went out with max_tokens=52428 and the whole transcript, with nothing omitted.

New finding (thread): the new summary max_tokens can be at or below the agent's thinking budget. Every compaction then fails on Anthropic models. This is a regression from this commit.

Comment thread cyclops/core/compaction.py Resolved
Adds AgentConfig.compaction: before each completion the run counts the
request with LiteLLM's token_counter against the model's max_input_tokens
and, past a threshold, replaces the older messages with a summary the
model writes, keeping the system prompt, the most recent messages and
every tool call with its results. Agent.compact() does the same on demand.
A Compacted event and the on_compaction hook report it.

Adds AgentConfig.max_tool_output_chars, which cuts long tool results in
the middle with a note of what was omitted.
…ools

- Save the whole session after a compaction, through the session saver.
- Always keep the last message, and move a cut that lands among tool
  results back to their call.
- Don't summarize an earlier summary on its own; after a compaction that
  leaves the request past the threshold, warn once and stop compacting.
- Send the summarizing model only the newest messages that fit its window.
- Raise on an empty, cut or filtered summary, leaving the transcript.
- Raise ValueError when compaction is set and the model's limits are unknown.
- Count the tools a run sends: again when a search loads deferred ones,
  and only the always loaded ones in Agent.compact().
The summarizing request reserved the agent's max_tokens, or else the
model's output limit, which for a model whose output limit equals its
input limit left no room and summarized nothing. It now gets max_tokens
of keep of the window, capped at the output limit, and raises when the
transcript would be empty.
The summary's max_tokens of keep of the window can fall under the
agent's thinking budget, which Anthropic models reject. The summarizing
request now drops thinking and reasoning_effort, as it drops cache
markers.

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Context window management: compaction and tool output limits

1 participant