The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
"""
Unit tests for Amazon Bedrock Mantle provider configuration.
Bedrock Mantle is Amazon Bedrock's OpenAI-compatible inference engine (Project Mantle).
API docs: https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html
"""
import json
import asyncio
from collections.abc import Mapping
from typing import Final
from unittest.mock import Mock, patch
import httpx
import pytest
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
import litellm
from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
from litellm.llms.bedrock_mantle.chat.transformation import BedrockMantleChatConfig
from litellm.llms.bedrock.base_aws_llm import run_off_loop_if_aws
from litellm.llms.custom_httpx.http_handler import HTTPHandler
from litellm.types.utils import LlmProviders
from tests.unit.llms.bedrock.event_loop_probe import EventLoopProbe
@pytest.fixture
def local_cost_map(monkeypatch):
original_model_cost = litellm.model_cost
original_bedrock_mantle_models = set(litellm.bedrock_mantle_models)
try:
monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "true")
litellm.model_cost = litellm.get_model_cost_map(url="")
litellm.get_model_info.cache_clear()
litellm.add_known_models()
yield
finally:
litellm.model_cost = original_model_cost
litellm.bedrock_mantle_models.clear()
litellm.bedrock_mantle_models.update(original_bedrock_mantle_models)
litellm.get_model_info.cache_clear()
_RESPONSES_API_REPLY: Final = {
"id": "resp_test",
"object": "response",
"created_at": 1733529600,
"status": "completed",
"model": "openai.gpt-5.6-terra",
"output": [
{
"type": "message",
"id": "msg_test",
"status": "completed",
"role": "assistant",
"content": [{"type": "output_text", "text": "ok", "annotations": []}],
}
],
"usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2},
}
_CHAT_COMPLETIONS_REPLY: Final = {
"id": "chatcmpl-test",
"object": "chat.completion",
"created": 1733529600,
"model": "openai.gpt-5.6-terra",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
}
def _use_mantle_bearer(monkeypatch: pytest.MonkeyPatch) -> None:
for var in ("AWS_BEARER_TOKEN_BEDROCK", "BEDROCK_MANTLE_API_BASE", "BEDROCK_MANTLE_REGION"):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "test-key")
def _reply_by_route(request: httpx.Request) -> httpx.Response:
reply: Final = _RESPONSES_API_REPLY if request.url.path.endswith("/responses") else _CHAT_COMPLETIONS_REPLY
return httpx.Response(status_code=200, json=reply, request=request)
def _recording_client(handler: Mock) -> HTTPHandler:
return HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler)))
def _mantle_chat_request(drop_params: bool, **params: object) -> dict[str, object]:
optional_params: Final = litellm.get_optional_params(
model="openai.gpt-5.6-terra", custom_llm_provider="bedrock_mantle", drop_params=drop_params, **params
)
return BedrockMantleChatConfig().transform_request(
model="openai.gpt-5.6-terra",
messages=[{"role": "user", "content": "hello"}],
optional_params=optional_params,
litellm_params={"drop_params": drop_params},
headers={},
)
class TestBedrockMantleProviderRegistration:
def test_provider_enum_exists(self):
assert LlmProviders.BEDROCK_MANTLE == "bedrock_mantle"
def test_provider_in_provider_list(self):
assert "bedrock_mantle" in litellm.provider_list
class TestBedrockMantleConfig:
def test_custom_llm_provider(self):
cfg = BedrockMantleChatConfig()
assert cfg.custom_llm_provider == "bedrock_mantle"
def test_default_api_base_uses_env_region(self, monkeypatch):
monkeypatch.setenv("BEDROCK_MANTLE_REGION", "eu-west-1")
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(None, None)
assert api_base == "https://bedrock-mantle.eu-west-1.api.aws/v1"
def test_default_api_base_uses_aws_region(self, monkeypatch):
monkeypatch.delenv("BEDROCK_MANTLE_REGION", raising=False)
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
monkeypatch.setenv("AWS_REGION", "ap-northeast-1")
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(None, None)
assert api_base == "https://bedrock-mantle.ap-northeast-1.api.aws/v1"
def test_default_api_base_uses_aws_region_name_env(self, monkeypatch):
monkeypatch.delenv("BEDROCK_MANTLE_REGION", raising=False)
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
monkeypatch.delenv("AWS_REGION", raising=False)
monkeypatch.setenv("AWS_REGION_NAME", "ca-central-1")
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(None, None)
assert api_base == "https://bedrock-mantle.ca-central-1.api.aws/v1"
def test_aws_region_name_param_overrides_env(self, monkeypatch):
from litellm.types.router import GenericLiteLLMParams
monkeypatch.setenv("BEDROCK_MANTLE_REGION", "us-west-2")
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(
None, None, litellm_params=GenericLiteLLMParams(aws_region_name="us-east-2")
)
assert api_base == "https://bedrock-mantle.us-east-2.api.aws/v1"
def test_malicious_aws_region_name_rejected(self, monkeypatch):
from litellm.types.router import GenericLiteLLMParams
monkeypatch.delenv("BEDROCK_MANTLE_REGION", raising=False)
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
monkeypatch.delenv("AWS_REGION", raising=False)
cfg = BedrockMantleChatConfig()
with pytest.raises(ValueError, match="api\\.aws\\.attacker\\.example/'\\. Region names must contain only"):
cfg.get_openai_compatible_provider_info(
None,
None,
litellm_params=GenericLiteLLMParams(aws_region_name="us-east-1.api.aws.attacker.example/"),
)
def test_get_llm_provider_rejects_malicious_aws_region_name(self, monkeypatch):
from litellm.types.router import GenericLiteLLMParams
monkeypatch.delenv("BEDROCK_MANTLE_REGION", raising=False)
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
monkeypatch.delenv("AWS_REGION", raising=False)
with pytest.raises(litellm.exceptions.BadRequestError):
litellm.get_llm_provider(
model="openai.gpt-5.5",
custom_llm_provider="bedrock_mantle",
litellm_params=GenericLiteLLMParams(
aws_region_name="us-east-1.api.aws.attacker.example/"
),
)
def test_get_llm_provider_uses_aws_region_name_for_responses(
self, monkeypatch, local_cost_map
):
from litellm.types.router import GenericLiteLLMParams
monkeypatch.delenv("BEDROCK_MANTLE_REGION", raising=False)
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
monkeypatch.delenv("AWS_REGION", raising=False)
_, provider, _, api_base = litellm.get_llm_provider(
model="openai.gpt-5.5",
custom_llm_provider="bedrock_mantle",
litellm_params=GenericLiteLLMParams(aws_region_name="us-east-2"),
)
assert provider == "bedrock_mantle"
# gpt-5.x carries use_openai_responses_path, so it is served on the
# /openai/v1 base per the AWS model card.
assert api_base == "https://bedrock-mantle.us-east-2.api.aws/openai/v1"
def test_region_prefixed_model_routes_to_that_region(self, monkeypatch, local_cost_map):
for var in ("BEDROCK_MANTLE_REGION", "BEDROCK_MANTLE_API_BASE", "AWS_REGION", "AWS_REGION_NAME"):
monkeypatch.delenv(var, raising=False)
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(None, None, model="us-gov-west-1/xai.grok-4.3")
assert api_base == "https://bedrock-mantle.us-gov-west-1.api.aws/openai/v1"
def test_aws_region_name_param_beats_model_region_prefix(self, monkeypatch, local_cost_map):
from litellm.types.router import GenericLiteLLMParams
for var in ("BEDROCK_MANTLE_REGION", "BEDROCK_MANTLE_API_BASE", "AWS_REGION", "AWS_REGION_NAME"):
monkeypatch.delenv(var, raising=False)
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(
None,
None,
litellm_params=GenericLiteLLMParams(aws_region_name="us-east-1"),
model="us-gov-west-1/xai.grok-4.3",
)
assert api_base == "https://bedrock-mantle.us-east-1.api.aws/openai/v1"
def test_default_api_base_fallback_to_us_east_1(self, monkeypatch):
monkeypatch.delenv("BEDROCK_MANTLE_REGION", raising=False)
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
monkeypatch.delenv("AWS_REGION", raising=False)
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(None, None)
assert api_base == "https://bedrock-mantle.us-east-1.api.aws/v1"
def test_custom_api_base_overrides_default(self, monkeypatch):
custom_base = "https://bedrock-mantle.us-west-2.api.aws/v1"
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(custom_base, None)
assert api_base == custom_base
def test_chat_base_for_gpt_oss_uses_v1(self, monkeypatch):
# gpt-oss carries no use_openai_responses_path flag, so it stays on the
# standard /v1 base; no regression for existing chat usage now that the
# segment is data-driven.
monkeypatch.setenv("BEDROCK_MANTLE_REGION", "us-east-2")
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(None, None, model="openai.gpt-oss-120b")
assert api_base == "https://bedrock-mantle.us-east-2.api.aws/v1"
@pytest.mark.parametrize(
"model_id",
["google.gemma-4-31b", "google.gemma-4-26b-a4b", "google.gemma-4-e2b"],
)
def test_chat_base_for_gemma_4_uses_openai_v1(self, monkeypatch, local_cost_map, model_id):
# The chat-config bug the Gemma 4 cards exposed: gemma-4-* is served on the
# /openai/v1 base, not the hardcoded /v1. Driven by the price-map
# use_openai_responses_path flag (loaded by local_cost_map). Fails before
# the data-driven segment lands.
monkeypatch.setenv("BEDROCK_MANTLE_REGION", "us-east-2")
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(None, None, model=model_id)
assert api_base == "https://bedrock-mantle.us-east-2.api.aws/openai/v1"
def test_chat_base_explicit_api_base_wins_over_derived(self, monkeypatch, local_cost_map):
# An explicit api_base must not be overridden by the data-driven default,
# even for a model whose default differs (gemma-4 -> openai/v1).
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
custom_base = "https://bedrock-mantle.us-west-2.api.aws/v1"
cfg = BedrockMantleChatConfig()
api_base, _ = cfg.get_openai_compatible_provider_info(custom_base, None, model="google.gemma-4-31b")
assert api_base == custom_base
def test_api_key_from_env(self, monkeypatch):
monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "test-key-123")
cfg = BedrockMantleChatConfig()
_, api_key = cfg.get_openai_compatible_provider_info(None, None)
assert api_key == "test-key-123"
def test_api_key_param_overrides_env(self, monkeypatch):
monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "env-key")
cfg = BedrockMantleChatConfig()
_, api_key = cfg.get_openai_compatible_provider_info(None, "explicit-key")
assert api_key == "explicit-key"
def test_api_key_from_aws_bearer_token_bedrock_env(self, monkeypatch):
monkeypatch.delenv("BEDROCK_MANTLE_API_KEY", raising=False)
monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "standard-bearer")
cfg = BedrockMantleChatConfig()
_, api_key = cfg.get_openai_compatible_provider_info(None, None)
assert api_key == "standard-bearer"
def test_get_supported_openai_params(self):
cfg = BedrockMantleChatConfig()
params = cfg.get_supported_openai_params("openai.gpt-oss-120b")
assert "tools" in params
assert "tool_choice" in params
assert "temperature" in params
assert "stream" in params
assert "max_tokens" in params
assert "verbosity" not in params
def test_verbosity_passes_through_for_gpt_5_models(self):
cfg = BedrockMantleChatConfig()
assert "verbosity" in cfg.get_supported_openai_params("openai.gpt-5.6-sol")
optional_params = litellm.get_optional_params(
model="openai.gpt-5.6-sol",
custom_llm_provider="bedrock_mantle",
verbosity="low",
drop_params=False,
)
assert optional_params["verbosity"] == "low"
@pytest.mark.parametrize(
"model", ["openai.gpt-5.6-terra", "us-gov-west-1/openai.gpt-5.6-terra", "openai.gpt-6-sol"]
)
@pytest.mark.parametrize("limit_param", ["max_tokens", "max_completion_tokens"])
def test_gpt_reasoning_series_output_limit_is_sent_as_max_completion_tokens(
self, model: str, limit_param: str
) -> None:
optional_params = litellm.get_optional_params(
model=model,
custom_llm_provider="bedrock_mantle",
drop_params=False,
**{limit_param: 1000},
)
assert optional_params["max_completion_tokens"] == 1000
assert "max_tokens" not in optional_params
def test_gpt_reasoning_series_explicit_max_completion_tokens_wins_over_max_tokens(self):
optional_params = litellm.get_optional_params(
model="openai.gpt-5.6-terra",
custom_llm_provider="bedrock_mantle",
drop_params=False,
max_tokens=1000,
max_completion_tokens=50,
)
assert optional_params["max_completion_tokens"] == 50
assert "max_tokens" not in optional_params
@pytest.mark.parametrize(
"reasoning_effort, expected",
[({"effort": "low", "summary": "auto"}, "low"), ("medium", "medium"), ({"summary": "auto"}, None)],
)
def test_chat_completions_gets_reasoning_effort_as_a_level(self, reasoning_effort, expected) -> None:
"""Mantle chat answers a Responses-shaped ``{"effort", "summary"}`` with ``invalid_type``."""
request = _mantle_chat_request(drop_params=True, reasoning_effort=reasoning_effort)
assert request.get("reasoning_effort") == expected
@pytest.mark.parametrize("params", [{"n": 2}, {"reasoning_effort": {"effort": "low", "summary": "auto"}}])
def test_chat_completions_answers_400_for_what_mantle_chat_cannot_serve_without_drop_params(self, params) -> None:
with pytest.raises(litellm.UnsupportedParamsError):
_mantle_chat_request(drop_params=False, **params)
@pytest.mark.parametrize("n, drop_params, expected", [(1, False, 1), (2, True, None)])
def test_chat_completions_sends_n_only_where_mantle_chat_serves_it(self, n, drop_params, expected) -> None:
assert _mantle_chat_request(drop_params=drop_params, n=n).get("n") == expected
@pytest.mark.parametrize(
"params, model_info",
[
({"n": 2}, None),
({"reasoning_effort": {"effort": "low", "summary": "auto"}}, {"mode": "chat"}),
({"web_search_options": {"search_context_size": "low"}}, {"mode": "chat"}),
],
)
def test_what_mantle_chat_cannot_serve_reaches_the_responses_api(
self, monkeypatch, local_cost_map, params, model_info
) -> None:
_use_mantle_bearer(monkeypatch)
handler: Final = Mock(side_effect=_reply_by_route)
response: Final = litellm.completion(
model="bedrock_mantle/openai.gpt-5.6-terra",
messages=[{"role": "user", "content": "hello"}],
aws_region_name="us-east-1",
model_info=model_info,
client=_recording_client(handler),
**params,
)
sent: Final = tuple(call.args[0] for call in handler.call_args_list)
assert response.choices[0].message.content == "ok"
assert [request.url.path.rsplit("/", 1)[-1] for request in sent] == ["responses"]
assert json.loads(sent[0].content).get("reasoning", {}).get("summary") == params.get(
"reasoning_effort", {}
).get("summary")
@pytest.mark.parametrize(
"extra_body, drop_params, expected",
[
({"reasoning_effort": {"effort": "low"}}, False, {"reasoning_effort": "low"}),
({"n": 2}, True, {}),
({"reasoning_effort": {}}, False, {}),
({"reasoning_effort": {"effort": None}}, False, {}),
({"n": 1, "reasoning_effort": "high"}, False, {"n": 1, "reasoning_effort": "high"}),
],
ids=[
"dict-effort",
"n-above-one-dropped",
"empty-effort-asks-for-the-default",
"null-effort-asks-for-the-default",
"servable",
],
)
def test_a_chat_pin_sends_extra_body_through_the_same_chat_checks(
self, monkeypatch, local_cost_map, extra_body, drop_params, expected
) -> None:
_use_mantle_bearer(monkeypatch)
handler: Final = Mock(side_effect=_reply_by_route)
litellm.completion(
model="bedrock_mantle/openai.gpt-5.6-terra",
messages=[{"role": "user", "content": "hello"}],
aws_region_name="us-east-1",
model_info={"mode": "chat"},
client=_recording_client(handler),
extra_body=extra_body,
drop_params=drop_params,
)
(sent,) = (call.args[0] for call in handler.call_args_list)
body: Final = json.loads(sent.content)
assert sent.url.path.endswith("/chat/completions")
assert {key: body[key] for key in ("n", "reasoning_effort") if key in body} == expected
def test_a_chat_pin_answers_400_for_n_above_one_in_extra_body_without_drop_params(
self, monkeypatch, local_cost_map
) -> None:
_use_mantle_bearer(monkeypatch)
handler: Final = Mock(side_effect=_reply_by_route)
with pytest.raises(litellm.BadRequestError, match="does not support n=2"):
litellm.completion(
model="bedrock_mantle/openai.gpt-5.6-terra",
messages=[{"role": "user", "content": "hello"}],
aws_region_name="us-east-1",
model_info={"mode": "chat"},
client=_recording_client(handler),
extra_body={"n": 2},
)
handler.assert_not_called()
def test_non_gpt_reasoning_models_keep_the_openai_compatible_max_tokens(self):
optional_params = litellm.get_optional_params(
model="openai.gpt-oss-120b",
custom_llm_provider="bedrock_mantle",
drop_params=False,
max_completion_tokens=1000,
)
assert optional_params["max_tokens"] == 1000
assert "max_completion_tokens" not in optional_params
class TestBedrockMantleChatAuth:
"""Chat Completions must use the same Bearer-or-SigV4 auth as the Responses
backend. These fail on a config that inherits the no-op default sign_request.
"""
def _signer_that_forbids_credentials(self):
from unittest.mock import MagicMock
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
signer = BaseAWSLLM()
signer.get_credentials = MagicMock(
side_effect=AssertionError("SigV4 must not run when a Bearer token exists")
)
return signer
def test_bearer_token_skips_sigv4(self, monkeypatch):
monkeypatch.delenv("BEDROCK_MANTLE_API_KEY", raising=False)
monkeypatch.delenv("AWS_BEARER_TOKEN_BEDROCK", raising=False)
signer = self._signer_that_forbids_credentials()
cfg = BedrockMantleChatConfig(aws_signer=signer)
headers, signed_body = cfg.sign_request(
headers={},
optional_params={},
request_data={"model": "openai.gpt-oss-120b", "messages": []},
api_base="https://bedrock-mantle.us-east-1.api.aws/v1/chat/completions",
api_key="bearer-from-arg",
)
assert headers["Authorization"] == "Bearer bearer-from-arg"
assert json.loads(signed_body) == {
"model": "openai.gpt-oss-120b",
"messages": [],
}
signer.get_credentials.assert_not_called()
def test_mantle_env_key_used_as_bearer(self, monkeypatch):
monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "env-mantle-key")
monkeypatch.delenv("AWS_BEARER_TOKEN_BEDROCK", raising=False)
signer = self._signer_that_forbids_credentials()
cfg = BedrockMantleChatConfig(aws_signer=signer)
headers, _ = cfg.sign_request(
headers={},
optional_params={},
request_data={"input": "hi"},
api_base="https://bedrock-mantle.us-east-1.api.aws/v1/chat/completions",
api_key=None,
)
assert headers["Authorization"] == "Bearer env-mantle-key"
signer.get_credentials.assert_not_called()
def test_aws_bearer_token_bedrock_used_as_bearer(self, monkeypatch):
monkeypatch.delenv("BEDROCK_MANTLE_API_KEY", raising=False)
monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "standard-bearer")
signer = self._signer_that_forbids_credentials()
cfg = BedrockMantleChatConfig(aws_signer=signer)
headers, _ = cfg.sign_request(
headers={},
optional_params={},
request_data={"input": "hi"},
api_base="https://bedrock-mantle.us-east-1.api.aws/v1/chat/completions",
api_key=None,
)
assert headers["Authorization"] == "Bearer standard-bearer"
signer.get_credentials.assert_not_called()
def test_no_bearer_signs_with_sigv4(self, monkeypatch):
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
monkeypatch.delenv("BEDROCK_MANTLE_API_KEY", raising=False)
monkeypatch.delenv("AWS_BEARER_TOKEN_BEDROCK", raising=False)
cfg = BedrockMantleChatConfig(aws_signer=BaseAWSLLM())
headers, signed_body = cfg.sign_request(
headers={},
optional_params={
"aws_access_key_id": "AKIAEXAMPLE",
"aws_secret_access_key": "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0",
"aws_session_token": "session-token-test",
"aws_region_name": "us-east-2",
},
request_data={"model": "openai.gpt-oss-120b", "messages": []},
api_base="https://bedrock-mantle.us-east-2.api.aws/v1/chat/completions",
api_key=None,
)
assert headers["Authorization"].startswith("AWS4-HMAC-SHA256")
assert "Credential=AKIAEXAMPLE/" in headers["Authorization"]
assert "/us-east-2/bedrock/aws4_request" in headers["Authorization"]
assert headers["X-Amz-Security-Token"] == "session-token-test"
assert json.loads(signed_body) == {
"model": "openai.gpt-oss-120b",
"messages": [],
}
def test_sigv4_region_resolved_from_api_base_host(self, monkeypatch):
# Chat passes the OpenAI-mapped optional_params (no aws_region_name) to
# sign_request, so the SigV4 credential scope has to come from the already
# region-resolved api_base host or it would disagree with the URL -> 401.
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
for var in (
"BEDROCK_MANTLE_API_KEY",
"AWS_BEARER_TOKEN_BEDROCK",
"BEDROCK_MANTLE_REGION",
"BEDROCK_MANTLE_API_BASE",
"AWS_REGION",
"AWS_REGION_NAME",
):
monkeypatch.delenv(var, raising=False)
cfg = BedrockMantleChatConfig(aws_signer=BaseAWSLLM())
headers, _ = cfg.sign_request(
headers={},
optional_params={
"aws_access_key_id": "AKIAEXAMPLE",
"aws_secret_access_key": "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0",
},
request_data={"input": "hi"},
api_base="https://bedrock-mantle.eu-west-1.api.aws/v1/chat/completions",
api_key=None,
)
assert "/eu-west-1/bedrock/aws4_request" in headers["Authorization"]
def test_sigv4_scope_matches_api_base_when_aws_region_name_disagrees(
self, monkeypatch
):
# If a caller (e.g. proxy) passes a stale api_base in one region and an
# aws_region_name in a different region, the SigV4 credential scope must
# match the URL host or Bedrock rejects the request with 401. Without the
# fix, sign_request would prefer aws_region_name and sign for us-west-2
# while POSTing to eu-west-1.
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
for var in (
"BEDROCK_MANTLE_API_KEY",
"AWS_BEARER_TOKEN_BEDROCK",
"BEDROCK_MANTLE_REGION",
"BEDROCK_MANTLE_API_BASE",
"AWS_REGION",
"AWS_REGION_NAME",
):
monkeypatch.delenv(var, raising=False)
cfg = BedrockMantleChatConfig(aws_signer=BaseAWSLLM())
headers, _ = cfg.sign_request(
headers={},
optional_params={
"aws_access_key_id": "AKIAEXAMPLE",
"aws_secret_access_key": "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0",
"aws_region_name": "us-west-2",
},
request_data={"input": "hi"},
api_base="https://bedrock-mantle.eu-west-1.api.aws/v1/chat/completions",
api_key=None,
)
assert "/eu-west-1/bedrock/aws4_request" in headers["Authorization"]
assert "/us-west-2/bedrock/aws4_request" not in headers["Authorization"]
@pytest.mark.parametrize(
("region_params", "env", "expected_region"),
[
({"aws_region_name": "us-west-2"}, {}, "us-west-2"),
({}, {"BEDROCK_MANTLE_REGION": "ap-southeast-2"}, "ap-southeast-2"),
],
)
def test_sigv4_scope_ignores_the_region_segment_of_a_lookalike_host(
self, monkeypatch, region_params, env, expected_region
):
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
for var in (
"BEDROCK_MANTLE_API_KEY",
"AWS_BEARER_TOKEN_BEDROCK",
"BEDROCK_MANTLE_REGION",
"BEDROCK_MANTLE_API_BASE",
"AWS_REGION",
"AWS_REGION_NAME",
):
monkeypatch.delenv(var, raising=False)
for var, value in env.items():
monkeypatch.setenv(var, value)
cfg = BedrockMantleChatConfig(aws_signer=BaseAWSLLM())
headers, _ = cfg.sign_request(
headers={},
optional_params={
"aws_access_key_id": "AKIAEXAMPLE",
"aws_secret_access_key": "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0",
**region_params,
},
request_data={"input": "hi"},
api_base="https://bedrock-mantle.eu-west-1.api.aws.internal.example.com/openai/v1/chat/completions",
api_key=None,
)
assert f"/{expected_region}/bedrock/aws4_request" in headers["Authorization"]
assert "/eu-west-1/bedrock/aws4_request" not in headers["Authorization"]
def test_no_bearer_and_no_credentials_raises_value_error(self, monkeypatch):
from unittest.mock import MagicMock
from botocore.exceptions import NoCredentialsError
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
monkeypatch.delenv("BEDROCK_MANTLE_API_KEY", raising=False)
monkeypatch.delenv("AWS_BEARER_TOKEN_BEDROCK", raising=False)
signer = BaseAWSLLM()
signer.get_credentials = MagicMock(side_effect=NoCredentialsError())
cfg = BedrockMantleChatConfig(aws_signer=signer)
with pytest.raises(ValueError, match='Bedrock Mantle auth failed: no Bearer token and no usable') as exc:
cfg.sign_request(
headers={},
optional_params={"aws_region_name": "us-east-2"},
request_data={"input": "hi"},
api_base="https://bedrock-mantle.us-east-2.api.aws/v1/chat/completions",
api_key=None,
)
msg = str(exc.value)
assert "Bearer" in msg
assert "SigV4" in msg or "IAM" in msg
def test_completion_no_bearer_signs_with_sigv4_end_to_end(self, monkeypatch):
# The full completion chain (not just sign_request in isolation) must reach
# the SigV4 path when no Bearer token exists: with api_key=None the parent
# validate_environment must not short-circuit before sign_request runs.
for var in (
"BEDROCK_MANTLE_API_KEY",
"AWS_BEARER_TOKEN_BEDROCK",
"BEDROCK_MANTLE_API_BASE",
"BEDROCK_MANTLE_REGION",
"AWS_REGION_NAME",
):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAEXAMPLE")
monkeypatch.setenv(
"AWS_SECRET_ACCESS_KEY", "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0"
)
monkeypatch.setenv("AWS_REGION", "us-east-2")
requests = []
def mock_post(self, url, data=None, headers=None, **kwargs):
requests.append({"url": url, "headers": headers or {}})
return httpx.Response(
status_code=200,
json={
"id": "chatcmpl-test",
"object": "chat.completion",
"created": 1733529600,
"model": "openai.gpt-oss-120b",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "ok"},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 1,
"completion_tokens": 1,
"total_tokens": 2,
},
},
request=httpx.Request("POST", url),
)
with patch(
"litellm.llms.custom_httpx.http_handler.HTTPHandler.post", mock_post
):
response = litellm.completion(
model="bedrock_mantle/openai.gpt-oss-120b",
messages=[{"role": "user", "content": "hello"}],
)
assert response.choices[0].message.content == "ok"
assert len(requests) == 1
authorization = requests[0]["headers"]["Authorization"]
assert authorization.startswith("AWS4-HMAC-SHA256")
assert "/us-east-2/bedrock/aws4_request" in authorization
assert requests[0]["url"].startswith("https://bedrock-mantle.us-east-2.api.aws")
def test_completion_per_request_role_reaches_signer_and_not_the_body(self, monkeypatch):
from unittest.mock import MagicMock, Mock
from botocore.credentials import Credentials
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
from litellm.llms.custom_httpx.http_handler import HTTPHandler
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
from litellm.types.utils import ModelResponse
for var in ("BEDROCK_MANTLE_API_KEY", "AWS_BEARER_TOKEN_BEDROCK", "BEDROCK_MANTLE_API_BASE"):
monkeypatch.delenv(var, raising=False)
signer = BaseAWSLLM()
signer.get_credentials = MagicMock(
return_value=Credentials(
access_key="ASIAEXAMPLE",
secret_key="YXNzdW1lZC1yb2xlLXNlY3JldC1hc3N1bWVk",
token="assumed-session-token",
)
)
url = "https://bedrock-mantle.us-east-1.api.aws/openai/v1/chat/completions"
client = HTTPHandler(client=httpx.Client())
client.post = Mock(
return_value=httpx.Response(
status_code=200,
json={
"id": "chatcmpl-test",
"object": "chat.completion",
"created": 1733529600,
"model": "google.gemma-4-31b",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
},
request=httpx.Request("POST", url),
)
)
BaseLLMHTTPHandler().completion(
model="google.gemma-4-31b",
messages=[{"role": "user", "content": "hello"}],
api_base=None,
custom_llm_provider="bedrock_mantle",
model_response=ModelResponse(),
encoding=None,
logging_obj=Mock(),
optional_params={},
timeout=10,
litellm_params={
"aws_role_name": "arn:aws:iam::000000000000:role/attributed-role",
"aws_session_name": "user-123",
"aws_region_name": "us-east-1",
},
acompletion=False,
client=client,
provider_config=BedrockMantleChatConfig(aws_signer=signer),
)
credential_kwargs = signer.get_credentials.call_args.kwargs
assert credential_kwargs["aws_role_name"] == "arn:aws:iam::000000000000:role/attributed-role"
assert credential_kwargs["aws_session_name"] == "user-123"
sent = client.post.call_args.kwargs
assert sent["headers"]["Authorization"].startswith("AWS4-HMAC-SHA256")
assert not [key for key in json.loads(sent["data"]) if key.startswith("aws_")]
class TestBedrockMantleProjectHeader:
def test_validate_environment_sets_openai_project_header(self):
cfg = BedrockMantleChatConfig()
headers = cfg.validate_environment(
headers={},
model="openai.gpt-oss-120b",
messages=[{"role": "user", "content": "hi"}],
optional_params={},
litellm_params={"aws_bedrock_project_id": "proj_abc123def456"},
api_key="fake-key",
)
assert headers["OpenAI-Project"] == "proj_abc123def456"
assert headers["Authorization"] == "Bearer fake-key"
def test_validate_environment_without_project_id(self):
cfg = BedrockMantleChatConfig()
headers = cfg.validate_environment(
headers={},
model="openai.gpt-oss-120b",
messages=[{"role": "user", "content": "hi"}],
optional_params={},
litellm_params={},
api_key="fake-key",
)
assert "OpenAI-Project" not in headers
def test_completion_sends_openai_project_header_and_clean_body(self):
requests = []
def mock_post(self, url, data=None, headers=None, **kwargs):
raw_body = data.decode("utf-8") if isinstance(data, bytes) else data
requests.append(
{"headers": headers or {}, "body": json.loads(raw_body or "{}")}
)
return httpx.Response(
status_code=200,
json={
"id": "chatcmpl-test",
"object": "chat.completion",
"created": 1733529600,
"model": "openai.gpt-oss-120b",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "ok"},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 1,
"completion_tokens": 1,
"total_tokens": 2,
},
},
request=httpx.Request("POST", url),
)
with patch(
"litellm.llms.custom_httpx.http_handler.HTTPHandler.post", mock_post
):
response = litellm.completion(
model="bedrock_mantle/openai.gpt-oss-120b",
messages=[{"role": "user", "content": "hello"}],
api_key="fake-key",
aws_bedrock_project_id="proj_abc123def456",
)
assert response.choices[0].message.content == "ok"
assert len(requests) == 1
assert requests[0]["headers"]["OpenAI-Project"] == "proj_abc123def456"
assert "aws_bedrock_project_id" not in requests[0]["body"]
class TestBedrockMantleProviderResolution:
def test_get_llm_provider_resolves_correctly(self):
model, provider, _, _ = litellm.get_llm_provider(
"bedrock_mantle/openai.gpt-oss-120b"
)
assert provider == "bedrock_mantle"
assert model == "openai.gpt-oss-120b"
def test_get_llm_provider_20b(self):
model, provider, _, _ = litellm.get_llm_provider(
"bedrock_mantle/openai.gpt-oss-20b"
)
assert provider == "bedrock_mantle"
assert model == "openai.gpt-oss-20b"
def test_get_llm_provider_strips_region_prefix(self, monkeypatch, local_cost_map):
for var in ("BEDROCK_MANTLE_REGION", "BEDROCK_MANTLE_API_BASE", "AWS_REGION", "AWS_REGION_NAME"):
monkeypatch.delenv(var, raising=False)
model, provider, _, api_base = litellm.get_llm_provider("bedrock_mantle/us-gov-west-1/xai.grok-4.3")
assert provider == "bedrock_mantle"
assert model == "xai.grok-4.3"
assert api_base == "https://bedrock-mantle.us-gov-west-1.api.aws/openai/v1"
def test_completion_region_prefixed_model_sends_bare_model_to_that_region(self, monkeypatch, local_cost_map):
from litellm.llms.custom_httpx.http_handler import HTTPHandler
for var in (
"BEDROCK_MANTLE_API_KEY",
"AWS_BEARER_TOKEN_BEDROCK",
"BEDROCK_MANTLE_API_BASE",
"BEDROCK_MANTLE_REGION",
"AWS_REGION_NAME",
"AWS_REGION",
"AWS_PROFILE",
):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAEXAMPLE")
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0")
def respond(request: httpx.Request) -> httpx.Response:
return httpx.Response(
status_code=200,
json={
"id": "chatcmpl-test",
"object": "chat.completion",
"created": 1733529600,
"model": "xai.grok-4.3",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 38, "completion_tokens": 20, "total_tokens": 58},
},
request=request,
)
handler = Mock(side_effect=respond)
response = litellm.completion(
model="bedrock_mantle/us-gov-west-1/xai.grok-4.3",
messages=[{"role": "user", "content": "hello"}],
client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler))),
)
gov = litellm.model_cost["bedrock_mantle/us-gov-west-1/xai.grok-4.3"]
sent = handler.call_args.args[0]
assert str(sent.url) == "https://bedrock-mantle.us-gov-west-1.api.aws/openai/v1/chat/completions"
assert json.loads(sent.content)["model"] == "xai.grok-4.3"
assert "/us-gov-west-1/bedrock/aws4_request" in sent.headers["Authorization"]
assert response._hidden_params["response_cost"] == pytest.approx(
38 * gov["input_cost_per_token"] + 20 * gov["output_cost_per_token"]
)
def test_responses_region_prefixed_model_prices_from_that_region_over_env_region(self, monkeypatch, local_cost_map):
from litellm.llms.custom_httpx.http_handler import HTTPHandler
for var in (
"BEDROCK_MANTLE_API_KEY",
"AWS_BEARER_TOKEN_BEDROCK",
"BEDROCK_MANTLE_API_BASE",
"BEDROCK_MANTLE_REGION",
"AWS_REGION",
"AWS_PROFILE",
):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("AWS_REGION_NAME", "us-east-1")
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAEXAMPLE")
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0")
def respond(request: httpx.Request) -> httpx.Response:
return httpx.Response(
status_code=200,
json={
"id": "resp_test",
"object": "response",
"created_at": 1733529600,
"status": "completed",
"model": "xai.grok-4.3",
"output": [
{
"type": "message",
"id": "msg_test",
"status": "completed",
"role": "assistant",
"content": [{"type": "output_text", "text": "ok", "annotations": []}],
}
],
"parallel_tool_calls": True,
"tool_choice": "auto",
"tools": [],
"top_p": 1.0,
"usage": {"input_tokens": 38, "output_tokens": 20, "total_tokens": 58},
},
request=request,
)
handler = Mock(side_effect=respond)
response = litellm.responses(
model="bedrock_mantle/us-gov-west-1/xai.grok-4.3",
input="hello",
client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler))),
)
gov = litellm.model_cost["bedrock_mantle/us-gov-west-1/xai.grok-4.3"]
sent = handler.call_args.args[0]
assert str(sent.url) == "https://bedrock-mantle.us-gov-west-1.api.aws/openai/v1/responses"
assert json.loads(sent.content)["model"] == "xai.grok-4.3"
assert "/us-gov-west-1/bedrock/aws4_request" in sent.headers["Authorization"]
assert response._hidden_params["response_cost"] == pytest.approx(
38 * gov["input_cost_per_token"] + 20 * gov["output_cost_per_token"]
)
def _row_cost(key: str, input_tokens: int, output_tokens: int) -> float:
row: Final[Mapping[str, float]] = litellm.model_cost[key]
return input_tokens * row["input_cost_per_token"] + output_tokens * row["output_cost_per_token"]
def _anthropic_message(request: httpx.Request) -> httpx.Response:
return httpx.Response(
status_code=200,
json={
"id": "msg_test",
"type": "message",
"role": "assistant",
"model": "anthropic.claude-opus-5-5",
"content": [{"type": "text", "text": "ok"}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 10, "output_tokens": 5},
},
request=request,
)
def _anthropic_event_stream(request: httpx.Request) -> httpx.Response:
events = (
(
"message_start",
{
"type": "message_start",
"message": {
"id": "msg_test",
"type": "message",
"role": "assistant",
"model": "anthropic.claude-opus-5-5",
"content": [],
"usage": {"input_tokens": 10, "output_tokens": 0},
},
},
),
(
"content_block_start",
{"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
),
(
"content_block_delta",
{"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "streamed"}},
),
(
"message_delta",
{"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 3}},
),
("message_stop", {"type": "message_stop"}),
)
body = "".join(f"event: {name}\ndata: {json.dumps(data)}\n\n" for name, data in events)
return httpx.Response(
status_code=200, content=body.encode(), headers={"content-type": "text/event-stream"}, request=request
)
class TestBedrockMantleClaudeChatRoute:
def test_claude_completion_uses_native_messages_endpoint(self, monkeypatch, local_cost_map):
from litellm.llms.custom_httpx.http_handler import HTTPHandler
monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "mantle-key")
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
handler = Mock(side_effect=_anthropic_message)
response = litellm.completion(
model="bedrock_mantle/anthropic.claude-opus-5-5",
messages=[{"role": "user", "content": "hello"}],
max_tokens=64,
aws_region_name="us-east-2",
client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler))),
)
sent = handler.call_args.args[0]
assert str(sent.url) == "https://bedrock-mantle.us-east-2.api.aws/anthropic/v1/messages"
assert sent.headers["Authorization"] == "Bearer mantle-key"
assert json.loads(sent.content) == {
"model": "anthropic.claude-opus-5-5",
"messages": [{"role": "user", "content": [{"type": "text", "text": "hello"}]}],
"max_tokens": 64,
"anthropic_version": "bedrock-2023-05-31",
}
assert response.choices[0].message.content == "ok"
assert response._hidden_params["response_cost"] == pytest.approx(
_row_cost("bedrock_mantle/anthropic.claude-opus-5-5", 10, 5)
)
assert response._hidden_params["response_cost"] != pytest.approx(_row_cost("anthropic.claude-opus-5-5", 10, 5))
def test_claude_streaming_completion_uses_native_messages_endpoint(self, monkeypatch, local_cost_map):
from litellm.llms.custom_httpx.http_handler import HTTPHandler
monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "mantle-key")
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
handler = Mock(side_effect=_anthropic_event_stream)
stream = litellm.completion(
model="bedrock_mantle/anthropic.claude-opus-5-5",
messages=[{"role": "user", "content": "hello"}],
max_tokens=64,
stream=True,
aws_region_name="us-east-2",
client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler))),
)
assert isinstance(stream, CustomStreamWrapper)
text = "".join(chunk.choices[0].delta.content or "" for chunk in stream)
sent = handler.call_args.args[0]
assert str(sent.url) == "https://bedrock-mantle.us-east-2.api.aws/anthropic/v1/messages"
assert json.loads(sent.content)["stream"] is True
assert text == "streamed"
def test_claude_region_prefixed_model_sends_bare_model_to_that_region(self, monkeypatch, local_cost_map):
from litellm.llms.custom_httpx.http_handler import HTTPHandler
for var in (
"BEDROCK_MANTLE_API_KEY",
"AWS_BEARER_TOKEN_BEDROCK",
"BEDROCK_MANTLE_API_BASE",
"BEDROCK_MANTLE_REGION",
"AWS_REGION_NAME",
"AWS_REGION",
"AWS_PROFILE",
):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAEXAMPLE")
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "c2VjcmV0LXRlc3Qtc2VjcmV0LXRlc3Qtc2VjcmV0")
handler = Mock(side_effect=_anthropic_message)
response = litellm.completion(
model="bedrock_mantle/us-gov-west-1/anthropic.claude-opus-5-5",
messages=[{"role": "user", "content": "hello"}],
max_tokens=64,
client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler))),
)
sent = handler.call_args.args[0]
assert str(sent.url) == "https://bedrock-mantle.us-gov-west-1.api.aws/anthropic/v1/messages"
assert json.loads(sent.content)["model"] == "anthropic.claude-opus-5-5"
assert "/us-gov-west-1/bedrock/aws4_request" in sent.headers["Authorization"]
assert response._hidden_params["response_cost"] == pytest.approx(
_row_cost("bedrock_mantle/us-gov-west-1/anthropic.claude-opus-5-5", 10, 5)
)
def test_non_claude_completion_stays_on_chat_completions(self, monkeypatch, local_cost_map):
from litellm.llms.custom_httpx.http_handler import HTTPHandler
monkeypatch.setenv("BEDROCK_MANTLE_API_KEY", "mantle-key")
monkeypatch.delenv("BEDROCK_MANTLE_API_BASE", raising=False)
def respond(request: httpx.Request) -> httpx.Response:
return httpx.Response(
status_code=200,
json={
"id": "chatcmpl-test",
"object": "chat.completion",
"created": 1733529600,
"model": "openai.gpt-oss-120b",
"choices": [
{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}
],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
},
request=request,
)
handler = Mock(side_effect=respond)
response = litellm.completion(
model="bedrock_mantle/openai.gpt-oss-120b",
messages=[{"role": "user", "content": "hello"}],
aws_region_name="us-east-2",
client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(handler))),
)
sent = handler.call_args.args[0]
assert str(sent.url) == "https://bedrock-mantle.us-east-2.api.aws/v1/chat/completions"
assert response.choices[0].message.content == "ok"
@pytest.mark.parametrize("request_type", ["chat_completion", "embeddings"])
def test_supported_openai_params_follow_the_route_the_model_takes(self, request_type):
claude_params = litellm.get_supported_openai_params(
model="anthropic.claude-opus-5-5", custom_llm_provider="bedrock_mantle", request_type=request_type
)
open_weight_params = litellm.get_supported_openai_params(
model="openai.gpt-oss-120b", custom_llm_provider="bedrock_mantle", request_type=request_type
)
assert claude_params is not None and open_weight_params is not None
assert "thinking" in claude_params
assert "thinking" not in open_weight_params
class TestBedrockMantlePricing:
"""Tests that verify Bedrock Mantle uses correct AWS Bedrock pricing, not OpenAI pricing."""
@pytest.mark.parametrize(
"model_id",
[
"google.gemma-4-31b",
"google.gemma-4-26b-a4b",
"google.gemma-4-e2b",
],
)
def test_gemma_4_models_register_under_bedrock_mantle(local_cost_map, model_id):
full_model_name = f"bedrock_mantle/{model_id}"
assert full_model_name in litellm.bedrock_mantle_models
resolved_model, provider, _, _ = litellm.get_llm_provider(full_model_name)
assert provider == "bedrock_mantle"
assert resolved_model == model_id
@pytest.mark.asyncio
async def test_mantle_signing_runs_off_the_event_loop():
"""Regression for issue #40165: Mantle signs with SigV4 through a composed BaseAWSLLM, so the
off-loop gate must recognise it too, or its credential refresh blocks the loop like Bedrock's did."""
probe = EventLoopProbe()
def sign(headers: dict[str, str]) -> dict[str, str]:
request = AWSRequest(
method="POST", url="https://bedrock-mantle.us-east-1.api.aws/v1/responses", data="{}", headers=headers
)
SigV4Auth(probe.credentials(), "bedrock", "us-east-1").add_auth(request)
return dict(request.headers)
release = asyncio.create_task(probe.release_refresh_from_the_loop())
signed = await run_off_loop_if_aws(BedrockMantleChatConfig(), sign, headers={"Content-Type": "application/json"})
await release
assert "Authorization" in signed
assert probe.served_during_refresh is True
@pytest.mark.parametrize("missing", ["botocore", "unrelated_dependency"])
def test_mantle_signing_reports_only_missing_aws_dependency(missing):
config = BedrockMantleChatConfig()
failure = ModuleNotFoundError("missing dependency", name=missing)
with patch.dict("os.environ", {}, clear=True), patch("builtins.__import__", side_effect=failure):
with pytest.raises(ImportError) as error:
config.sign_request(headers={}, optional_params={}, request_data={},
api_base="https://bedrock-mantle.us-east-1.api.aws/v1/chat/completions", api_key="")
if missing == "botocore":
assert "pip install boto3" in str(error.value)
assert error.value.__cause__ is failure
else:
assert error.value is failure