The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(conversation_loop): compress messages on output-cap retry path (#55546)
Hermes Agent9938d2050338
diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 00000000000..942dc3c62dd--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,25 @@+# Changelog++## [v0.19.2] — 2026-08-03++### Fixed+- **context_compressor / conversation_loop**: Output-cap retry path now compresses message history (#55546)++ Previously, when the provider returned an "output cap too large" HTTP 400, the+ retry loop only reduced `max_tokens` by 64 tokens per attempt. The input grew by+ ~65 tokens each retry, leaving the total stuck at 200,001 tokens — 1 token over+ the 200,000 ceiling. After 3 retries, the session crashed with+ `compression_exhausted=True`.++ The fix adds `_compress_context()` to the output-cap retry path so the compressor+ drops the middle window, freeing ~50% of tokens in one pass. If compression makes+ ≥5% savings, the session continues; otherwise vision payloads are stripped, and+ if that fails too, the session ends with a clear "cannot compress further" message.++ Affected providers: vLLM, DashScope (Qwen), OpenRouter, LM Studio, Anthropic.++### Testing+- `test_output_cap_parsing.py` — output-cap error parsing across providers+- `test_1630_context_overflow_loop.py` — context overflow heuristic and compression_exhausted flag+- `test_preflight_compression_cap_e2e.py` — preflight compression with configurable max_attempts+- `test_max_tokens_propagation.py` — max_tokens config propagation to gateway\ No newline at end of filediff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex ad25a31553e..e5f6c20e0db 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -4764,6 +4764,50 @@ def run_conversation("failed": True,"compression_exhausted": True,}+ # Also compress the message history so the output-cap+ # retry does not just spin on max_tokens alone. The+ # compressor drops the middle window, freeing enough+ # tokens for the total to fit inside context_length.+ # (#55546)+ try:+ original_len = len(messages)+ original_tokens = estimate_messages_tokens_rough(messages)+ _overflow_input = messages+ messages, active_system_prompt = agent._compress_context(+ messages, system_message,+ approx_tokens=estimate_request_tokens_rough(api_messages, tools=agent.tools or None),+ task_id=effective_task_id,+ )+ if messages is _overflow_input and compression_skipped_due_to_lock(agent):+ compression_attempts -= 1+ agent._persist_session(messages, conversation_history)+ return _compression_deferred_result(+ agent, messages, api_call_count+ )+ conversation_history = conversation_history_after_compression(+ agent, messages, conversation_history+ )+ new_tokens = estimate_messages_tokens_rough(messages)+ approx_tokens = new_tokens+ if len(messages) < original_len:+ agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))+ elif new_tokens > 0 and new_tokens < original_tokens * 0.95:+ agent._buffer_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))+ elif agent._try_strip_image_parts_from_tool_messages(+ api_messages,+ remember_model=False,+ ):+ agent._buffer_status(+ "📐 Compression could not reduce the request further — "+ "removed retained vision payloads and retrying..."+ )+ except Exception:+ # Compression must never turn an output-cap error+ # fatal — fall through and retry on max_tokens alone.+ logger.warning(+ "%sOutput-cap compression hit an error; retrying on max_tokens only.",+ agent.log_prefix,+ )_retry.restart_with_compressed_messages = Truebreakdiff --git a/docs/reports/output_cap_compression_fix.md b/docs/reports/output_cap_compression_fix.mdnew file mode 100644index 00000000000..8ecdd68e283--- /dev/null+++ b/docs/reports/output_cap_compression_fix.md@@ -0,0 +1,111 @@+# Output-Cap Compression Fix: Detailed Report++## The Bug++When a provider returns an "output cap too large" HTTP 400 (e.g. `max_tokens`+exceeds the space left in the context window), the retry path reduced+`max_tokens` by 64 tokens per attempt but never called `_compress_context()`.+The message compressor was not wired into this path at all.++Because the compressor never fired, each retry made almost no real progress:+input grew by ~65 tokens per attempt while the output cap shrank by 64, for a+net effect of ~1 token per attempt. The total footprint stayed just over the+context ceiling instead of coming back under it.++## What Happened (observed token math)++- Input grew per attempt: 134,465 → 134,530 → 134,595 → 134,660+- Output cap shrank per attempt: 65,535 → 65,471 → 65,406 → 65,341 → 65,276+- Net: ~1 token of growth per retry (65 − 64 = 1)+- Total stayed at 200,001 tokens — 1 over the 200,000 ceiling+- After the retry budget was exhausted, the run ended with+ `compression_exhausted=True` and the session dropped.++## How It Broke++The output-cap retry loop only adjusted `max_tokens` each pass. The flag it set+to continue — `restart_with_compressed_messages` — is named as though the+messages get compressed, but the messages were **not** actually compressed on+this branch. The compressor simply was not invoked, so nothing reduced the+growing footprint.++This path is old (~4 months, from a series of compaction/output-cap changes),+but the details of exactly which change first introduced it are less important+than the current behavior and the fix.++## Root Cause (factual)++The output-cap handling dates back to a compaction/output-cap change Apr 2026;+it was later refactored into `agent/conversation_loop.py` (May 2026) and its+cap calculation refined (Jul 2026). The defect is behavioral rather than+attributable to one edit: the output-cap branch set+`restart_with_compressed_messages = True` without ever calling+`_compress_context()`, so nothing actually shrank the in-flight footprint.++## Why It Surfaced Now (Aug 2026)++The bug is old (~4 months) but latent — it only becomes reachable when a+conversation actually fills or near-fills its context window **and** the+provider returns the specific "output cap too large" wording the parser+matches. That combination is rare; most sessions never get near the ceiling.++What changed leading up to the first real-world exposure in early Aug 2026:++1. Two token-estimator accuracy fixes reduced the reported token counts:+ - `530503a6a` (2026-07-28): exclude `reasoning_details` from the preflight+ estimate. Its own message notes that field inflated the rough estimate by+ ~4x and caused compression far too early (a measured session reported+ ~533K estimated vs ~140K real).+ - `e3bc51703` (2026-07-31): stop double-counting `api_content`.+2. The preflight auto-compression gate (`should_compress()` ->+ `should_compress_info()`) uses the same estimator, comparing+ `prompt_tokens >= threshold_tokens`, where+ `threshold_tokens ≈ (context_length − max_tokens) × 0.50`. With these fixes,+ the estimate dropped, so preflight judged sessions "under threshold" and+ deferred compression far longer than before.+3. A long-running session therefore reached the hard context ceiling for the+ first time, hit the provider's output-cap 400, and entered the output-cap+ retry branch — which (pre-fix) never compressed and death-looped.++In short: the Jul estimator fixes did not introduce the death-loop; they+unmasked it. They removed the (over-aggressive) early compression that had been+silently keeping sessions away from the ceiling, exposing the latent+never-compresses-on-output-cap defect.++## The Fix++Add `_compress_context()` to the output-cap retry path so the message history+is actually compressed before retrying:++1. The compressor drops the middle window, freeing a large fraction of tokens+ in a single pass.+2. If compression made real progress, the session continues under the ceiling.+3. If compression could not reduce further, vision payloads are stripped and it+ retries again.+4. Compression failures are non-fatal: if anything goes wrong during+ compression, the code falls back to retrying on `max_tokens` alone. The+ existing max-attempts guard still bounds the retry loop, so it cannot spin+ forever.++## Verification++- Both output-cap retry regression tests pass:+ `test_output_cap_retry_uses_provider_available_out` and+ `test_output_cap_retry_with_large_api_only_content`.+- Full `tests/run_agent/test_run_agent.py`: 232 passed, 1 failed — and the 1+ failure (`test_interruptible_anthropic_interrupt_never_closes_shared_client`)+ is a pre-existing environment issue (missing `anthropic` package), failing+ identically on a clean base without this change.+- `ruff check` passes on both modified files.++## Impact++- Sessions at the context ceiling now recover via message compression instead+ of exhausting retries.+- Applies across providers (vLLM, DashScope/Qwen, OpenRouter, LM Studio,+ Anthropic). Additive fix; no breaking changes.++## Affected Code++`agent/conversation_loop.py` — the output-cap retry block (added compression to+the retry path that previously only adjusted `max_tokens`).diff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex 6161e266b07..b77ee236aed 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -4090,7 +4090,10 @@ class TestRunConversation:ok_resp = _mock_response(content="done", finish_reason="stop")agent.client.chat.completions.create.side_effect = [exc, ok_resp]- mock_compress = MagicMock()+ mock_compress = MagicMock(return_value=(+ [{"role": "user", "content": "hello"}],+ "You are helpful.",+ ))with (patch.object(agent, "_persist_session"),patch.object(agent, "_save_trajectory"),@@ -4104,7 +4107,7 @@ class TestRunConversation:assert result["completed"] is Trueassert second_call["max_tokens"] <= 936assert agent.context_compressor.context_length == 200_000- mock_compress.assert_not_called()+ mock_compress.assert_called_once()def test_output_cap_retry_with_large_api_only_content(self, agent):"""When a large system prompt makes api_messages huge while persisted@@ -4134,7 +4137,10 @@ class TestRunConversation:ok_resp = _mock_response(content="done", finish_reason="stop")agent.client.chat.completions.create.side_effect = [exc, ok_resp]- mock_compress = MagicMock()+ mock_compress = MagicMock(return_value=(+ [{"role": "user", "content": "hello"}],+ "You are helpful.",+ ))with (patch.object(agent, "_persist_session"),patch.object(agent, "_save_trajectory"),@@ -4150,8 +4156,64 @@ class TestRunConversation:# near 199927 — this test fails on it.assert second_call["max_tokens"] <= 936assert agent.context_compressor.context_length == 200_000- mock_compress.assert_not_called()+ mock_compress.assert_called_once()++ def test_output_cap_retry_triggers_compression_and_recovers(self, agent):+ """Regression for the output-cap death-loop (#55546 / #61761).++ When the provider reports an output-cap error on a near-full context+ window, the retry must NOT just shrink max_tokens by a tiny amount and+ spin forever. It must fire _compress_context() to actually free tokens+ so the session recovers instead of exhausting compression_attempts.+ This locks in the fix: previously the output-cap path set+ restart_with_compressed_messages without ever calling the compressor.+ """+ self._setup_agent(agent)+ agent.api_mode = "chat_completions"+ agent.provider = "openrouter"+ agent.model = "some/model"+ agent.max_tokens = 65_536+ agent.compression_enabled = True+ agent.context_compressor.context_length = 200_000+ # Context is essentially full -> compressor would want to run.+ agent.context_compressor.should_compress = MagicMock(return_value=True)++ error_msg = (+ "max_tokens: 65536 > context_window: 200000 "+ "- input_tokens: 199000 = available_tokens: 1000"+ )+ exc = Exception(error_msg)+ exc.status_code = 400+ exc.code = 400++ ok_resp = _mock_response(content="done", finish_reason="stop")+ agent.client.chat.completions.create.side_effect = [exc, ok_resp]++ # Compress drops the huge history (15 msgs -> 1), freeing tokens.+ mock_compress = MagicMock(return_value=(+ [{"role": "user", "content": "hello"}],+ "You are helpful.",+ ))+ with (+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ patch.object(agent.context_compressor, "update_model"),+ patch.object(agent, "_compress_context", mock_compress),+ ):+ result = agent.run_conversation("hello")++ # Compression fired exactly once, on the output-cap retry.+ mock_compress.assert_called_once()+ # The compressed messages were re-sent and the call succeeded.+ assert result["completed"] is True+ assert result["final_response"] == "done"+ # The retry honored the reduced max_tokens (available_out - 64).+ second_call = agent.client.chat.completions.create.call_args_list[1].kwargs+ assert second_call["max_tokens"] <= 936+ # context_length was NOT mutated by an output-cap error.+ assert agent.context_compressor.context_length == 200_000