The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): share the truncation-retry output boost; clamp to model limit (#72770, #79715)
kshitijk4poorf477c13d533d
diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex 8786dc7b62a..66163155a48 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -19,6 +19,7 @@ from typing import Any, Dictfrom agent.display import KawaiiSpinnerfrom agent.interrupt_control import interrupt_issuerfrom agent.turn_context_compaction import _reanchor+from agent.turn_truncation import boosted_output_caplogger = logging.getLogger("agent.conversation_loop")@@ -529,15 +530,10 @@ def apply_retry_restarts(return _verdict("continue")if _retry.restart_with_length_continuation:- # Boost output budget per retry: 2×, 4×, 8×, 16× base, capped at 32 768, via- # _ephemeral_max_output_tokens. Keep a larger original provider/model- # default as the floor so retries never downshift.- _boost = (agent.max_tokens or 4096) * (2 ** length_continue_retries)- _requested_cap = agent._requested_output_cap_from_api_kwargs(api_kwargs)- if _requested_cap is not None:- _boost = max(_boost, _requested_cap)- _boost_cap = max(32768, _requested_cap or 0)- agent._ephemeral_max_output_tokens = min(_boost, _boost_cap)+ # Boost the output budget per retry (shared ladder, see boosted_output_cap).+ agent._ephemeral_max_output_tokens = boosted_output_cap(+ agent, agent._requested_output_cap_from_api_kwargs(api_kwargs), length_continue_retries+ )return _verdict("continue")# All retries may exhaust with `response` still None; break out cleanly.diff --git a/agent/turn_truncation.py b/agent/turn_truncation.pyindex af2b3876c26..fbecb43bf3b 100644--- a/agent/turn_truncation.py+++ b/agent/turn_truncation.py@@ -316,6 +316,33 @@ def _continue_text(st: _Trunc, _retry: TurnRetryState, assistant_message: Any) -)+def _model_output_limit(agent: Any) -> Optional[int]:+ """The model's real max output tokens when Hermes knows it, else None."""+ if getattr(agent, "api_mode", None) != "anthropic_messages":+ return None+ # Local: only Anthropic-Messages turns need the adapter module.+ from agent.anthropic_adapter import _get_anthropic_max_output+ return _get_anthropic_max_output(getattr(agent, "model", None) or "")+++def boosted_output_cap(agent: Any, requested_cap: Optional[int], n: int, base: Optional[int] = None) -> int:+ """Output budget for truncation retry ``n`` (1-based): ``base·2ⁿ``, never below the+ failed request's cap, at most ``max(32768, 2×cap)``, and never above the model's+ known output limit. ``base`` defaults to max_tokens, else the cap actually sent.++ A ceiling equal to the requested cap would re-send the same budget (#72770); a+ ceiling past the model limit only buys a provider 400 (#79715).+ """+ if base is None:+ base = agent.max_tokens or requested_cap or 4096+ anchor = requested_cap or base+ limit = _model_output_limit(agent)+ if limit and anchor >= limit:+ return anchor # already at the model ceiling: doubling cannot help+ boost = min(max(base * (2 ** n), requested_cap or 0), max(32768, anchor * 2))+ return min(boost, limit) if limit else boost++def _retry_truncated_tool_call(st: _Trunc, api_kwargs: Any) -> TruncationVerdict:"""Truncated tool call: re-run the same call (up to 4×) with a boosted max_tokens —a real output-cap truncation needs it, harmless for a network stall — else refuse to@@ -328,13 +355,9 @@ def _retry_truncated_tool_call(st: _Trunc, api_kwargs: Any) -> TruncationVerdictagent._buffer_vprint(f"⚠️ Stream interrupted mid tool-call — retrying ({n}/4)...")else:agent._buffer_vprint(f"⚠️ Truncated tool call detected — retrying API call ({n}/4)...")- _tc_requested_cap = agent._requested_output_cap_from_api_kwargs(api_kwargs)- # Ladder from the budget actually in use when max_tokens is unset, and cap at 2×- # that budget — a ceiling equal to the requested cap re-sends the same request (#72770).- _tc_boost = (agent.max_tokens if agent.max_tokens else (_tc_requested_cap or 4096)) * (2 ** n)- if _tc_requested_cap is not None:- _tc_boost = max(_tc_boost, _tc_requested_cap)- agent._ephemeral_max_output_tokens = min(_tc_boost, max(32768, (_tc_requested_cap or 0) * 2))+ agent._ephemeral_max_output_tokens = boosted_output_cap(+ agent, agent._requested_output_cap_from_api_kwargs(api_kwargs), n+ )return st.done("continue") # don't append the broken responseagent._flush_status_buffer()if st.is_stub:@@ -571,8 +594,9 @@ def continue_codex_incomplete(# output_tokens IS that ceiling, so seed the escalation from it (else 4096).usage = getattr(response, "usage", None)observed = getattr(usage, "output_tokens", None) if not isinstance(usage, dict) else usage.get("output_tokens")- base = agent.max_tokens or int(observed or 0) or 4096- agent._ephemeral_max_output_tokens = min(base * (2 ** n), max(32768, base))+ agent._ephemeral_max_output_tokens = boosted_output_cap(+ agent, None, n, base=agent.max_tokens or int(observed or 0) or 4096+ )if not agent.quiet_mode:agent._vprint(f"{agent.log_prefix}↻ Codex response incomplete; continuing turn ({n}/3)", diagnostic=True)# Spinner/heartbeat notice: these retries can take minutes and otherwise lookdiff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex 47413ee6cc7..25d64e224b9 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -4099,7 +4099,8 @@ class TestRunConversation:assert second_call_messages[-1]["role"] == "user"def test_length_continuation_preserves_large_provider_default_output_cap(self, agent):- """Continuation retries must not shrink a higher provider default cap."""+ """Continuation retries must not shrink a higher provider default cap — and must+ raise it, since re-sending the same cap just truncates again (#72770)."""self._setup_agent(agent)agent.max_tokens = Nonerequested_caps = []@@ -4126,7 +4127,7 @@ class TestRunConversation:assert result["completed"] is Trueassert result["final_response"] == "Part 1 Part 2"- assert requested_caps == [65536, 65536]+ assert requested_caps == [65536, 131072]def test_ollama_glm_stop_after_tools_without_terminal_boundary_requests_continuation(self, agent):"""Local Ollama-hosted GLM (no :cloud suffix) misreports truncated output as stop."""diff --git a/tests/agent/test_truncated_tool_call_boost.py b/tests/agent/test_truncated_tool_call_boost.pyindex d0f3b077b93..9e9e51b6b2d 100644--- a/tests/agent/test_truncated_tool_call_boost.py+++ b/tests/agent/test_truncated_tool_call_boost.py@@ -1,18 +1,25 @@-"""Truncated tool-call retries must send a larger output budget than the failed request (#72770)."""+"""Truncation retries must send a larger output budget than the failed request (#72770),+without exceeding the model's known output limit (#79715)."""from types import SimpleNamespaceimport pytest+from agent.turn_iteration_prep import apply_retry_restarts+from agent.turn_retry_state import TurnRetryStatefrom agent.turn_truncation import _retry_truncated_tool_call-def _retry_budgets(max_tokens, requested_cap, attempts=4):- agent = SimpleNamespace(+def _agent(max_tokens, requested_cap, **extra):+ return SimpleNamespace(max_tokens=max_tokens,_ephemeral_max_output_tokens=None,_buffer_vprint=lambda *a, **k: None,_requested_output_cap_from_api_kwargs=lambda kw: requested_cap,+ **extra,)+++def _tool_call_budgets(agent, attempts=4):st = SimpleNamespace(agent=agent, truncated_tool_call_retries=0, is_stub=False)st.done = lambda action, result=None: actionbudgets = []@@ -22,12 +29,43 @@ def _retry_budgets(max_tokens, requested_cap, attempts=4):return budgets+def _length_continuation_budgets(agent, attempts=4):+ budgets = []+ for n in range(1, attempts + 1):+ _retry = TurnRetryState()+ _retry.restart_with_length_continuation = True+ verdict = apply_retry_restarts(+ agent, _retry=_retry, response=None, interrupted=False, messages=[],+ conversation_history=[], user_message="hi", api_kwargs={}, current_turn_user_idx=0,+ final_response=None, retry_count=0, max_retries=3, api_call_count=1,+ restart_count=0, length_continue_retries=n,+ _preflight_compression_blocked=False, _turn_exit_reason="unknown",+ )+ assert verdict.action == "continue"+ budgets.append(agent._ephemeral_max_output_tokens)+ return budgets+++SITES = [_tool_call_budgets, _length_continuation_budgets]++[email protected]("site", SITES)@pytest.mark.parametrize("requested_cap", [32768, 65536])-def test_retry_raises_budget_above_large_requested_cap(requested_cap):- budgets = _retry_budgets(None, requested_cap)+def test_retry_raises_budget_above_large_requested_cap(site, requested_cap):+ budgets = site(_agent(None, requested_cap))assert budgets[0] > requested_capassert max(budgets) <= requested_cap * 2[email protected]("site", SITES)+def test_boost_clamped_to_known_model_output_limit(site):+ # claude-sonnet-4-5 outputs at most 64000: never ask for more, and don't double a+ # request that already sits at the ceiling (the provider would 400).+ below = site(_agent(None, 40000, api_mode="anthropic_messages", model="claude-sonnet-4-5"))+ at_limit = site(_agent(None, 64000, api_mode="anthropic_messages", model="claude-sonnet-4-5"))+ assert below == [64000] * 4+ assert at_limit == [64000] * 4++def test_small_explicit_max_tokens_ladder_still_capped_at_floor():- assert _retry_budgets(4096, None) == [8192, 16384, 32768, 32768]+ assert _tool_call_budgets(_agent(4096, None)) == [8192, 16384, 32768, 32768]