Skip to content

The agent that grows with you

fix(anthropic): use standard speed when an org has no fast-mode capacity

emozilla2108059c8a65
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 918b9fe2313..7563828d24f 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -2408,6 +2408,9 @@ def init_agent(
# Every (provider, model) that rejected image content this session. build_api_request strips
# images from requests to those models only, so history keeps them for any model that can see.
agent._image_rejecting_models = set()
+ # Models whose Anthropic organization answered a fast request with a fast-mode limit of 0;
+ # agent.fast_mode stops sending ``speed`` to them for the rest of the session.
+ agent._fast_mode_unavailable_models = set()
_init_prompt_cache_config(agent)
_init_turn_state(agent, run_budget_seconds)
diff --git a/agent/fast_mode.py b/agent/fast_mode.py
index 042c63abf5f..04a0498802c 100644
--- a/agent/fast_mode.py
+++ b/agent/fast_mode.py
@@ -5,7 +5,9 @@
window of ``agent.fast_auto_seconds``) or ``"cold"`` (only a session's first turn,
no prior history, opens it). The provider's fast override is layered onto request
kwargs only while the window is open; only per-request params (``service_tier`` /
-``speed``) vary, so the prompt cache survives the boundary.
+``speed``) vary, so the request body stays byte-identical. Anthropic keeps a separate
+prompt cache per speed, so each Anthropic window boundary re-writes the prefix at the
+new speed.
"""
from __future__ import annotations
@@ -15,6 +17,9 @@ from typing import Any
BOUNDED_MODES = frozenset({"auto", "cold"})
DEFAULT_WINDOW_SECONDS = 60
+# Documented fast-mode rate-limit headers; a limit of 0 means the organization has no fast
+# capacity for the model (https://platform.claude.com/docs/en/build-with-claude/fast-mode).
+_FAST_LIMIT_HEADERS = ("anthropic-fast-input-tokens-limit", "anthropic-fast-output-tokens-limit")
def begin_turn(agent: Any, conversation_history: Any) -> None:
@@ -36,15 +41,43 @@ def begin_turn(agent: Any, conversation_history: Any) -> None:
def effective_request_overrides(agent: Any) -> dict[str, Any]:
- """``agent.request_overrides`` plus the fast override while the window is open."""
+ """``agent.request_overrides`` plus the fast override while the window is open, minus
+ ``speed`` for a model this session learned has no fast capacity."""
overrides = dict(getattr(agent, "request_overrides", None) or {})
- if getattr(agent, "service_tier", None) not in BOUNDED_MODES or time.monotonic() >= getattr(agent, "_fast_until", 0.0):
- return overrides
- from hermes_cli.models import resolve_fast_mode_overrides
- base_url = getattr(agent, "base_url", None)
- if getattr(agent, "api_mode", None) == "anthropic_messages":
- base_url = getattr(agent, "_anthropic_base_url", None) or base_url
- overrides.update(
- resolve_fast_mode_overrides(getattr(agent, "model", None), provider=getattr(agent, "provider", None), base_url=base_url) or {}
- )
+ if getattr(agent, "service_tier", None) in BOUNDED_MODES and time.monotonic() < getattr(agent, "_fast_until", 0.0):
+ from hermes_cli.models import resolve_fast_mode_overrides
+ base_url = getattr(agent, "base_url", None)
+ if getattr(agent, "api_mode", None) == "anthropic_messages":
+ base_url = getattr(agent, "_anthropic_base_url", None) or base_url
+ overrides.update(
+ resolve_fast_mode_overrides(getattr(agent, "model", None), provider=getattr(agent, "provider", None), base_url=base_url) or {}
+ )
+ if "speed" in overrides and getattr(agent, "model", None) in (getattr(agent, "_fast_mode_unavailable_models", None) or ()):
+ overrides.pop("speed", None)
return overrides
+
+
+def fast_mode_unprovisioned(api_error: Any, api_kwargs: Any) -> bool:
+ """True for a 429 on a ``speed: "fast"`` request whose fast-mode limit header is 0. The
+ organization has no fast capacity for the model, so waiting or rotating keys cannot help."""
+ if getattr(api_error, "status_code", None) != 429 or not isinstance(api_kwargs, dict):
+ return False
+ if (api_kwargs.get("extra_body") or {}).get("speed") != "fast":
+ return False
+ headers = getattr(getattr(api_error, "response", None), "headers", None)
+ if headers is None:
+ return False
+ return any(str(headers.get(name, "")).strip() == "0" for name in _FAST_LIMIT_HEADERS)
+
+
+def mark_fast_mode_unavailable(agent: Any) -> bool:
+ """Stop sending ``speed`` for the current model for the rest of the session. False when the
+ model was already marked, so the caller retries at most once per model."""
+ model = getattr(agent, "model", None)
+ unavailable = getattr(agent, "_fast_mode_unavailable_models", None)
+ if not isinstance(unavailable, set):
+ unavailable = agent._fast_mode_unavailable_models = set()
+ if not model or model in unavailable:
+ return False
+ unavailable.add(model)
+ return True
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 4de90f26fdf..d757a745fd8 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -18,6 +18,7 @@ from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
from agent.conversation_compression import COMPRESSION_RETRY_CONTEXT_REDUCED_STATUS_TEMPLATE
+from agent.fast_mode import fast_mode_unprovisioned, mark_fast_mode_unavailable
from agent.model_metadata import is_output_cap_error, parse_available_output_tokens_from_error
from agent.retry_utils import is_zai_coding_overload_error, zai_coding_overload_retry_ceiling
from agent.error_classifier import FailoverReason, classify_api_error
@@ -236,7 +237,8 @@ def recover_before_classification(
api_kwargs: Any, active_system_prompt: Any,
) -> Tuple[bool, Any]:
"""Recovery branches that run BEFORE ``classify_api_error``: UnicodeEncodeError
- sanitization, provider image-content rejection (record the (provider, model);
+ sanitization, Anthropic fast mode with no capacity (drop ``speed`` for that model),
+ provider image-content rejection (record the (provider, model);
build_api_request strips images from that model's requests only), and the Bedrock
AnthropicBedrock SDK streaming fallback. Returns ``(retry_now, active_system_prompt)``;
the prompt may be ASCII-sanitized in place."""
@@ -247,6 +249,14 @@ def recover_before_classification(
if _recovered:
return True, active_system_prompt
+ # Anthropic fast mode with no capacity: a 429 whose fast-mode limit header is 0 can never
+ # succeed at fast speed, and it says nothing about the key's standard-speed limits. Stop
+ # sending ``speed`` to this model and retry now, before credential rotation benches the key.
+ if fast_mode_unprovisioned(api_error, api_kwargs) and mark_fast_mode_unavailable(agent):
+ _vlines(agent, f"⚠️ Fast mode isn't available for {agent.model} on this Anthropic organization — using standard speed for this session, retrying...")
+ logger.warning("%sFast mode: %s has a fast-mode limit of 0; standard speed for this session", agent.log_prefix, agent.model)
+ return True, active_system_prompt
+
# Some providers 4xx on image_url content: record the (provider, model) and retry;
# build_api_request strips images from that model's requests only. English phrase
# match; extend it.
diff --git a/tests/agent/test_fast_mode_auto.py b/tests/agent/test_fast_mode_auto.py
index 053bd587040..0d552eb3b46 100644
--- a/tests/agent/test_fast_mode_auto.py
+++ b/tests/agent/test_fast_mode_auto.py
@@ -141,3 +141,56 @@ def test_fast_auto_and_cold_parse_and_slash_command(monkeypatch):
route_stub.base_url = "https://openrouter.ai/api/v1"
route_stub.provider = "openrouter"
assert cli_mod.HermesCLI._resolve_turn_agent_config(route_stub, "hi")["request_overrides"] is None
+
+
+class _FastRateLimitError(Exception):
+ """A fast-mode 429 shaped like the live API's: documented limit headers, no retry-after."""
+
+ def __init__(self, limit="0"):
+ super().__init__("This request would exceed your organization's rate limit of 0 fast mode input tokens per minute.")
+ self.status_code = 429
+ self.body = {"type": "error", "error": {"type": "rate_limit_error", "message": str(self)}}
+ self.response = SimpleNamespace(headers={
+ "anthropic-fast-input-tokens-limit": limit, "anthropic-fast-output-tokens-limit": limit,
+ })
+
+
+_FAST_KWARGS = {"model": "claude-opus-5", "extra_body": {"speed": "fast"}}
+
+
+def test_unprovisioned_detects_only_zero_limit_fast_429s():
+ assert fast_mode.fast_mode_unprovisioned(_FastRateLimitError("0"), _FAST_KWARGS) is True
+ # A real limit that ran out is transient: the retry-after path handles it.
+ assert fast_mode.fast_mode_unprovisioned(_FastRateLimitError("2000000"), _FAST_KWARGS) is False
+ # The request has to have asked for fast speed.
+ assert fast_mode.fast_mode_unprovisioned(_FastRateLimitError("0"), {"model": "claude-opus-5"}) is False
+ assert fast_mode.fast_mode_unprovisioned(RuntimeError("boom"), _FAST_KWARGS) is False
+
+
+def test_unavailable_model_drops_speed_for_the_session_and_only_that_model():
+ agent = _agent(
+ service_tier="priority", model="claude-opus-5", provider="anthropic",
+ api_mode="anthropic_messages", request_overrides={"speed": "fast"},
+ )
+ assert fast_mode.effective_request_overrides(agent) == {"speed": "fast"}
+ assert fast_mode.mark_fast_mode_unavailable(agent) is True
+ assert fast_mode.mark_fast_mode_unavailable(agent) is False # one retry per model
+ assert fast_mode.effective_request_overrides(agent) == {}
+ agent.model = "claude-opus-5-5"
+ assert fast_mode.effective_request_overrides(agent) == {"speed": "fast"}
+
+
+def test_recovery_retries_at_standard_speed_before_classification():
+ from agent.turn_recovery import recover_before_classification
+
+ printed = []
+ agent = SimpleNamespace(
+ model="claude-opus-5", provider="anthropic", log_prefix="", _fast_mode_unavailable_models=set(),
+ _vprint=lambda *a, **k: printed.append(" ".join(str(x) for x in a)),
+ )
+ retry, prompt = recover_before_classification(
+ agent, _FastRateLimitError("0"), messages=[], api_messages=[], api_kwargs=_FAST_KWARGS, active_system_prompt="sys",
+ )
+ assert (retry, prompt) == (True, "sys")
+ assert agent._fast_mode_unavailable_models == {"claude-opus-5"}
+ assert any("standard speed" in line for line in printed)