The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(prompt-caching): background one-shot calls no longer pay a cache write nobody reads
Tekniumfbcadb9508c0
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 52bae54ddf6..91fb9c47c37 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -4007,13 +4007,13 @@ def _fallback_destination(def _replan_synchronous_cache_sections(messages: list, tools: Optional[list], *, destination: _FallbackDestination) -> tuple[list, list]:- """Strip source decoration and plan one synchronous destination locally."""+ """Plan one destination at the configured TTL (1h must not regress to 5m); one-shots never cache."""from agent.agent_runtime_helpers import configured_cache_ttl, plan_cache_sections_for_destination+ from agent.prompt_caching import is_one_shot_requestreturn plan_cache_sections_for_destination(messages, tools, provider=destination.provider, base_url=destination.base_url,- api_mode=destination.api_mode or "", model=destination.model or "",- # Operator's configured TTL so fallbacks don't regress 1h → 5m default (no live agent here; read config).- cache_ttl=configured_cache_ttl(),+ api_mode=destination.api_mode or "", model=destination.model or "", cache_ttl=configured_cache_ttl(),+ cache_disabled=True if is_one_shot_request(messages, tools) else None,)diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.pyindex 6e92773da0c..44c118755e2 100644--- a/agent/bedrock_adapter.py+++ b/agent/bedrock_adapter.py@@ -1235,7 +1235,7 @@ def build_converse_kwargs(model: str, messages: list[dict], tools: Optional[list[dict]] = None, max_tokens: Optional[int] = 4096,temperature: Optional[float] = None, top_p: Optional[float] = None,stop_sequences: Optional[list[str]] = None, guardrail_config: Optional[dict] = None,- reasoning_config: Optional[dict] = None,+ reasoning_config: Optional[dict] = None, prompt_cache: bool = True,) -> dict[str, Any]:"""Build kwargs for ``bedrock-runtime.converse()`` / ``converse_stream()``. ``max_tokens=None`` omits``maxTokens`` (model maximum; default stays 4096). cachePoint markers go on system, tools and the@@ -1243,7 +1243,7 @@ def build_converse_kwargs(model supports caching and Bedrock has not rejected that placement. ``reasoning_config`` becomes themodel's ``additionalModelRequestFields`` reasoning switch (Claude ``thinking``, Nova 2 ``reasoningConfig``)."""system_prompt, converse_messages = convert_messages_to_converse(messages, model=model)- cache_at = {p for p in CACHE_POINT_PLACEMENTS if cache_point_allowed(model, p)} if _model_supports_prompt_cache(model) else set()+ cache_at = {p for p in CACHE_POINT_PLACEMENTS if cache_point_allowed(model, p)} if prompt_cache and _model_supports_prompt_cache(model) else set()inference_config: dict[str, Any] = {} if max_tokens is None else {"maxTokens": max_tokens}kwargs: dict[str, Any] = {"modelId": model, "messages": converse_messages, "inferenceConfig": inference_config}if system_prompt:@@ -1282,8 +1282,11 @@ def call_converse() -> SimpleNamespace:"""Non-streaming Converse call → OpenAI-compatible response. Retries once without a rejected cachePointplacement; evicts the cached client on stale-connection errors."""+ from agent.prompt_caching import is_one_shot_requestclient = _get_bedrock_runtime_client(region)- kwargs = build_converse_kwargs(model, messages, tools, max_tokens, temperature, top_p, stop_sequences, guardrail_config)+ # Auxiliary-only entry point: a one-shot's cachePoint is a write no later call reads.+ kwargs = build_converse_kwargs(model, messages, tools, max_tokens, temperature, top_p, stop_sequences, guardrail_config,+ prompt_cache=not is_one_shot_request(messages, tools))try:response = client.converse(**kwargs)except Exception as exc:diff --git a/agent/moa_loop.py b/agent/moa_loop.pyindex 5a03be692f5..8c736abf684 100644--- a/agent/moa_loop.py+++ b/agent/moa_loop.py@@ -946,18 +946,14 @@ def aggregate_moa_context(agg_label = _slot_label(aggregator)agg_runtime = _slot_runtime(aggregator)- cache_disabled, cache_ttl = _agent_cache_opts(agent)_touch_fanout_progress(agent, f"MoA: synthesizing aggregator guidance ({agg_label})")try:- # Same cache_control decoration as the advisor calls; this synthesis call is- # a third independent MoA call path that otherwise re-bills its full input.- agg_messages = _maybe_apply_moa_cache_control(- [{"role": "user", "content": synth_prompt}], _with_cache_disabled(agg_runtime, cache_disabled), cache_ttl=cache_ttl,- )+ # Undecorated: the prompt embeds this call's reference outputs, so no later call+ # reads it back and a marker would only pay a cache write (is_one_shot_request).synthesis = _extract_text(call_llm(- task="moa_aggregator", messages=agg_messages, temperature=aggregator_temperature,+ task="moa_aggregator", messages=[{"role": "user", "content": synth_prompt}], temperature=aggregator_temperature,reasoning_config=_aggregator_reasoning_config(aggregator), **agg_runtime,))except Exception as exc:diff --git a/agent/prompt_caching.py b/agent/prompt_caching.pyindex f479646f5f3..79449517bf2 100644--- a/agent/prompt_caching.py+++ b/agent/prompt_caching.py@@ -32,6 +32,16 @@ def envelope_tool_part_cache_markers_supported(provider: str | None, base_url: sreturn not _is_litellm_route((provider or "").strip().lower(), base_url or "")+def is_one_shot_request(messages: list[dict[str, Any]] | None, tools: list[dict[str, Any]] | None) -> bool:+ """True for a request no later call can read back from cache: no tools, no assistant/tool+ turns, at most one user turn (compression summaries, titles, MoA synthesis). A marker there+ only buys a cache write (1.25x input at 5m, 2x at 1h) that nothing ever reads."""+ if tools:+ return False+ roles = [m.get("role") for m in messages or [] if isinstance(m, dict)]+ return roles.count("user") <= 1 and not any(r in ("assistant", "tool") for r in roles)++def _text_part(text: str, cache_marker: dict | None = None) -> dict:part: dict = {"type": "text", "text": text}if cache_marker is not None:diff --git a/tests/agent/test_bedrock_adapter.py b/tests/agent/test_bedrock_adapter.pyindex 67d7aac959f..c88dd4abb12 100644--- a/tests/agent/test_bedrock_adapter.py+++ b/tests/agent/test_bedrock_adapter.py@@ -851,6 +851,20 @@ class TestCachePointRejectionRecovery:assert CACHE_POINT in first.kwargs["toolConfig"]["tools"]assert CACHE_POINT not in second.kwargs["toolConfig"]["tools"]+ def test_call_converse_one_shot_carries_no_cache_point(self):+ """call_converse is the auxiliary entry point: a system + single-user request with no+ tools is never read back, so no section may carry a cachePoint (a pure cache write)."""+ from agent.bedrock_adapter import call_converse+ client = MagicMock()+ client.converse.return_value = {+ "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},+ "stopReason": "end_turn", "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2}}+ with patch("agent.bedrock_adapter._get_bedrock_runtime_client", return_value=client):+ call_converse(region="us-east-1", model="us.anthropic.claude-sonnet-4-6",+ messages=[{"role": "system", "content": "Summarize."},+ {"role": "user", "content": "TRANSCRIPT"}])+ assert "cachePoint" not in repr(client.converse.call_args.kwargs)+def test_call_converse_reraises_unrelated_errors(self):from agent.bedrock_adapter import call_converseclient = MagicMock()diff --git a/tests/agent/test_moa_aggregator_cache_control.py b/tests/agent/test_moa_aggregator_cache_control.pyindex 544a7390ff9..5bea73b4e3f 100644--- a/tests/agent/test_moa_aggregator_cache_control.py+++ b/tests/agent/test_moa_aggregator_cache_control.py@@ -1,16 +1,7 @@-"""Regression test: the MoA aggregator's one-shot synthesis call-(``aggregate_moa_context``, used by the ``/moa <prompt>`` command) must get-the same Anthropic-style prompt-caching decoration as the acting-aggregator-turn (``MoAChatCompletions.create``) and the advisor fan-out-(``_run_reference``).--22c5048d9 ("fix(moa): restore prompt caching for the aggregator and-advisors") fixed the other two MoA call paths but never touched-``aggregate_moa_context`` — a third, independent call path with its own-``call_llm(task="moa_aggregator", ...)`` invocation. Without this fix, every-``/moa <prompt>`` one-shot call re-bills its full input (system-less prompt-containing all joined reference outputs) with zero cache_control breakpoints,-even when the resolved aggregator slot is a cache-honoring route.+"""MoA aggregator cache decoration: the acting aggregator (``MoAChatCompletions``)+and advisor fan-out are re-read across iterations and stay decorated; the one-shot+``/moa <prompt>`` synthesis (``aggregate_moa_context``) embeds this call's reference+outputs, is never read back, and stays undecorated (no cache write)."""from __future__ import annotations@@ -47,11 +38,12 @@ def _aggregator_kwargs(calls):return next(c for c in calls if c.get("task") == "moa_aggregator")-def test_aggregator_synthesis_gets_cache_control_on_native_anthropic_route(+def test_aggregator_synthesis_unmarked_on_native_anthropic_route(captured_calls, monkeypatch):- """A cache-honoring aggregator slot (native Anthropic) must get- cache_control breakpoints on its synthesis call."""+ """The synthesis prompt embeds this call's reference outputs, so no later call reads+ it back: even on a cache-honoring slot it carries no cache_control (a marker would+ only pay a cache write)."""from agent import moa_loopmonkeypatch.setattr(@@ -72,17 +64,9 @@ def test_aggregator_synthesis_gets_cache_control_on_native_anthropic_route(aggregator={"provider": "anthropic", "model": "claude-opus-4.8"},)- agg_kwargs = _aggregator_kwargs(captured_calls)- synth_message = agg_kwargs["messages"][0]+ synth_message = _aggregator_kwargs(captured_calls)["messages"][0]assert synth_message["role"] == "user"- content = synth_message["content"]- # Native Anthropic layout places cache_control on inner content blocks,- # so a cached message's content is a list of blocks rather than a bare- # string once decorated.- assert isinstance(content, list), "expected native cache_control block layout"- assert any(- isinstance(block, dict) and "cache_control" in block for block in content- ), "aggregator synthesis message must carry a cache_control breakpoint"+ assert "cache_control" not in repr(synth_message)def test_aggregator_synthesis_untouched_on_non_caching_route(diff --git a/tests/agent/test_prompt_cache_ttl_propagation.py b/tests/agent/test_prompt_cache_ttl_propagation.pyindex 66a871e85ae..c64c45fdc51 100644--- a/tests/agent/test_prompt_cache_ttl_propagation.py+++ b/tests/agent/test_prompt_cache_ttl_propagation.py@@ -213,9 +213,12 @@ class TestAuxFallbackReplanThreadsTtl:"anthropic_messages","claude-opus-4.8",)+ # Multi-turn: a later call can read this prefix back, so it stays cacheable.messages = [{"role": "system", "content": "You are helpful."},{"role": "user", "content": "hello"},+ {"role": "assistant", "content": "hi"},+ {"role": "user", "content": "next"},]out_msgs, _ = auxiliary_client._replan_synchronous_cache_sections(messages, None, destination=destination@@ -225,3 +228,27 @@ class TestAuxFallbackReplanThreadsTtl:assert all(m.get("ttl") == "1h" for m in markers), ("the configured 1h tier must reach auxiliary fallback replans")++ def test_replan_leaves_one_shot_unmarked_on_caching_route(self, monkeypatch):+ """system + one user turn, no tools: nothing reads the prefix back, so a marker+ would only pay a cache write (2x input at 1h)."""+ from agent import auxiliary_client++ monkeypatch.setattr(+ "hermes_cli.config.load_config_readonly",+ lambda: {"prompt_caching": {"cache_ttl": "1h"}},+ )+ messages = [+ {"role": "system", "content": "Summarize the transcript."},+ {"role": "user", "content": "TRANSCRIPT"},+ ]+ for destination in (+ auxiliary_client._FallbackDestination(+ "anthropic", "https://api.anthropic.com", "anthropic_messages", "claude-opus-4.8"),+ auxiliary_client._FallbackDestination(+ "openrouter", "https://openrouter.ai/api/v1", "chat_completions", "anthropic/claude-opus-4.8"),+ ):+ out_msgs, _ = auxiliary_client._replan_synchronous_cache_sections(+ messages, None, destination=destination+ )+ assert _collect_cache_controls(out_msgs) == [], destination.provider