Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(learn): retry LLM analysis with a smaller digest when the prompt overflows the context window (#3404)
gglucassd329a04b4b55
diff --git a/headroom/learn/analyzer.py b/headroom/learn/analyzer.pyindex 5fdb44a0e..4a429ef02 100644--- a/headroom/learn/analyzer.py+++ b/headroom/learn/analyzer.py@@ -48,6 +48,10 @@ _MODEL_DEFAULTS: list[tuple[str, str]] = []_MAX_DIGEST_TOKENS = 80_000 # Budget for the digest (leave room for prompt + output)+# Smallest digest budget worth retrying with after a context overflow. The+# budget halves on each "prompt is too long" failure; below this the digest+# carries too little signal to produce useful recommendations.+_MIN_DIGEST_TOKENS = 10_000# CLI tools to try when no API key is set (checked in order).# Each entry: (binary_name, model_identifier, command_prefix). The claude-cli@@ -187,26 +191,38 @@ class SessionAnalyzer:if not failed_calls and not loops and not any(s.events for s in sessions):return result- # Build compact digest of all sessions, leading with detected loops.- digest = _build_digest(project, sessions, loops=loops)-# Resolve model (auto-detect if not specified)model = self.model or _detect_default_model()- # Call LLM for analysis- try:- raw = _call_llm(digest, model)- result.recommendations = _parse_llm_response(raw)- # Weight loop guardrails above one-off rules using MEASURED waste.- apply_loop_weighting(result.recommendations, loops)- result.recommendations.sort(key=lambda r: r.estimated_tokens_saved, reverse=True)- except Exception as e:- logger.warning("LLM analysis failed: %s", e)- # Preserve the stats so multi-project runs can continue, but retain- # the failure so the CLI cannot report an empty result as success.- result.analysis_error = str(e) or type(e).__name__-- return result+ # Call LLM for analysis. The digest budget only bounds our side of the+ # prompt: CLI backends (claude -p) load the user's own context on top+ # (CLAUDE.md, MCP tool definitions), so a full-budget digest can still+ # overflow the model's window. On a context-overflow error, rebuild the+ # digest at half the budget and retry.+ budget = _MAX_DIGEST_TOKENS+ while True:+ # Build compact digest of all sessions, leading with detected loops.+ digest = _build_digest(project, sessions, loops=loops, max_tokens=budget)+ try:+ raw = _call_llm(digest, model)+ result.recommendations = _parse_llm_response(raw)+ # Weight loop guardrails above one-off rules using MEASURED waste.+ apply_loop_weighting(result.recommendations, loops)+ result.recommendations.sort(key=lambda r: r.estimated_tokens_saved, reverse=True)+ except Exception as e:+ if _is_prompt_too_long(e) and budget > _MIN_DIGEST_TOKENS:+ budget //= 2+ logger.info(+ "Prompt too long for %s; retrying with a %d-token digest budget",+ model,+ budget,+ )+ continue+ logger.warning("LLM analysis failed: %s", e)+ # Preserve the stats so multi-project runs can continue, but retain+ # the failure so the CLI cannot report an empty result as success.+ result.analysis_error = str(e) or type(e).__name__+ return result# =============================================================================@@ -253,10 +269,32 @@ def _build_prior_patterns_section(project: ProjectInfo) -> str:return "\n".join(lines)+def _is_prompt_too_long(exc: Exception) -> bool:+ """True when *exc* signals the prompt overflowed the model's context window.++ Matches the known phrasings across backends: claude CLI ("Prompt is too+ long"), Anthropic via LiteLLM ("prompt is too long: N tokens > M maximum"),+ OpenAI ("context_length_exceeded" / "maximum context length"), and Gemini+ ("input token count exceeds the maximum").+ """+ msg = str(exc).lower()+ return any(+ needle in msg+ for needle in (+ "prompt is too long",+ "context_length_exceeded",+ "maximum context length",+ "context window",+ "token count exceeds",+ )+ )++def _build_digest(project: ProjectInfo,sessions: list[SessionData],loops: list[LoopPattern] | None = None,+ max_tokens: int = _MAX_DIGEST_TOKENS,) -> str:"""Build a token-efficient text digest of all session events.@@ -306,7 +344,7 @@ def _build_digest(# Budget tracking — stop adding events when we approach the limit# Rough estimate: 4 chars per token- char_budget = _MAX_DIGEST_TOKENS * 4+ char_budget = max_tokens * 4chars_used = sum(len(ln) for ln in lines)for session in sessions:diff --git a/tests/test_learn/test_analyzer.py b/tests/test_learn/test_analyzer.pyindex 69308f4e3..ce6e1bc4e 100644--- a/tests/test_learn/test_analyzer.py+++ b/tests/test_learn/test_analyzer.py@@ -475,6 +475,67 @@ class TestSessionAnalyzer:assert result.recommendations == []assert result.analysis_error == "API key not set"+ @patch("headroom.learn.analyzer._call_llm")+ def test_retries_smaller_digest_on_prompt_too_long(self, mock_call_llm: MagicMock):+ """A context-overflow error rebuilds the digest at half the budget and retries."""+ mock_call_llm.side_effect = [+ RuntimeError("`claude -p` failed (exit 1):\nPrompt is too long"),+ {"context_file_rules": [], "memory_file_rules": []},+ ]++ analyzer = SessionAnalyzer(model="test-model")+ sessions = [+ SessionData(+ session_id="s1",+ tool_calls=[+ # Enough volume to overflow even the halved (40k-token) budget,+ # so the retry digest is visibly shorter than the first.+ _tc(msg_index=i, is_error=True, output="x" * 200)+ for i in range(2000)+ ],+ )+ ]+ result = analyzer.analyze(_project(), sessions)++ assert mock_call_llm.call_count == 2+ first_digest = mock_call_llm.call_args_list[0][0][0]+ second_digest = mock_call_llm.call_args_list[1][0][0]+ assert len(second_digest) < len(first_digest)+ assert result.recommendations == []++ @patch("headroom.learn.analyzer._call_llm")+ def test_gives_up_when_min_digest_budget_still_too_long(self, mock_call_llm: MagicMock):+ """Persistent overflow stops at the minimum budget instead of looping forever."""+ mock_call_llm.side_effect = RuntimeError("Prompt is too long")++ analyzer = SessionAnalyzer(model="test-model")+ sessions = [+ SessionData(+ session_id="s1",+ tool_calls=[_tc(msg_index=0, is_error=True, output="error")],+ )+ ]+ result = analyzer.analyze(_project(), sessions)++ # Budgets: 80k, 40k, 20k, 10k — then give up.+ assert mock_call_llm.call_count == 4+ assert result.recommendations == []++ @patch("headroom.learn.analyzer._call_llm")+ def test_non_overflow_failure_does_not_retry(self, mock_call_llm: MagicMock):+ mock_call_llm.side_effect = RuntimeError("API key not set")++ analyzer = SessionAnalyzer(model="test-model")+ sessions = [+ SessionData(+ session_id="s1",+ tool_calls=[_tc(msg_index=0, is_error=True, output="error")],+ )+ ]+ analyzer.analyze(_project(), sessions)++ mock_call_llm.assert_called_once()+@patch("headroom.learn.analyzer._call_llm")def test_passes_events_to_digest(self, mock_call_llm: MagicMock):"""User messages and subagent events should appear in the digest."""