The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): preserve tool cache in iteration summary
ywatanabe419a05042759
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 3013eb61242..ee612290d58 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2069,8 +2069,17 @@ def _iteration_summary_chat_kwargs(agent, api_messages: list) -> dict:return summary_kwargs-def _summary_text(agent, response, **normalize_kwargs) -> str:- return (agent._get_transport().normalize_response(response, **normalize_kwargs).content or "").strip()+def _summary_text_with_scrub(agent, response, **normalize_kwargs) -> str:+ """Keep summary text while discarding any tool calls emitted alongside it.++ Summary callers never execute the normalized ``tool_calls``. A response+ containing only tool calls therefore becomes empty and follows the existing+ single-retry path in ``handle_max_iterations``.+ """+ normalized = agent._get_transport().normalize_response(response, **normalize_kwargs)+ if getattr(normalized, "tool_calls", None):+ logger.warning("Iteration summary emitted tool calls; discarding them")+ return (normalized.content or "").strip()def _codex_summary_attempt(agent, api_messages: list, api_request_id: str):@@ -2081,7 +2090,7 @@ def _codex_summary_attempt(agent, api_messages: list, api_request_id: str):codex_kwargs.pop("tools", None)codex_kwargs.pop("tool_choice", None)codex_kwargs.pop("parallel_tool_calls", None)- return _summary_text(agent, agent._run_codex_stream(codex_kwargs))+ return _summary_text_with_scrub(agent, agent._run_codex_stream(codex_kwargs))return _attempt@@ -2093,18 +2102,23 @@ def _anthropic_summary_attempt(agent, api_messages: list, api_request_id: str):preserve_dots=agent._anthropic_preserve_dots(), base_url=getattr(agent, "_anthropic_base_url", None))ant_kw = _merge_nous_portal_messages_extra_body(agent, ant_kw)response = _managed_summary_call(agent, api_request_id, ant_kw, agent._anthropic_messages_create, retry_count=retry_count)- return _summary_text(agent, response, strip_tool_prefix=agent._is_anthropic_oauth)+ return _summary_text_with_scrub(agent, response, strip_tool_prefix=agent._is_anthropic_oauth)return _attemptdef _chat_summary_attempt(agent, api_messages: list, api_request_id: str):- summary_kwargs = _iteration_summary_chat_kwargs(agent, api_messages)+ # Use the ordinary request builder so the summary inherits the exact tool+ # transformation and cache-routing path (including xAI aliases, Moonshot+ # schema sanitization, and prompt_cache_key). In particular, do not force+ # tool_choice="none": SGLang removes tools from its rendered prompt in that+ # mode, which would invalidate the cached prefix this path is preserving.+ summary_kwargs = agent._build_api_kwargs(api_messages)def _attempt(retry_count: int) -> str:summary_client = agent._ensure_primary_openai_client(reason="iteration_limit_summary_retry" if retry_count else "iteration_limit_summary")response = _managed_summary_call(agent, api_request_id, summary_kwargs, lambda request: summary_client.chat.completions.create(**request), retry_count=retry_count)- return _summary_text(agent, response)+ return _summary_text_with_scrub(agent, response)return _attemptdiff --git a/tests/agent/test_api_content_sidecar.py b/tests/agent/test_api_content_sidecar.pyindex ce7f3cb9be3..2f65df5c1be 100644--- a/tests/agent/test_api_content_sidecar.py+++ b/tests/agent/test_api_content_sidecar.py@@ -863,22 +863,23 @@ class TestMaxIterationsSummaryReplay:class _Completions:def create(self, **kwargs):captured.update(kwargs)- return "RAW-RESPONSE"+ return types.SimpleNamespace(+ choices=[types.SimpleNamespace(+ message=types.SimpleNamespace(content="SUMMARY", tool_calls=None),+ finish_reason="stop",+ )],+ )client = types.SimpleNamespace(chat=types.SimpleNamespace(completions=_Completions()))- transport = types.SimpleNamespace(- normalize_response=lambda _r: types.SimpleNamespace(content="SUMMARY")- )-messages = [{"role": "user", "content": "q1", "api_content": "q1\n\nPLUGIN-CTX"},{"role": "assistant", "content": "a1"},]with patch.object(agent, "_ensure_primary_openai_client", return_value=client- ), patch.object(agent, "_get_transport", return_value=transport):+ ):out = handle_max_iterations(agent, messages, 5)assert out == "SUMMARY"diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex 9418b396b90..0dd326dc9f5 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -2783,6 +2783,46 @@ class TestHandleMaxIterations:kwargs = agent.client.chat.completions.create.call_args.kwargsassert "reasoning" not in kwargs.get("extra_body", {})+ def test_summary_uses_ordinary_tools_and_prompt_cache_key(self, agent):+ """The terminal summary follows the ordinary request's cache lineage."""+ agent.client.chat.completions.create.side_effect = [+ _mock_response(content=""),+ _mock_response(content="Summary"),+ ]+ agent.base_url = "https://api.openai.com/v1"+ agent.provider = "openai"+ agent._cached_system_prompt = "You are helpful."+ messages = [{"role": "user", "content": "do stuff"}]+ ordinary = agent._build_api_kwargs(+ [{"role": "system", "content": agent._cached_system_prompt}, *messages]+ )++ result = agent._handle_max_iterations(messages, 60)++ summaries = [call.kwargs for call in agent.client.chat.completions.create.call_args_list]+ assert result == "Summary"+ assert len(summaries) == 2+ assert all(summary["tools"] == ordinary["tools"] for summary in summaries)+ assert all(summary["prompt_cache_key"] == ordinary["prompt_cache_key"] for summary in summaries)+ assert all(summary.get("tool_choice") == ordinary.get("tool_choice") for summary in summaries)+ assert all(summary["model"] == ordinary["model"] for summary in summaries)+ assert all(summary["messages"][0] == ordinary["messages"][0] for summary in summaries)++ def test_summary_tool_call_only_response_retries_once(self, agent):+ """A tool-only summary is scrubbed to empty and receives one retry."""+ agent.client.chat.completions.create.side_effect = [+ _mock_response(content="", tool_calls=[_mock_tool_call()]),+ _mock_response(content="Summary"),+ ]+ agent._cached_system_prompt = "You are helpful."++ result = agent._handle_max_iterations(+ [{"role": "user", "content": "do stuff"}], 60,+ )++ assert result == "Summary"+ assert agent.client.chat.completions.create.call_count == 2+def test_summary_request_removes_orphan_tool_result(self, agent):"""Regression: max-iterations summary request must NOT containorphan tool results (tool_call_id with no matching assistant tool_call)."""