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): bedrock-mantle count_tokens fallback + error logging (#64167)

Chris Volzerd8ef6c31c136
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.py
index 7c0a319ee746..1a621f1a0228 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -6,6 +6,7 @@ from typing import Any
import httpx
import litellm
import structlog
+from botocore.exceptions import ClientError
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import StreamingResponse
@@ -16,7 +17,12 @@ from llm_gateway.api.handler import (
handle_llm_request,
normalize_litellm_model_name,
)
-from llm_gateway.bedrock import count_tokens_with_bedrock, ensure_bedrock_configured, map_to_bedrock_model
+from llm_gateway.bedrock import (
+ count_tokens_with_bedrock,
+ count_tokens_with_bedrock_mantle,
+ ensure_bedrock_configured,
+ map_to_bedrock_model,
+)
from llm_gateway.circuit_breaker import AnthropicCircuitBreaker
from llm_gateway.config import get_settings
from llm_gateway.dependencies import AnthropicCircuitBreakerDep, RateLimitedUser
@@ -100,6 +106,55 @@ BEDROCK_SUPPORTED_PARAMS: frozenset[str] = frozenset(
)
+# Cap how much of a provider error message we copy into structured logs — provider 5xx bodies can be
+# multi-KB HTML error pages (e.g. Cloudflare 520s), and we only need enough to identify the failure.
+_MAX_LOGGED_ERROR_MESSAGE_CHARS = 2048
+
+
+def _exception_log_fields(exc: BaseException, *, prefix: str) -> dict[str, Any]:
+ """Pull the queryable bits out of an exception for structured logging.
+
+ `logger.exception` attaches the traceback via exc_info, but that text doesn't land in the
+ rendered JSON body — so the actual provider error (status + message) is invisible when grepping
+ logs. This surfaces it as explicit fields. For HTTPException we prefer the structured
+ `detail["error"]["message"]` (the real upstream message) over `str(exc)`.
+ """
+ status = getattr(exc, "status_code", None)
+ message = str(exc)
+ detail = getattr(exc, "detail", None)
+ if isinstance(detail, dict):
+ error = detail.get("error")
+ if isinstance(error, dict) and error.get("message"):
+ message = str(error["message"])
+ return {
+ f"{prefix}_status": status,
+ f"{prefix}_error_type": type(exc).__name__,
+ f"{prefix}_error_message": message[:_MAX_LOGGED_ERROR_MESSAGE_CHARS],
+ }
+
+
+def _bedrock_runtime_exception_log_fields(exc: BaseException) -> dict[str, Any]:
+ fields = _exception_log_fields(exc, prefix="runtime")
+ if not isinstance(exc, ClientError):
+ return fields
+
+ error = exc.response.get("Error", {})
+ metadata = exc.response.get("ResponseMetadata", {})
+ status = metadata.get("HTTPStatusCode")
+ if status is not None:
+ fields["runtime_status"] = status
+
+ error_code = error.get("Code")
+ if error_code:
+ fields["runtime_error_code"] = str(error_code)
+
+ message = error.get("Message")
+ if message:
+ fields["runtime_error_message"] = str(message)[:_MAX_LOGGED_ERROR_MESSAGE_CHARS]
+
+ return fields
+
+
def sanitize_for_bedrock(data: dict[str, Any], *, model: str, product: str) -> dict[str, Any]:
"""Adapt an Anthropic Messages request for the Bedrock path.
@@ -226,7 +281,7 @@ def _wrap_stream_with_breaker(
inner = response.body_iterator
- async def wrapped() -> AsyncIterator[bytes]:
+ async def wrapped() -> AsyncIterator[str | bytes | memoryview]:
success = True
try:
async for chunk in inner:
@@ -240,8 +295,12 @@ def _wrap_stream_with_breaker(
finally:
try:
await breaker.record_outcome(success=success)
- except Exception:
- logger.exception("circuit_breaker_stream_record_failed")
+ except Exception as exc:
+ logger.exception(
+ "circuit_breaker_stream_record_failed",
+ error_type=type(exc).__name__,
+ error_message=str(exc),
+ )
response.body_iterator = wrapped()
return response
@@ -296,9 +355,16 @@ async def _handle_anthropic_messages(
result = await _send_bedrock_messages(data, user, request, body.stream or False, product)
BEDROCK_FALLBACK_SUCCESS.labels(model=body.model, product=product).inc()
return result
- except Exception:
+ except Exception as bedrock_exc:
BEDROCK_FALLBACK_FAILURE.labels(model=body.model, product=product).inc()
- logger.exception("Bedrock fallback also failed", model=body.model, product=product)
+ logger.exception(
+ "Bedrock fallback also failed",
+ model=body.model,
+ product=product,
+ original_status=exc.status_code,
+ original_error_type=error_type,
+ **_exception_log_fields(bedrock_exc, prefix="bedrock"),
+ )
raise exc from None
else:
if isinstance(result, StreamingResponse):
@@ -346,9 +412,16 @@ async def _handle_count_tokens(
result = await _bedrock_count_tokens_impl(data, body.model, user, product)
BEDROCK_FALLBACK_SUCCESS.labels(model=body.model, product=product).inc()
return result
- except Exception:
+ except Exception as bedrock_exc:
BEDROCK_FALLBACK_FAILURE.labels(model=body.model, product=product).inc()
- logger.exception("Bedrock count_tokens fallback also failed", model=body.model, product=product)
+ logger.exception(
+ "Bedrock count_tokens fallback also failed",
+ model=body.model,
+ product=product,
+ original_status=exc.status_code,
+ original_error_type=error_type,
+ **_exception_log_fields(bedrock_exc, prefix="bedrock"),
+ )
raise exc from None
else:
await _record_anthropic_outcome(breaker, success=True)
@@ -449,28 +522,45 @@ async def _bedrock_count_tokens_impl(
settings.request_timeout,
)
return {"input_tokens": input_tokens}
- except HTTPException as e:
- status_code = str(e.status_code)
- raise
except Exception as e:
- status_code = "502"
- error_type_name = type(e).__name__
+ # 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(
- "Error proxying bedrock count_tokens request",
+ "Bedrock CountTokens failed",
model=bedrock_model,
- max_tokens=data.get("max_tokens", 4096),
- error_type=error_type_name,
- error_message=str(e),
+ product=product,
+ **_bedrock_runtime_exception_log_fields(e),
)
- raise HTTPException(
- status_code=502,
- detail={
- "error": {
- "message": f"Failed to count tokens via Bedrock ({error_type_name})",
- "type": "proxy_error",
- }
- },
- ) from e
+ logger.info("Attempting bedrock-mantle count_tokens fallback", model=bedrock_model, product=product)
+ try:
+ input_tokens = await count_tokens_with_bedrock_mantle(
+ data,
+ bedrock_model,
+ bedrock_region_name,
+ settings.request_timeout,
+ product=product,
+ )
+ return {"input_tokens": input_tokens}
+ except Exception as mantle_exc:
+ status_code = "502"
+ error_type_name = type(mantle_exc).__name__
+ 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),
+ )
+ raise HTTPException(
+ status_code=502,
+ detail={
+ "error": {
+ "message": f"Failed to count tokens via Bedrock ({error_type_name})",
+ "type": "proxy_error",
+ }
+ },
+ ) from mantle_exc
finally:
REQUEST_COUNT.labels(
endpoint=BEDROCK_COUNT_TOKENS_ENDPOINT_NAME,
diff --git a/services/llm-gateway/src/llm_gateway/bedrock.py b/services/llm-gateway/src/llm_gateway/bedrock.py
index 4e47f368ba33..e4422cd1f68b 100644
--- a/services/llm-gateway/src/llm_gateway/bedrock.py
+++ b/services/llm-gateway/src/llm_gateway/bedrock.py
@@ -4,10 +4,15 @@ import asyncio
import functools
import json
import os
+import time
from typing import Any, Final
import boto3
+import httpx
import structlog
+from boto3.session import Session as Boto3Session
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
from botocore.config import Config
from fastapi import HTTPException
@@ -16,6 +21,10 @@ from llm_gateway.config import get_settings
logger = structlog.get_logger(__name__)
BEDROCK_ANTHROPIC_VERSION: Final[str] = "bedrock-2023-05-31"
+# The bedrock-mantle endpoint speaks Anthropic's native Messages API, so it expects the
+# public Anthropic version string in an HTTP header rather than the bedrock-runtime body value.
+BEDROCK_MANTLE_ANTHROPIC_VERSION: Final[str] = "2023-06-01"
+BEDROCK_MANTLE_SIGV4_SERVICE: Final[str] = "bedrock-mantle"
DEFAULT_BEDROCK_MAX_TOKENS: Final[int] = 4096
BEDROCK_ANTHROPIC_MODEL_PREFIXES: Final[tuple[str, ...]] = (
@@ -154,6 +163,11 @@ def get_bedrock_runtime_client(region_name: str, timeout_seconds: float):
)
+def get_bedrock_session() -> Boto3Session:
+ return boto3.Session()
+
+
async def count_tokens_with_bedrock(
request_data: dict[str, Any],
model: str,
@@ -164,7 +178,7 @@ async def count_tokens_with_bedrock(
bedrock_runtime_client = get_bedrock_runtime_client(aws_region_name, timeout_seconds)
# CountTokens API does not support regional model prefixes ("us.anthropic.", "eu.anthropic.")
- count_tokens_model = model.replace("us.anthropic.", "anthropic.").replace("eu.anthropic.", "anthropic.")
+ count_tokens_model = _strip_regional_inference_prefix(model)
# Build the minimal invoke body Bedrock CountTokens accepts. Unlike invoke_model,
# CountTokens rejects extra fields such as thinking and tools.
@@ -181,3 +195,85 @@ async def count_tokens_with_bedrock(
return int(response["inputTokens"])
return await asyncio.to_thread(_sync)
+
+
+def _strip_regional_inference_prefix(model: str) -> str:
+ """Drop the regional inference-profile prefix ("us.anthropic.", "eu.anthropic.") so the
+ bare foundation-model id ("anthropic.<model>") is used for token counting."""
+ return model.replace("us.anthropic.", "anthropic.").replace("eu.anthropic.", "anthropic.")
+
+
+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"
+
+
+def _sign_bedrock_mantle_request(url: str, body: bytes, region_name: str) -> dict[str, str]:
+ """SigV4-sign a bedrock-mantle request using the ambient AWS credentials (same IAM role
+ the bedrock-runtime client uses). The AWS SDKs don't expose a client for this endpoint."""
+ credentials = get_bedrock_session().get_credentials()
+ if credentials is None:
+ raise HTTPException(
+ status_code=503,
+ detail={"error": {"message": "AWS credentials not available", "type": "configuration_error"}},
+ )
+
+ request = AWSRequest(
+ method="POST",
+ url=url,
+ data=body,
+ headers={
+ "Content-Type": "application/json",
+ "anthropic-version": BEDROCK_MANTLE_ANTHROPIC_VERSION,
+ },
+ )
+ SigV4Auth(credentials.get_frozen_credentials(), BEDROCK_MANTLE_SIGV4_SERVICE, region_name).add_auth(request)
+ return dict(request.headers)
+
+
+async def count_tokens_with_bedrock_mantle(
+ request_data: dict[str, Any],
+ model: str,
+ aws_region_name: str,
+ timeout_seconds: float,
+ *,
+ product: str,
+) -> int:
+ """Count input tokens via Anthropic's count_tokens API on the bedrock-mantle endpoint.
+
+ AWS recommends this path for Claude models that bedrock-runtime CountTokens doesn't support
+ (e.g. cross-Region-inference-only models like claude-opus-4-8). Unlike the runtime CountTokens
+ body, mantle takes the native Anthropic shape (model + messages + optional system/tools).
+ """
+ mantle_model = _strip_regional_inference_prefix(model)
+ body: dict[str, Any] = {"model": mantle_model, "messages": request_data.get("messages")}
+ for key in ("system", "tools", "tool_choice"):
+ if key in request_data:
+ body[key] = request_data[key]
+
+ payload = json.dumps(body).encode("utf-8")
+ url = get_bedrock_mantle_count_tokens_url(aws_region_name)
+ # Credential resolution can touch the network (e.g. role refresh), so sign off the event loop.
+ headers = await asyncio.to_thread(_sign_bedrock_mantle_request, url, payload, aws_region_name)
+
+ request_start_time = time.monotonic()
+ async with httpx.AsyncClient(timeout=timeout_seconds) as client:
+ response = await client.post(url, content=payload, headers=headers)
+
+ if response.status_code != 200:
+ try:
+ detail = response.json()
+ except Exception:
+ detail = {"error": {"message": response.text, "type": "api_error"}}
+ raise HTTPException(status_code=response.status_code, detail=detail)
+
+ input_tokens = int(response.json()["input_tokens"])
+ logger.info(
+ "bedrock-mantle count_tokens request succeeded",
+ model=model,
+ mantle_model=mantle_model,
+ product=product,
+ region_name=aws_region_name,
+ status_code=response.status_code,
+ duration_ms=round((time.monotonic() - request_start_time) * 1000, 2),
+ )
+ return input_tokens
diff --git a/services/llm-gateway/src/llm_gateway/circuit_breaker.py b/services/llm-gateway/src/llm_gateway/circuit_breaker.py
index eacf3596b068..472f39bb161f 100644
--- a/services/llm-gateway/src/llm_gateway/circuit_breaker.py
+++ b/services/llm-gateway/src/llm_gateway/circuit_breaker.py
@@ -76,11 +76,16 @@ class AnthropicCircuitBreaker:
pipe.hincrby(key, field, 1)
pipe.expire(key, self.window_seconds + BUCKET_WIDTH_SECONDS)
await asyncio.wait_for(pipe.execute(), timeout=REDIS_OP_TIMEOUT_SECONDS)
- except Exception:
+ except Exception as exc:
from llm_gateway.metrics.prometheus import ANTHROPIC_CIRCUIT_BREAKER_REDIS_ERRORS
ANTHROPIC_CIRCUIT_BREAKER_REDIS_ERRORS.labels(op="record").inc()
- logger.exception("circuit_breaker_record_failed", success=success)
+ logger.exception(
+ "circuit_breaker_record_failed",
+ success=success,
+ error_type=type(exc).__name__,
+ error_message=str(exc),
+ )
async def _get_stats(self) -> tuple[int, int]:
if not self.enabled or self.redis is None:
diff --git a/services/llm-gateway/tests/test_bedrock.py b/services/llm-gateway/tests/test_bedrock.py
index 9c6b917dd79c..da599e9d7a1c 100644
--- a/services/llm-gateway/tests/test_bedrock.py
+++ b/services/llm-gateway/tests/test_bedrock.py
@@ -1,7 +1,8 @@
from typing import Any
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import ANY, AsyncMock, MagicMock, patch
import pytest
+from botocore.exceptions import ClientError
from fastapi import HTTPException
from fastapi.testclient import TestClient
@@ -420,12 +421,16 @@ class TestBedrockCountTokensViaProvider:
assert response.status_code == 503
assert "Bedrock region not configured" in response.json()["error"]["message"]
+ @patch("llm_gateway.api.anthropic.REQUEST_COUNT")
@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_on_boto3_error(
+ def test_returns_502_when_runtime_and_mantle_both_fail(
self,
mock_count_tokens: MagicMock,
+ mock_mantle_count_tokens: AsyncMock,
mock_get_settings: MagicMock,
+ mock_request_count: MagicMock,
authenticated_client: TestClient,
valid_request_body: dict,
valid_request_headers: dict[str, str],
@@ -436,6 +441,10 @@ class TestBedrockCountTokensViaProvider:
mock_get_settings.return_value = mock_settings
mock_count_tokens.side_effect = Exception("AWS error")
+ mock_mantle_count_tokens.side_effect = HTTPException(
+ status_code=403,
+ detail={"error": {"message": "Access denied", "type": "permission_error"}},
+ )
response = authenticated_client.post(
"/v1/messages/count_tokens",
@@ -445,6 +454,71 @@ class TestBedrockCountTokensViaProvider:
assert response.status_code == 502
assert "Failed to count tokens via Bedrock" in response.json()["error"]["message"]
+ assert mock_request_count.labels.call_args.kwargs["status_code"] == "502"
+
+ @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(
+ self,
+ mock_count_tokens: MagicMock,
+ mock_mantle_count_tokens: AsyncMock,
+ mock_get_settings: MagicMock,
+ authenticated_client: TestClient,
+ valid_request_body: dict,
+ 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
+
+ # Mirrors bedrock-runtime rejecting CountTokens for a CRIS-only model like claude-opus-4-8.
+ mock_count_tokens.side_effect = ClientError(
+ {
+ "Error": {
+ "Code": "ValidationException",
+ "Message": "The provided model doesn't support counting tokens.",
+ },
+ "ResponseMetadata": {
+ "HTTPHeaders": {},
+ "HTTPStatusCode": 400,
+ "HostId": "",
+ "RequestId": "test-request-id",
+ "RetryAttempts": 0,
+ },
+ },
+ "CountTokens",
+ )
+ mock_mantle_count_tokens.return_value = 77
+
+ with patch("llm_gateway.api.anthropic.logger") as mock_logger:
+ response = authenticated_client.post(
+ "/v1/messages/count_tokens",
+ json=valid_request_body,
+ headers=valid_request_headers,
+ )
+
+ assert response.status_code == 200
+ assert response.json()["input_tokens"] == 77
+ 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.kwargs["product"] == "llm_gateway"
+ mock_logger.exception.assert_called_once_with(
+ "Bedrock CountTokens failed",
+ model="us.anthropic.claude-sonnet-4-6",
+ product="llm_gateway",
+ runtime_status=400,
+ runtime_error_type="ClientError",
+ runtime_error_message="The provided model doesn't support counting tokens.",
+ runtime_error_code="ValidationException",
+ )
+ mock_logger.info.assert_any_call(
+ "Attempting bedrock-mantle count_tokens fallback",
+ model="us.anthropic.claude-sonnet-4-6",
+ product="llm_gateway",
+ )
@patch("llm_gateway.api.anthropic.get_settings")
@patch("llm_gateway.api.anthropic.count_tokens_with_bedrock")
@@ -586,3 +660,141 @@ class TestModelMapping:
# which is not a valid product, so returns 400
assert response.status_code == 400
assert "Invalid product" in response.json()["detail"]
+
+
+class TestBedrockMantleCountTokens:
+ """Unit tests for the bedrock-mantle count_tokens fallback transport."""
+
+ @patch("llm_gateway.bedrock.SigV4Auth")
+ @patch("llm_gateway.bedrock.boto3.Session")
+ def test_reuses_cached_session_when_signing_mantle_requests(
+ self,
+ mock_session_cls: MagicMock,
+ mock_sigv4_auth_cls: MagicMock,
+ ) -> None:
+ from llm_gateway.bedrock import _sign_bedrock_mantle_request, get_bedrock_session
+
+ get_bedrock_session.cache_clear()
+ try:
+ frozen_credentials = MagicMock()
+ credentials = MagicMock()
+ credentials.get_frozen_credentials.return_value = frozen_credentials
+ session = MagicMock()
+ session.get_credentials.return_value = credentials
+ mock_session_cls.return_value = session
+
+ def add_auth(request: Any) -> None:
+ request.headers["Authorization"] = "signed"
+
+ mock_sigv4_auth = MagicMock()
+ mock_sigv4_auth.add_auth.side_effect = add_auth
+ mock_sigv4_auth_cls.return_value = mock_sigv4_auth
+
+ first_headers = _sign_bedrock_mantle_request(
+ "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages/count_tokens",
+ b'{"messages":[]}',
+ "us-east-1",
+ )
+ second_headers = _sign_bedrock_mantle_request(
+ "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages/count_tokens",
+ b'{"messages":[]}',
+ "us-east-1",
+ )
+
+ assert first_headers["Authorization"] == "signed"
+ assert second_headers["Authorization"] == "signed"
+ assert mock_session_cls.call_count == 1
+ assert session.get_credentials.call_count == 2
+ assert credentials.get_frozen_credentials.call_count == 2
+ assert mock_sigv4_auth_cls.call_count == 2
+ finally:
+ get_bedrock_session.cache_clear()
+
+ @pytest.mark.asyncio
+ @patch("llm_gateway.bedrock._sign_bedrock_mantle_request")
+ @patch("llm_gateway.bedrock.httpx.AsyncClient")
+ async def test_builds_request_for_mantle_endpoint(
+ self,
+ mock_async_client_cls: MagicMock,
+ mock_sign: MagicMock,
+ ) -> None:
+ import httpx
+
+ from llm_gateway.bedrock import count_tokens_with_bedrock_mantle
+
+ mock_sign.return_value = {"Authorization": "AWS4-HMAC-SHA256 ...", "anthropic-version": "2023-06-01"}
+ mock_client = AsyncMock()
+ mock_client.post = AsyncMock(return_value=httpx.Response(status_code=200, json={"input_tokens": 99}))
+ mock_async_client_cls.return_value.__aenter__.return_value = mock_client
+
+ request_data = {
+ "messages": [{"role": "user", "content": "Hello"}],
+ "system": "Be brief.",
+ "tools": [{"name": "x", "description": "", "input_schema": {"type": "object"}}],
+ }
+
+ with patch("llm_gateway.bedrock.logger") as mock_logger:
+ result = await count_tokens_with_bedrock_mantle(
+ request_data,
+ "us.anthropic.claude-opus-4-8",
+ "us-east-1",
+ 300.0,
+ product="llm_gateway",
+ )
+
+ assert result == 99
+ mock_logger.info.assert_called_once_with(
+ "bedrock-mantle count_tokens request succeeded",
+ model="us.anthropic.claude-opus-4-8",
+ mantle_model="anthropic.claude-opus-4-8",
+ product="llm_gateway",
+ region_name="us-east-1",
+ status_code=200,
+ duration_ms=ANY,
+ )
+ # URL targets the regional mantle endpoint and the native count_tokens path.
+ signed_url = mock_sign.call_args.args[0]
+ assert signed_url == "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages/count_tokens"
+ # The signed payload carries the native Anthropic shape with the prefix-stripped model id.
+ import json
+
+ signed_body = json.loads(mock_sign.call_args.args[1])
+ assert signed_body["model"] == "anthropic.claude-opus-4-8"
+ assert signed_body["messages"] == request_data["messages"]
+ assert signed_body["system"] == request_data["system"]
+ assert signed_body["tools"] == request_data["tools"]
+ # The same signed payload bytes are what gets POSTed.
+ assert mock_client.post.call_args.kwargs["content"] == mock_sign.call_args.args[1]
+
+ @pytest.mark.asyncio
+ @patch("llm_gateway.bedrock._sign_bedrock_mantle_request")
+ @patch("llm_gateway.bedrock.httpx.AsyncClient")
+ async def test_raises_http_exception_on_mantle_error(
+ self,
+ mock_async_client_cls: MagicMock,
+ mock_sign: MagicMock,
+ ) -> None:
+ import httpx
+
+ from llm_gateway.bedrock import count_tokens_with_bedrock_mantle
+
+ mock_sign.return_value = {"anthropic-version": "2023-06-01"}
+ mock_client = AsyncMock()
+ mock_client.post = AsyncMock(
+ return_value=httpx.Response(
+ status_code=400,
+ json={"type": "error", "error": {"type": "invalid_request_error", "message": "bad"}},
+ )
+ )
+ mock_async_client_cls.return_value.__aenter__.return_value = mock_client
+
+ with pytest.raises(HTTPException) as exc_info:
+ await count_tokens_with_bedrock_mantle(
+ {"messages": [{"role": "user", "content": "Hi"}]},
+ "us.anthropic.claude-opus-4-8",
+ "us-east-1",
+ 300.0,
+ product="llm_gateway",
+ )
+
+ assert exc_info.value.status_code == 400