Repository navigation
feat: summarize older messages near the model's input limit - #118
Conversation
gopaljigaur
left a comment
There was a problem hiding this comment.
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:
- #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. - 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.
- A summary that leaves the request past the threshold is redone every step (3 compactions in 3 steps in a probe).
- The summary request can overflow the summarizing model (smaller
Compaction.model, or a session already past the window). - An empty or cut summary replaces the messages.
- Compaction on a model with unknown limits silently does nothing; LangChain raises.
- Not on top of main: conflicts with #110, and the fixed token count ignores tools loaded mid run.
- Naive fallback after a compaction reports and pays for a compaction it undoes.
- 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.
90ded7b to
081b684
Compare
gopaljigaur
left a comment
There was a problem hiding this comment.
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:
- Autosave: fixed.
_savenow sets_savedwhen the save is scheduled, sorewritten()can't be undone by a pending write. My probe with #115 on main stores exactly the in-memory session in bothsyncandasyncmode. - 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_cutoffdoesn'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. - 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
compactdirectly and ignores the flag, so a stuck run still recovers once it overflows. - Summary input: the author's reasons for not using
trim_messagescheck out in LiteLLM 1.105.1.process_messagescallstoken_counteron the whole accumulated list for each message, so it is quadratic.shorten_message_to_fit_limitremoves characters from the middle.trim_messagescatches every exception and returns the original messages. The hand-rolled_trimmedreuses the cached counts and is short. The budget has the bug above. - Empty or cut summary: fixed. It raises before the transcript changes.
- Unknown limits: fixed. It raises
ValueErrorat run start and fromacompact. - Deferred tools: fixed.
request()recounts when the tools change, andacompactcounts only the tools a run starts with. - 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_compactionpins it. - Test gaps: covered.
Probes:
- The newest message is kept.
- The long-summary case compacts once and warns.
- A router with an unserved
Compaction.modelraisesValueErrorat the start. - On a 500-message session the first count takes 31 ms per run and each later step 0.04 ms.
081b684 to
d51822c
Compare
gopaljigaur
left a comment
There was a problem hiding this comment.
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 withmax_tokens=52428and 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.
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.
d51822c to
4aefaec
Compare
Keeps a run's requests within the model's context window.
What changed
AgentConfig.compaction(a newCompactionmodel, off by default). Before each completion the run counts the request withlitellm.token_counteragainstlitellm.get_model_info(...)["max_input_tokens"]. Once it reachesthreshold(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:").modelpicks another summarizing model andpromptthe instruction.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'sSummarizationMiddlewaredoes, so a call and its results stay together.cyclops/core/compaction.py,_ContextWindow).max_input_tokenssets the limit, throughRouter.get_router_model_info, so deploymentmodel_infooverrides count.compactionset, a model (or summarizing model) LiteLLM has nomax_input_tokensfor raisesValueErrorat the run's first step and fromcompact(), as LangChain does, with thelitellm.register_modelhint.max_tokensiskeepof 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'sthinkingorreasoning_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 raisesRuntimeError. It goes through_acompletion(retries,on_llm_start/on_llm_end/on_llm_error). Its usage counts in the run'susage,max_total_tokensandmax_cost, and it is not a step. An empty, cut or filtered summary raisesRuntimeErrorand leaves the transcript as it was.rewritten(), so the next save stores the whole session.Compactedevent (summary,replaced_messages,tokens_before,tokens_after) and anon_compaction(summary, tokens_before, tokens_after)hook.Agent.compact(session)/acompact(session)useconfig.compactionor the defaults and count the tools a run starts with. They add the summary's usage to the session and returnFalsewhen only an earlier summary would be summarized. Likesession.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.resultandRunResult.tool_callsget the cut text; hooks and middleware see the whole result.Decisions
SummarizationMiddleware, Pydantic AI's history processors and the OpenAI Agents SDK'sOpenAIResponsesCompactionSessionare all opt-in: compaction costs an extra completion and replaces what the model saw.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.context_managementthrough, soclear_tool_uses_20250919works fromcompletion_kwargs. Itscompact_20260112edit returns a compaction block inprovider_specific_fieldsthat has to be sent back, which the transcript does not keep, so this compaction is provider independent instead.Tests
tests/test_compaction.pyuses LiteLLM's realtoken_counterandmock_response, with a model registered with a 400 token limit. It covers:uv run pytest,uv run pre-commit run --all-filesanduv run mypy cyclopspass.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