Skip to content

The agent that grows with you

fix(agent): honor prompt_caching for custom providers

Blood Shot0a3b7efec55c
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 1055cfba36e..861c4d23252 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2302,29 +2302,67 @@ def anthropic_prompt_cache_policy(
and (eff_provider == "anthropic" or base_url_hostname(eff_base_url) == "api.anthropic.com")
)
- # A custom Anthropic-compatible route may use a bare model alias that is
- # canonicalized only after Hermes sends the request. In that case model
- # spelling cannot prove cache support. Honor an exact route+model
- # capability declaration instead; explicit false is authoritative too.
- # This preserves the runtime model id (and therefore request/cache keys)
- # while avoiding unsafe alias-name guesses.
+ # A configured route may use an arbitrary provider name and model alias
+ # that are canonicalized only after Hermes sends the request. Honor its
+ # existing per-model ``prompt_caching`` capability instead of guessing
+ # support from either spelling. Explicit false is authoritative too.
#
- # Also consulted for a LiteLLM route on the OpenAI wire: that grant is
- # inferred from the provider/host name, so an operator who explicitly
- # declares prompt_caching for the route+model must still win over the
- # inference — in either direction. Narrowed to the routes the LiteLLM
- # branch below can actually grant (chat_completions + Claude): the lookup
- # calls get_compatible_custom_providers, which rebuilds its normalized
- # view on every call (~1.5ms uncached), and this function runs per
- # request destination. Widening it unconditionally regressed the
- # non-declaring common case ~200x (7.5us -> 1528us).
+ # The declaration only controls the two transports handled by this marker
+ # planner. Responses and Bedrock use separate caching protocols and must
+ # not receive Anthropic-style cache_control fields.
custom_prompt_caching = None
+ _supports_anthropic_cache_markers = eff_api_mode in {
+ "anthropic_messages",
+ "chat_completions",
+ }
_litellm_openai_wire = (
eff_api_mode == "chat_completions"
and is_claude
and _is_litellm_route(provider_lower, eff_base_url)
)
- if is_anthropic_wire or _litellm_openai_wire:
+ _custom_providers = getattr(agent, "_custom_providers", None)
+ _route_may_be_custom = False
+ if _custom_providers:
+ # The normalized list is already attached after agent initialization.
+ # Use cheap runtime identity signals before calling the capability
+ # helper so an unrelated configured provider does not put every
+ # built-in chat-completions request on the route-normalization path.
+ _provider_ids = {provider_lower}
+ if provider_lower.startswith("custom:"):
+ _provider_ids.add(provider_lower.removeprefix("custom:"))
+ for _entry in _custom_providers:
+ if not isinstance(_entry, dict):
+ continue
+ _entry_ids = {
+ str(_entry.get("name") or "").strip().lower(),
+ str(_entry.get("provider_key") or "").strip().lower(),
+ }
+ if _provider_ids & (_entry_ids - {""}) or (
+ eff_base_url
+ and str(_entry.get("base_url") or "") == eff_base_url
+ ):
+ _route_may_be_custom = True
+ break
+ elif _custom_providers is None:
+ # During early agent initialization the normalized custom-provider list
+ # is not attached yet. Avoid rebuilding it for ordinary built-in routes,
+ # while still recognizing arbitrary config keys and built-in-name
+ # overrides that point at a different endpoint.
+ try:
+ from hermes_cli.providers import get_provider
+
+ _provider_def = get_provider(eff_provider)
+ _route_may_be_custom = _provider_def is None or (
+ bool(_provider_def.base_url)
+ and base_url_hostname(_provider_def.base_url)
+ != base_url_hostname(eff_base_url)
+ )
+ except Exception:
+ _route_may_be_custom = provider_lower.startswith("custom:")
+
+ if _supports_anthropic_cache_markers and (
+ is_anthropic_wire or _litellm_openai_wire or _route_may_be_custom
+ ):
try:
from hermes_cli.config import get_custom_provider_model_capability
@@ -2332,7 +2370,7 @@ def anthropic_prompt_cache_policy(
model=eff_model,
base_url=eff_base_url,
capability="prompt_caching",
- custom_providers=getattr(agent, "_custom_providers", None),
+ custom_providers=_custom_providers,
)
except Exception as _cap_exc:
logger.debug(
@@ -2340,10 +2378,9 @@ def anthropic_prompt_cache_policy(
_cap_exc,
)
if custom_prompt_caching is not None:
- # Layout follows the transport, not the declaration: the native
- # inner-block form is only honored on the Anthropic Messages wire
- # (see the LiteLLM OpenAI-wire branch below for why a top-level
- # marker is dropped or 400s on chat_completions).
+ # Layout follows the transport, not the declaration: native Messages
+ # uses inner-block markers; OpenAI-compatible chat uses the envelope
+ # layout already emitted for OpenRouter and LiteLLM.
return custom_prompt_caching, custom_prompt_caching and is_anthropic_wire
# MiniMax-M3 rides MiniMax's server-side automatic prefix cache on the
diff --git a/tests/run_agent/test_anthropic_prompt_cache_policy.py b/tests/run_agent/test_anthropic_prompt_cache_policy.py
index 4128aeff7bf..0e4e1668a4f 100644
--- a/tests/run_agent/test_anthropic_prompt_cache_policy.py
+++ b/tests/run_agent/test_anthropic_prompt_cache_policy.py
@@ -294,6 +294,99 @@ class TestThirdPartyAnthropicGateway:
assert agent._anthropic_prompt_cache_policy() == (False, False)
+class TestCustomProviderOpenAIWireCapability:
+ """Explicit model capability works without provider, host, or family guesses."""
+
+ @staticmethod
+ def _configured_agent(*, enabled: bool, api_mode: str = "chat_completions"):
+ agent = _make_agent(
+ provider="custom:edge-router",
+ base_url="https://models.example.net/v1",
+ api_mode=api_mode,
+ model="vendor-agnostic-model",
+ )
+ agent._custom_providers = [
+ {
+ "name": "edge-router",
+ "base_url": "https://models.example.net/v1",
+ "models": {
+ "vendor-agnostic-model": {"prompt_caching": enabled},
+ },
+ }
+ ]
+ return agent
+
+ def test_explicit_true_enables_envelope_layout_on_chat_completions(self):
+ agent = self._configured_agent(enabled=True)
+
+ assert agent._anthropic_prompt_cache_policy() == (True, False)
+
+ def test_explicit_false_disables_markers_on_chat_completions(self):
+ agent = self._configured_agent(enabled=False)
+
+ assert agent._anthropic_prompt_cache_policy() == (False, False)
+
+ def test_undeclared_chat_completions_route_stays_conservative(self):
+ agent = self._configured_agent(enabled=True)
+ agent._custom_providers[0]["models"]["vendor-agnostic-model"] = {
+ "context_length": 131072,
+ }
+
+ assert agent._anthropic_prompt_cache_policy() == (False, False)
+
+ def test_unrelated_custom_route_skips_capability_lookup(self, monkeypatch):
+ agent = self._configured_agent(enabled=True)
+ agent.provider = "openrouter"
+ agent.base_url = "https://openrouter.ai/api/v1"
+ agent.model = "openai/gpt-5.4"
+
+ def unexpected_lookup(**_kwargs):
+ pytest.fail("unrelated built-in route performed custom capability lookup")
+
+ monkeypatch.setattr(
+ "hermes_cli.config.get_custom_provider_model_capability",
+ unexpected_lookup,
+ )
+
+ assert agent._anthropic_prompt_cache_policy() == (False, False)
+
+ @pytest.mark.parametrize("api_mode", ["codex_responses", "bedrock_converse"])
+ def test_explicit_true_does_not_cross_into_other_wire_protocols(self, api_mode):
+ agent = self._configured_agent(enabled=True, api_mode=api_mode)
+
+ assert agent._anthropic_prompt_cache_policy() == (False, False)
+
+ def test_modern_providers_yaml_is_honored_during_early_init(
+ self, tmp_path, monkeypatch
+ ):
+ import textwrap
+
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "config.yaml").write_text(
+ textwrap.dedent(
+ """
+ providers:
+ edge-router:
+ api: https://models.example.net/v1
+ transport: openai_chat
+ models:
+ vendor-agnostic-model:
+ prompt_caching: true
+ """
+ )
+ )
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ agent = _make_agent(
+ provider="edge-router",
+ base_url="https://models.example.net/v1",
+ api_mode="chat_completions",
+ model="vendor-agnostic-model",
+ )
+
+ assert agent._anthropic_prompt_cache_policy() == (True, False)
+
+
class TestMiniMaxAnthropicWire:
"""MiniMax's own model family on its Anthropic-compatible endpoint.
diff --git a/website/docs/user-guide/configuring-models.md b/website/docs/user-guide/configuring-models.md
index 422cdc57a3b..2ede0dba3ce 100644
--- a/website/docs/user-guide/configuring-models.md
+++ b/website/docs/user-guide/configuring-models.md
@@ -197,15 +197,15 @@ providers:
With discovery off, the model picker (`hermes model`, `/model`) shows the configured list instead of a live probe.
-For an Anthropic-compatible gateway that resolves a bare model alias only
-after receiving the request, opt the alias into native prompt-cache markers
-with the per-model `prompt_caching` capability:
+For a gateway that resolves a bare model alias only after receiving the
+request, opt the alias into prompt-cache markers with the per-model
+`prompt_caching` capability:
```yaml
providers:
- anthropic-proxy:
- api: https://gateway.example.com/anthropic
- transport: anthropic_messages
+ model-proxy:
+ api: https://gateway.example.com/v1
+ transport: openai_chat # or anthropic_messages
models:
fable:
context_length: 1000000
@@ -213,9 +213,12 @@ providers:
```
Hermes matches this declaration to the exact provider route and runtime model
-id, without rewriting the alias. Set `prompt_caching: false` to explicitly
-disable cache markers for a model; when omitted, Hermes keeps its normal
-provider and model capability detection.
+id, without rewriting the alias or inferring support from its provider name,
+host, or model family. The marker layout follows the configured transport:
+`openai_chat` uses the OpenAI-compatible envelope layout and
+`anthropic_messages` uses the native inner-block layout. Set
+`prompt_caching: false` to explicitly disable cache markers for a model; when
+omitted, Hermes keeps its normal provider and model capability detection.
:::note Legacy format
Older configs used a top-level `custom_providers:` list (with `base_url` instead of `api`). It still works and is auto-migrated to the `providers:` dict on `hermes update` (config v12).