Skip to content

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]

fix(bedrock): honor AWS auth params in realtime handler (#32275)

Mateo Wangc5454afc7919
diff --git a/litellm/llms/bedrock/realtime/handler.py b/litellm/llms/bedrock/realtime/handler.py
index 557ee3348d5..b48c37791c4 100644
--- a/litellm/llms/bedrock/realtime/handler.py
+++ b/litellm/llms/bedrock/realtime/handler.py
@@ -13,6 +13,7 @@ from litellm._logging import _redact_string, verbose_proxy_logger
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
from ..base_aws_llm import BaseAWSLLM
+from ..common_utils import BedrockError
from .transformation import BedrockRealtimeConfig
@@ -59,9 +60,7 @@ class BedrockRealtime(BaseAWSLLM):
InvokeModelWithBidirectionalStreamOperationInput,
)
from aws_sdk_bedrock_runtime.config import Config
- from smithy_aws_core.identity.environment import (
- EnvironmentCredentialsResolver,
- )
+ from smithy_aws_core.identity import StaticCredentialsResolver
except ImportError:
raise ImportError("Missing aws_sdk_bedrock_runtime. Install with: pip install aws-sdk-bedrock-runtime")
@@ -82,11 +81,36 @@ class BedrockRealtime(BaseAWSLLM):
verbose_proxy_logger.debug(f"Bedrock Realtime: Connecting to {endpoint_uri} with model {model}")
+ credentials = self.get_credentials(
+ aws_access_key_id=aws_access_key_id,
+ aws_secret_access_key=aws_secret_access_key,
+ aws_session_token=aws_session_token,
+ aws_region_name=aws_region_name,
+ aws_session_name=aws_session_name,
+ aws_profile_name=aws_profile_name,
+ aws_role_name=aws_role_name,
+ aws_web_identity_token=aws_web_identity_token,
+ aws_sts_endpoint=aws_sts_endpoint,
+ aws_external_id=aws_external_id,
+ )
+ if credentials is None:
+ raise BedrockError(
+ status_code=401,
+ message=(
+ "No AWS credentials found for Bedrock realtime. Set aws_* params in litellm_params "
+ "or configure credentials in the environment"
+ ),
+ )
+ frozen_credentials = credentials.get_frozen_credentials()
+
# Initialize Bedrock client with aws_sdk_bedrock_runtime
config = Config(
endpoint_uri=endpoint_uri,
region=aws_region_name,
- aws_credentials_identity_resolver=EnvironmentCredentialsResolver(),
+ aws_access_key_id=frozen_credentials.access_key,
+ aws_secret_access_key=frozen_credentials.secret_key,
+ aws_session_token=frozen_credentials.token,
+ aws_credentials_identity_resolver=StaticCredentialsResolver(),
)
bedrock_client = BedrockRuntimeClient(config=config)
diff --git a/tests/test_litellm/llms/bedrock/realtime/test_bedrock_realtime_handler.py b/tests/test_litellm/llms/bedrock/realtime/test_bedrock_realtime_handler.py
index 18e48169bc1..ddc2e026e83 100644
--- a/tests/test_litellm/llms/bedrock/realtime/test_bedrock_realtime_handler.py
+++ b/tests/test_litellm/llms/bedrock/realtime/test_bedrock_realtime_handler.py
@@ -2,12 +2,14 @@ import json
import os
import sys
import types
+from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
sys.path.insert(0, os.path.abspath("../../../../..")) # Adds the parent directory to the system path
+from litellm.llms.bedrock.common_utils import BedrockError
from litellm.llms.bedrock.realtime.handler import BedrockRealtime
from litellm.llms.bedrock.realtime.transformation import BedrockRealtimeConfig
@@ -80,6 +82,111 @@ class EndedBedrockStream:
return (None, EndedBedrockReceiver())
+class RealtimeClientWS:
+ def __init__(self):
+ self.closed = False
+
+ async def receive_text(self):
+ raise RuntimeError("client disconnected")
+
+ async def close(self, code=None, reason=None):
+ self.closed = True
+
+
+class ImmediatelyEndingBedrockStream:
+ def __init__(self):
+ self.input_stream = FakeInputStream()
+
+ async def await_output(self):
+ return (None, EndedBedrockReceiver())
+
+
+class FakeStaticCredentialsResolver:
+ pass
+
+
+class NoCredentialsBedrockRealtime(BedrockRealtime):
+ def get_credentials(self, **kwargs):
+ return None
+
+
+class StubCredentialsBedrockRealtime(BedrockRealtime):
+ def __init__(self, frozen_credentials):
+ super().__init__()
+ self.frozen_credentials = frozen_credentials
+ self.get_credentials_kwargs = None
+
+ def get_credentials(self, **kwargs):
+ self.get_credentials_kwargs = kwargs
+ return SimpleNamespace(get_frozen_credentials=lambda: self.frozen_credentials)
+
+
+def stub_aws_sdk_client(monkeypatch):
+ captured = {}
+
+ class CapturingConfig:
+ def __init__(self, **kwargs):
+ captured["config_kwargs"] = kwargs
+ self.kwargs = kwargs
+
+ class FakeOperationInput:
+ def __init__(self, model_id):
+ self.model_id = model_id
+
+ class FakeBedrockRuntimeClient:
+ def __init__(self, config):
+ captured["client_config"] = config
+
+ async def invoke_model_with_bidirectional_stream(self, operation_input):
+ captured["operation_input"] = operation_input
+ return ImmediatelyEndingBedrockStream()
+
+ package = types.ModuleType("aws_sdk_bedrock_runtime")
+ client_module = types.ModuleType("aws_sdk_bedrock_runtime.client")
+ client_module.BedrockRuntimeClient = FakeBedrockRuntimeClient
+ client_module.InvokeModelWithBidirectionalStreamOperationInput = FakeOperationInput
+ config_module = types.ModuleType("aws_sdk_bedrock_runtime.config")
+ config_module.Config = CapturingConfig
+ models_module = types.ModuleType("aws_sdk_bedrock_runtime.models")
+ models_module.BidirectionalInputPayloadPart = FakePayloadPart
+ models_module.InvokeModelWithBidirectionalStreamInputChunk = FakeInputChunk
+ package.client = client_module
+ package.config = config_module
+ package.models = models_module
+ smithy_package = types.ModuleType("smithy_aws_core")
+ identity_module = types.ModuleType("smithy_aws_core.identity")
+ identity_module.StaticCredentialsResolver = FakeStaticCredentialsResolver
+ smithy_package.identity = identity_module
+
+ stubbed_modules = {
+ "aws_sdk_bedrock_runtime": package,
+ "aws_sdk_bedrock_runtime.client": client_module,
+ "aws_sdk_bedrock_runtime.config": config_module,
+ "aws_sdk_bedrock_runtime.models": models_module,
+ "smithy_aws_core": smithy_package,
+ "smithy_aws_core.identity": identity_module,
+ }
+ for module_name, module in stubbed_modules.items():
+ monkeypatch.setitem(sys.modules, module_name, module)
+
+ for env_var in (
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN",
+ "AWS_REGION_NAME",
+ "AWS_SESSION_NAME",
+ "AWS_PROFILE_NAME",
+ "AWS_ROLE_NAME",
+ "AWS_WEB_IDENTITY_TOKEN",
+ "AWS_STS_ENDPOINT",
+ "AWS_EXTERNAL_ID",
+ ):
+ monkeypatch.delenv(env_var, raising=False)
+
+ return captured
+
+
@pytest.fixture
def stub_aws_models(monkeypatch):
package = types.ModuleType("aws_sdk_bedrock_runtime")
@@ -170,5 +277,86 @@ class TestBedrockRealtimeHandler:
assert client_ws.closed
+class TestBedrockRealtimeAwsAuth:
+ """AWS auth params passed via litellm_params must reach the Smithy client config (LIT-3923 regression)"""
+
+ @pytest.mark.asyncio
+ async def test_static_credentials_from_litellm_params_reach_smithy_config(self, stub_aws_sdk_client):
+ handler = BedrockRealtime()
+ websocket = RealtimeClientWS()
+
+ await handler.async_realtime(
+ model="amazon.nova-sonic-v1:0",
+ websocket=websocket,
+ logging_obj=MagicMock(),
+ aws_region_name="us-east-1",
+ aws_access_key_id="litellm-params-access-key",
+ aws_secret_access_key="litellm-params-secret-key",
+ aws_session_token="litellm-params-session-token",
+ )
+
+ config_kwargs = stub_aws_sdk_client["config_kwargs"]
+ assert config_kwargs["aws_access_key_id"] == "litellm-params-access-key"
+ assert config_kwargs["aws_secret_access_key"] == "litellm-params-secret-key"
+ assert config_kwargs["aws_session_token"] == "litellm-params-session-token"
+ assert isinstance(config_kwargs["aws_credentials_identity_resolver"], FakeStaticCredentialsResolver)
+ assert config_kwargs["region"] == "us-east-1"
+ assert stub_aws_sdk_client["client_config"].kwargs is config_kwargs
+ assert stub_aws_sdk_client["operation_input"].model_id == "amazon.nova-sonic-v1:0"
+ assert websocket.closed
+
+ @pytest.mark.asyncio
+ async def test_role_assumption_params_forwarded_to_get_credentials(self, stub_aws_sdk_client):
+ handler = StubCredentialsBedrockRealtime(
+ SimpleNamespace(
+ access_key="assumed-access-key",
+ secret_key="assumed-secret-key",
+ token="assumed-session-token",
+ )
+ )
+
+ await handler.async_realtime(
+ model="amazon.nova-sonic-v1:0",
+ websocket=RealtimeClientWS(),
+ logging_obj=MagicMock(),
+ aws_region_name="eu-west-1",
+ aws_role_name="arn:aws:iam::123456789012:role/nova-sonic",
+ aws_session_name="realtime-session",
+ aws_external_id="realtime-external-id",
+ )
+
+ assert handler.get_credentials_kwargs == {
+ "aws_access_key_id": None,
+ "aws_secret_access_key": None,
+ "aws_session_token": None,
+ "aws_region_name": "eu-west-1",
+ "aws_session_name": "realtime-session",
+ "aws_profile_name": None,
+ "aws_role_name": "arn:aws:iam::123456789012:role/nova-sonic",
+ "aws_web_identity_token": None,
+ "aws_sts_endpoint": None,
+ "aws_external_id": "realtime-external-id",
+ }
+ config_kwargs = stub_aws_sdk_client["config_kwargs"]
+ assert config_kwargs["aws_access_key_id"] == "assumed-access-key"
+ assert config_kwargs["aws_secret_access_key"] == "assumed-secret-key"
+ assert config_kwargs["aws_session_token"] == "assumed-session-token"
+ assert isinstance(config_kwargs["aws_credentials_identity_resolver"], FakeStaticCredentialsResolver)
+
+ @pytest.mark.asyncio
+ async def test_unresolvable_credentials_raise_clear_auth_error(self, stub_aws_sdk_client):
+ handler = NoCredentialsBedrockRealtime()
+
+ with pytest.raises(BedrockError, match="No AWS credentials found for Bedrock realtime"):
+ await handler.async_realtime(
+ model="amazon.nova-sonic-v1:0",
+ websocket=RealtimeClientWS(),
+ logging_obj=MagicMock(),
+ aws_region_name="us-east-1",
+ )
+
+ assert "config_kwargs" not in stub_aws_sdk_client
+
+
if __name__ == "__main__":
pytest.main([__file__, "-v"])