Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llm-gateway): skip bedrock-runtime CountTokens for CRIS-only models (#70515)

Chris Volzer5a97a5cbcbf6
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.py
index 1337c20e462c..84c8a0b88bfb 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -25,6 +25,7 @@ from llm_gateway.bedrock import (
count_tokens_with_bedrock_mantle,
ensure_bedrock_configured,
map_to_bedrock_model,
+ supports_bedrock_runtime_count_tokens,
)
from llm_gateway.circuit_breaker import AnthropicCircuitBreaker
from llm_gateway.cloudflare import (
@@ -779,30 +780,36 @@ async def _bedrock_count_tokens_impl(
status_code = "200"
try:
- input_tokens = await count_tokens_with_bedrock(
- data,
- bedrock_model,
- bedrock_region_name,
- settings.request_timeout,
- product=product,
- )
- return {"input_tokens": input_tokens}
- except Exception as e:
- # bedrock-runtime CountTokens doesn't support every Claude model (cross-Region-inference-only
- # models like claude-opus-4-8 return a ValidationException). AWS's recommended path for those
- # is Anthropic's count_tokens API on the bedrock-mantle endpoint — try it before giving up.
- logger.exception(
- "Bedrock CountTokens failed",
- model=bedrock_model,
- product=product,
- **_bedrock_runtime_exception_log_fields(e),
- )
- BEDROCK_COUNT_TOKENS_ERRORS.labels(
- transport="runtime",
- error_type=type(e).__name__,
- product=product,
- ).inc()
- logger.info("Attempting bedrock-mantle count_tokens fallback", model=bedrock_model, product=product)
+ # bedrock-runtime CountTokens rejects some models outright ("The provided model doesn't
+ # support counting tokens."); for those, skip the doomed runtime call and go straight to
+ # AWS's recommended path — Anthropic's count_tokens API on the bedrock-mantle endpoint.
+ runtime_exception: Exception | None = None
+ if supports_bedrock_runtime_count_tokens(bedrock_model):
+ try:
+ input_tokens = await count_tokens_with_bedrock(
+ data,
+ bedrock_model,
+ bedrock_region_name,
+ settings.request_timeout,
+ product=product,
+ )
+ return {"input_tokens": input_tokens}
+ except Exception as e:
+ # Unexpected runtime failure — try the mantle endpoint before giving up.
+ runtime_exception = e
+ logger.exception(
+ "Bedrock CountTokens failed",
+ model=bedrock_model,
+ product=product,
+ **_bedrock_runtime_exception_log_fields(e),
+ )
+ BEDROCK_COUNT_TOKENS_ERRORS.labels(
+ transport="runtime",
+ error_type=type(e).__name__,
+ product=product,
+ ).inc()
+ logger.info("Attempting bedrock-mantle count_tokens fallback", model=bedrock_model, product=product)
+
try:
input_tokens = await count_tokens_with_bedrock_mantle(
data,
@@ -815,12 +822,15 @@ async def _bedrock_count_tokens_impl(
except Exception as mantle_exc:
status_code = "502"
error_type_name = type(mantle_exc).__name__
+ runtime_log_fields = (
+ _bedrock_runtime_exception_log_fields(runtime_exception) if runtime_exception is not None else {}
+ )
logger.exception(
"Error proxying bedrock-mantle count_tokens request",
model=bedrock_model,
product=product,
**_exception_log_fields(mantle_exc, prefix="mantle"),
- **_bedrock_runtime_exception_log_fields(e),
+ **runtime_log_fields,
)
BEDROCK_COUNT_TOKENS_ERRORS.labels(
transport="mantle",
diff --git a/services/llm-gateway/src/llm_gateway/bedrock.py b/services/llm-gateway/src/llm_gateway/bedrock.py
index 4dbf0d7ec98d..ae774ff94f16 100644
--- a/services/llm-gateway/src/llm_gateway/bedrock.py
+++ b/services/llm-gateway/src/llm_gateway/bedrock.py
@@ -336,6 +336,25 @@ def _strip_regional_inference_prefix(model: str) -> str:
return model.replace("us.anthropic.", "anthropic.").replace("eu.anthropic.", "anthropic.")
+# Models bedrock-runtime CountTokens rejects outright with "The provided model doesn't support
+# counting tokens." — verified against production traffic, not inferred from the id shape: the
+# CRIS-only claude-sonnet-4-6 has no dated foundation-model id yet counts fine on runtime (its
+# only failures are request-content validation errors like oversized prompts). Models not listed
+# here keep the try-runtime-first behavior and fall back to mantle if AWS rejects them; re-verify
+# against the live CountTokens API before adding an entry.
+BEDROCK_RUNTIME_COUNT_TOKENS_UNSUPPORTED: Final[frozenset[str]] = frozenset(
+ {
+ "anthropic.claude-opus-4-8",
+ "anthropic.claude-fable-5",
+ }
+)
+
+
+def supports_bedrock_runtime_count_tokens(model: str) -> bool:
+ """Whether the bedrock-runtime CountTokens API can count tokens for this model."""
+ return _strip_regional_inference_prefix(model) not in BEDROCK_RUNTIME_COUNT_TOKENS_UNSUPPORTED
+
+
def get_bedrock_mantle_count_tokens_url(region_name: str) -> str:
return f"https://bedrock-mantle.{region_name}.api.aws/anthropic/v1/messages/count_tokens"
diff --git a/services/llm-gateway/tests/test_bedrock.py b/services/llm-gateway/tests/test_bedrock.py
index f89e372d0ffe..0468d6ed07d7 100644
--- a/services/llm-gateway/tests/test_bedrock.py
+++ b/services/llm-gateway/tests/test_bedrock.py
@@ -7,6 +7,7 @@ from botocore.exceptions import ClientError
from fastapi import HTTPException
from fastapi.testclient import TestClient
+from llm_gateway.bedrock import supports_bedrock_runtime_count_tokens
from llm_gateway.metrics.prometheus import BEDROCK_COUNT_TOKENS_DROPPED_PROPERTIES, BEDROCK_COUNT_TOKENS_ERRORS
BEDROCK_SETTINGS_PATCH = patch(
@@ -491,7 +492,7 @@ class TestBedrockCountTokensViaProvider:
@patch("llm_gateway.api.anthropic.get_settings")
@patch("llm_gateway.api.anthropic.count_tokens_with_bedrock_mantle", new_callable=AsyncMock)
@patch("llm_gateway.api.anthropic.count_tokens_with_bedrock")
- def test_falls_back_to_mantle_when_runtime_unsupported(
+ def test_falls_back_to_mantle_when_runtime_fails(
self,
mock_count_tokens: MagicMock,
mock_mantle_count_tokens: AsyncMock,
@@ -505,12 +506,13 @@ class TestBedrockCountTokensViaProvider:
mock_settings.request_timeout = 300.0
mock_get_settings.return_value = mock_settings
- # Mirrors bedrock-runtime rejecting CountTokens for a CRIS-only model like claude-opus-4-8.
+ # Mirrors bedrock-runtime rejecting the request contents (e.g. an oversized prompt) for a
+ # model whose CountTokens support is otherwise fine — the mantle fallback still runs.
mock_count_tokens.side_effect = ClientError(
{
"Error": {
"Code": "ValidationException",
- "Message": "The provided model doesn't support counting tokens.",
+ "Message": "prompt is too long: 290010 tokens > 200000 maximum",
},
"ResponseMetadata": {
"HTTPHeaders": {},
@@ -557,7 +559,7 @@ class TestBedrockCountTokensViaProvider:
product="llm_gateway",
runtime_status=400,
runtime_error_type="ClientError",
- runtime_error_message="The provided model doesn't support counting tokens.",
+ runtime_error_message="prompt is too long: 290010 tokens > 200000 maximum",
runtime_error_code="ValidationException",
)
mock_logger.info.assert_any_call(
@@ -566,6 +568,81 @@ class TestBedrockCountTokensViaProvider:
product="llm_gateway",
)
+ @pytest.mark.parametrize(
+ "model,expected_mantle_model",
+ [
+ pytest.param("claude-opus-4-8", "us.anthropic.claude-opus-4-8", id="opus_4_8"),
+ pytest.param("claude-fable-5", "us.anthropic.claude-fable-5", id="fable_5"),
+ ],
+ )
+ @patch("llm_gateway.api.anthropic.get_settings")
+ @patch("llm_gateway.api.anthropic.count_tokens_with_bedrock_mantle", new_callable=AsyncMock)
+ @patch("llm_gateway.api.anthropic.count_tokens_with_bedrock")
+ def test_cris_only_models_skip_runtime_and_count_via_mantle(
+ self,
+ mock_count_tokens: MagicMock,
+ mock_mantle_count_tokens: AsyncMock,
+ mock_get_settings: MagicMock,
+ authenticated_client: TestClient,
+ valid_request_headers: dict[str, str],
+ model: str,
+ expected_mantle_model: str,
+ ) -> None:
+ mock_settings = MagicMock()
+ mock_settings.bedrock_region_name = "us-east-1"
+ mock_settings.request_timeout = 300.0
+ mock_get_settings.return_value = mock_settings
+
+ mock_mantle_count_tokens.return_value = 55
+
+ response = authenticated_client.post(
+ "/v1/messages/count_tokens",
+ json={"model": model, "messages": [{"role": "user", "content": "Hello"}]},
+ headers=valid_request_headers,
+ )
+
+ assert response.status_code == 200
+ assert response.json()["input_tokens"] == 55
+ # The runtime CountTokens API always rejects CRIS-only models, so it must not be tried.
+ mock_count_tokens.assert_not_called()
+ assert mock_mantle_count_tokens.await_count == 1
+ mantle_count_tokens_call = mock_mantle_count_tokens.await_args
+ assert mantle_count_tokens_call is not None
+ assert mantle_count_tokens_call.args[1] == expected_mantle_model
+
+ @patch("llm_gateway.api.anthropic.get_settings")
+ @patch("llm_gateway.api.anthropic.count_tokens_with_bedrock_mantle", new_callable=AsyncMock)
+ @patch("llm_gateway.api.anthropic.count_tokens_with_bedrock")
+ def test_returns_502_when_mantle_fails_for_cris_only_model(
+ self,
+ mock_count_tokens: MagicMock,
+ mock_mantle_count_tokens: AsyncMock,
+ mock_get_settings: MagicMock,
+ authenticated_client: TestClient,
+ valid_request_headers: dict[str, str],
+ ) -> None:
+ mock_settings = MagicMock()
+ mock_settings.bedrock_region_name = "us-east-1"
+ mock_settings.request_timeout = 300.0
+ mock_get_settings.return_value = mock_settings
+
+ mock_mantle_count_tokens.side_effect = HTTPException(
+ status_code=400,
+ detail={
+ "error": {"message": "data retention mode 'default' is not available", "type": "invalid_request_error"}
+ },
+ )
+
+ response = authenticated_client.post(
+ "/v1/messages/count_tokens",
+ json={"model": "claude-fable-5", "messages": [{"role": "user", "content": "Hello"}]},
+ headers=valid_request_headers,
+ )
+
+ assert response.status_code == 502
+ assert "Failed to count tokens via Bedrock" in response.json()["error"]["message"]
+ mock_count_tokens.assert_not_called()
+
@patch("llm_gateway.api.anthropic.get_settings")
@patch("llm_gateway.api.anthropic.count_tokens_with_bedrock")
def test_product_route_supported(
@@ -826,6 +903,23 @@ class TestModelMapping:
assert "Invalid product" in response.json()["detail"]
+class TestSupportsBedrockRuntimeCountTokens:
+ @pytest.mark.parametrize(
+ "model,expected",
+ [
+ pytest.param("us.anthropic.claude-sonnet-4-5-20250929-v1:0", True, id="dated_foundation_model"),
+ # CRIS-only but supported — support is per-model, not derivable from the id shape.
+ pytest.param("us.anthropic.claude-sonnet-4-6", True, id="cris_only_but_supported"),
+ pytest.param("us.anthropic.claude-opus-4-6-v1", True, id="not_denylisted_versioned_suffix"),
+ pytest.param("us.anthropic.claude-opus-4-8", False, id="unsupported_opus"),
+ pytest.param("eu.anthropic.claude-opus-4-8", False, id="unsupported_opus_eu_prefix"),
+ pytest.param("us.anthropic.claude-fable-5", False, id="unsupported_fable"),
+ ],
+ )
+ def test_classifies_bedrock_model_ids(self, model: str, expected: bool) -> None:
+ assert supports_bedrock_runtime_count_tokens(model) is expected
+
+
class TestBedrockMantleCountTokens:
"""Unit tests for the bedrock-mantle count_tokens fallback transport."""