The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(prompt-caching): tool-using sessions no longer 400 behind LiteLLM Anthropic proxies (#89886)
Teknium1d8946b40b93
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 7f1b67822db..dd30d99ed54 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -2274,6 +2274,7 @@ def plan_cache_sections_for_destination(from agent.prompt_caching import (build_prompt_cache_plan,effective_cache_ttl,+ envelope_tool_part_cache_markers_supported,strip_anthropic_cache_control,strip_anthropic_tool_cache_control,)@@ -2313,6 +2314,11 @@ def plan_cache_sections_for_destination(api_mode=api_mode,model=model,),+ # LiteLLM-style envelope routes forward part-level markers into+ # tool_result.content[] → non-retryable 400 (#89886).+ tool_part_markers=envelope_tool_part_cache_markers_supported(+ provider, base_url+ ),)return plan.messages, plan.toolsdiff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 56397d9501b..ceb7ce16aa5 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1666,6 +1666,8 @@ def _redecorate_prompt_cache_for_provider("_direct_native_anthropic_tool_cache_capability",lambda: False,)()+ from agent.prompt_caching import envelope_tool_part_cache_markers_supported+plan = build_prompt_cache_plan(messages,planned_tools,@@ -1679,6 +1681,11 @@ def _redecorate_prompt_cache_for_provider(native_anthropic=agent._use_native_cache_layout,static_system_prefix=static if isinstance(static, str) else None,direct_native_tool_cache=direct_tool_cache,+ # LiteLLM-style envelope routes forward part-level markers into+ # tool_result.content[] → non-retryable 400 (#89886).+ tool_part_markers=envelope_tool_part_cache_markers_supported(+ getattr(agent, "provider", ""), getattr(agent, "base_url", "")+ ),)messages = plan.messagesplanned_tools = plan.tools@@ -2541,6 +2548,10 @@ def run_conversation(# the thinking-only drop is about to remove or merge away.tools_for_api = agent.toolsif agent._use_prompt_caching and agent.provider != "moa":+ from agent.prompt_caching import (+ envelope_tool_part_cache_markers_supported,+ )+_static_system_prefix = getattr(agent, "_cached_system_prompt_static", None)_initial_cache_plan = build_prompt_cache_plan(api_messages,@@ -2559,6 +2570,11 @@ def run_conversation(else None),direct_native_tool_cache=agent._direct_native_anthropic_tool_cache_capability(),+ # LiteLLM-style envelope routes forward part-level markers into+ # tool_result.content[] → non-retryable 400 (#89886).+ tool_part_markers=envelope_tool_part_cache_markers_supported(+ getattr(agent, "provider", ""), getattr(agent, "base_url", "")+ ),)api_messages = _initial_cache_plan.messagestools_for_api = _initial_cache_plan.toolsdiff --git a/agent/moa_loop.py b/agent/moa_loop.pyindex d783afd99b6..052ca339b41 100644--- a/agent/moa_loop.py+++ b/agent/moa_loop.py@@ -441,6 +441,7 @@ def _maybe_apply_moa_cache_control(from agent.prompt_caching import (apply_anthropic_cache_control,effective_cache_ttl,+ envelope_tool_part_cache_markers_supported,)# Prefer an explicit kwarg, then a snapshot on the runtime dict@@ -471,6 +472,11 @@ def _maybe_apply_moa_cache_control(model=runtime.get("model") or "",),native_anthropic=native_layout,+ # LiteLLM-style envelope routes forward part-level markers into+ # tool_result.content[] → non-retryable 400 (#89886).+ tool_part_markers=envelope_tool_part_cache_markers_supported(+ runtime.get("provider") or "", runtime.get("base_url") or ""+ ),)except Exception as exc: # pragma: no cover - decoration must never break a calllogger.debug("MoA cache_control decoration skipped: %s", exc)diff --git a/agent/prompt_caching.py b/agent/prompt_caching.pyindex d947d7c164a..3ec04af759d 100644--- a/agent/prompt_caching.py+++ b/agent/prompt_caching.py@@ -34,7 +34,32 @@ class PromptCachePlan:return _count_cache_markers(self.messages, self.tools)-def _apply_cache_marker(msg: dict, cache_marker: dict, native_anthropic: bool = False) -> None:+def envelope_tool_part_cache_markers_supported(+ provider: str | None, base_url: str | None+) -> bool:+ """Whether the envelope-layout route honors part-level markers on role:tool.++ OpenRouter (and Nous Portal, which proxies to it) relocate a+ ``cache_control`` sitting on a tool message's content part onto the+ ``tool_result`` block during their OpenAI→Anthropic translation, so the+ marker is honored there. LiteLLM-style OpenAI-wire proxies instead map+ content parts verbatim: the part-level marker lands at+ ``tool_result.content[0]``, which the Anthropic Messages schema forbids —+ a non-retryable HTTP 400 that kills the whole turn (#89886). On those+ routes tool messages must not carry part-level markers at all; the+ breakpoint budget reallocates to the nearest eligible message instead.+ """+ from agent.agent_runtime_helpers import _is_litellm_route++ return not _is_litellm_route((provider or "").strip().lower(), base_url or "")+++def _apply_cache_marker(+ msg: dict,+ cache_marker: dict,+ native_anthropic: bool = False,+ tool_part_markers: bool = True,+) -> None:"""Add cache_control to a single message, handling all format variations."""role = msg.get("role", "")content = msg.get("content")@@ -45,6 +70,12 @@ def _apply_cache_marker(msg: dict, cache_marker: dict, native_anthropic: bool =msg["cache_control"] = cache_markerreturn+ if role == "tool" and not tool_part_markers:+ # Envelope route whose OpenAI→Anthropic translation copies content+ # parts verbatim (LiteLLM et al.): a part-level marker becomes+ # tool_result.content[0].cache_control → non-retryable 400 (#89886).+ return+if content is None or content == "":if role == "tool" and not native_anthropic:# OpenRouter rejects top-level cache_control on role:tool (silent@@ -90,7 +121,9 @@ def _apply_cache_marker(msg: dict, cache_marker: dict, native_anthropic: bool =last["cache_control"] = cache_marker-def _can_carry_marker(msg: dict, native_anthropic: bool) -> bool:+def _can_carry_marker(+ msg: dict, native_anthropic: bool, tool_part_markers: bool = True+) -> bool:"""True if a marker on this message is actually honored by the provider.On the native Anthropic layout every message works (top-level markers are@@ -99,9 +132,16 @@ def _can_carry_marker(msg: dict, native_anthropic: bool) -> bool:assistant turns that are pure tool_calls) and empty tool messages wouldreceive a top-level marker the provider ignores — wasting one of the fourbreakpoints. Skip those so the breakpoints land on messages that count.++ ``tool_part_markers=False`` (LiteLLM-style envelope routes, #89886)+ additionally excludes ALL role:tool messages: their part-level marker+ would be forwarded verbatim into ``tool_result.content[]`` and rejected+ with a non-retryable 400, so the breakpoint must reallocate instead."""if native_anthropic:return True+ if msg.get("role") == "tool" and not tool_part_markers:+ return Falsecontent = msg.get("content")if content is None or content == "":return False@@ -392,8 +432,14 @@ def build_prompt_cache_plan(native_anthropic: bool = False,static_system_prefix: str | None = None,direct_native_tool_cache: bool = False,+ tool_part_markers: bool = True,) -> PromptCachePlan:- """Build isolated cache sections for one resolved request destination."""+ """Build isolated cache sections for one resolved request destination.++ ``tool_part_markers=False`` (LiteLLM-style envelope routes, #89886)+ keeps ``cache_control`` off role:tool content parts; breakpoints+ reallocate to the nearest eligible non-tool message.+ """messages = copy.deepcopy(api_messages or [])strip_anthropic_cache_control(messages)planned_tools = strip_anthropic_tool_cache_control(tools)@@ -404,6 +450,7 @@ def build_prompt_cache_plan(cache_ttl=cache_ttl,native_anthropic=native_anthropic,static_system_prefix=static_system_prefix,+ tool_part_markers=tool_part_markers,)return PromptCachePlan(messages=planned_messages, tools=planned_tools)@@ -438,6 +485,7 @@ def apply_anthropic_cache_control(cache_ttl: str = "5m",native_anthropic: bool = False,static_system_prefix: str | None = None,+ tool_part_markers: bool = True,) -> List[Dict[str, Any]]:"""Apply Anthropic cache-control markers to API messages.@@ -455,6 +503,10 @@ def apply_anthropic_cache_control(:func:`strip_anthropic_cache_control` is copy-on-write on content parts —and the rest of the copy-on-write contract is unchanged (#90971).+ ``tool_part_markers=False`` (LiteLLM-style envelope routes, #89886)+ keeps markers off role:tool messages entirely; the breakpoint budget+ reallocates to the nearest eligible non-tool message.+Returns:Shallow copy of message list with selective deep copies of modified messages."""@@ -494,10 +546,19 @@ def apply_anthropic_cache_control(ifor i in range(len(messages))if messages[i].get("role") != "system"- and _can_carry_marker(messages[i], native_anthropic=native_anthropic)+ and _can_carry_marker(+ messages[i],+ native_anthropic=native_anthropic,+ tool_part_markers=tool_part_markers,+ )]for idx in non_sys[-remaining:]:messages[idx] = copy.deepcopy(messages[idx])- _apply_cache_marker(messages[idx], marker, native_anthropic=native_anthropic)+ _apply_cache_marker(+ messages[idx],+ marker,+ native_anthropic=native_anthropic,+ tool_part_markers=tool_part_markers,+ )return messagesdiff --git a/tests/agent/test_litellm_tool_part_cache_markers.py b/tests/agent/test_litellm_tool_part_cache_markers.pynew file mode 100644index 00000000000..0087d3618c1--- /dev/null+++ b/tests/agent/test_litellm_tool_part_cache_markers.py@@ -0,0 +1,127 @@+"""Regression tests for #89886: part-level cache_control on role:tool messages+must be suppressed on LiteLLM-style envelope routes.++LiteLLM's OpenAI→Anthropic translation copies tool-message content parts+verbatim, so a part-level ``cache_control`` lands at ``tool_result.content[0]``+— a placement the Anthropic Messages schema rejects with a non-retryable+HTTP 400 that kills the whole turn. OpenRouter relocates the marker correctly,+so the part-level form stays on for it.+"""++import copy++from agent.prompt_caching import (+ apply_anthropic_cache_control,+ build_prompt_cache_plan,+ envelope_tool_part_cache_markers_supported,+)+++def _tool_history():+ return [+ {"role": "system", "content": "sys"},+ {"role": "user", "content": "run the tool"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "t", "arguments": "{}"},+ }+ ],+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "tool output"},+ ]+++def _tool_messages(msgs):+ return [m for m in msgs if m.get("role") == "tool"]+++def _has_part_marker(msg):+ content = msg.get("content")+ if isinstance(content, list):+ return any(+ isinstance(p, dict) and "cache_control" in p for p in content+ )+ return False+++class TestEnvelopeToolPartMarkerSuppression:+ def test_litellm_route_detected_as_unsupported(self):+ assert not envelope_tool_part_cache_markers_supported(+ "litellm", "https://litellm.internal.example/v1"+ )+ assert not envelope_tool_part_cache_markers_supported(+ "custom:litellm", "https://gw.example.com/v1"+ )+ assert not envelope_tool_part_cache_markers_supported(+ "custom", "https://litellm-proxy.example.com/v1"+ )++ def test_openrouter_route_stays_supported(self):+ assert envelope_tool_part_cache_markers_supported(+ "openrouter", "https://openrouter.ai/api/v1"+ )+ # Lookalike names must not be swept in.+ assert envelope_tool_part_cache_markers_supported(+ "custom:notlitellm", "https://notlitellm.example.com/v1"+ )++ def test_tool_message_not_marked_when_part_markers_off(self):+ decorated = apply_anthropic_cache_control(+ copy.deepcopy(_tool_history()),+ native_anthropic=False,+ tool_part_markers=False,+ )+ for tool_msg in _tool_messages(decorated):+ assert "cache_control" not in tool_msg+ assert not _has_part_marker(tool_msg)+ # Content must stay a plain string — no decoration-produced+ # part list that LiteLLM would forward into tool_result.content.+ assert isinstance(tool_msg.get("content"), str)++ def test_breakpoint_reallocates_to_non_tool_message(self):+ decorated = apply_anthropic_cache_control(+ copy.deepcopy(_tool_history()),+ native_anthropic=False,+ tool_part_markers=False,+ )+ non_tool_marked = [+ m+ for m in decorated+ if m.get("role") != "tool"+ and ("cache_control" in m or _has_part_marker(m))+ ]+ assert non_tool_marked, "budget must reallocate, not vanish"++ def test_openrouter_default_keeps_tool_part_marker(self):+ decorated = apply_anthropic_cache_control(+ copy.deepcopy(_tool_history()), native_anthropic=False+ )+ assert any(_has_part_marker(m) for m in _tool_messages(decorated))++ def test_build_prompt_cache_plan_threads_flag(self):+ plan = build_prompt_cache_plan(+ _tool_history(),+ [],+ native_anthropic=False,+ tool_part_markers=False,+ )+ for tool_msg in _tool_messages(plan.messages):+ assert "cache_control" not in tool_msg+ assert not _has_part_marker(tool_msg)++ def test_native_anthropic_layout_unaffected(self):+ # Native layout relies on the adapter to relocate a top-level marker+ # onto the tool_result block; the flag must not interfere.+ decorated = apply_anthropic_cache_control(+ copy.deepcopy(_tool_history()),+ native_anthropic=True,+ tool_part_markers=False,+ )+ assert any(+ "cache_control" in m for m in _tool_messages(decorated)+ )