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
refactor(azure/realtime): keep auth header build within lint budgets after merge
Devin AI5470645f87d1
diff --git a/litellm/llms/azure/realtime/handler.py b/litellm/llms/azure/realtime/handler.pyindex 70e39f47d63..88492ef996e 100644--- a/litellm/llms/azure/realtime/handler.py+++ b/litellm/llms/azure/realtime/handler.py@@ -4,6 +4,8 @@ This file contains the calling Azure OpenAI's `/openai/realtime` endpoint.This requires websockets, and is currently only supported on LiteLLM Proxy."""+from collections.abc import Mapping+from types import MappingProxyTypefrom typing import Any, Final, castfrom litellm._logging import _redact_string, verbose_proxy_logger@@ -31,15 +33,15 @@ async def forward_messages(client_ws: Any, backend_ws: Any):class AzureOpenAIRealtime(AzureChatCompletion):@staticmethod- def get_auth_headers(api_key: str | None, azure_ad_token: str | None) -> dict[str, str]:+ def get_auth_headers(api_key: str | None, azure_ad_token: str | None) -> Mapping[str, str]:"""Build the websocket handshake auth headers, preferring a static api-key and falling back toan Azure AD (Entra ID) bearer token. Never sends both."""if api_key:- return {"api-key": api_key}+ return MappingProxyType({"api-key": api_key})if azure_ad_token:- return {"Authorization": f"Bearer {azure_ad_token}"}+ return MappingProxyType({"Authorization": f"Bearer {azure_ad_token}"})raise ValueError("Missing Azure credentials for the realtime endpoint. Set an api_key, or configure Azure AD auth ""(azure_ad_token, tenant_id/client_id/client_secret, or a managed identity)"@@ -132,7 +134,7 @@ class AzureOpenAIRealtime(AzureChatCompletion):query_params=query_params,)- auth_headers = self.get_auth_headers(api_key=api_key, azure_ad_token=azure_ad_token)+ auth_headers: Final = self.get_auth_headers(api_key=api_key, azure_ad_token=azure_ad_token)try:ssl_context: Final = get_shared_realtime_ssl_context()diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.pyindex 8933d5e4506..e5f6c8328f4 100644--- a/litellm/realtime_api/main.py+++ b/litellm/realtime_api/main.py@@ -2,6 +2,8 @@import asyncioimport os+from collections.abc import Mapping+from types import MappingProxyTypefrom typing import Any, Final, Literal, castimport litellm@@ -45,6 +47,7 @@ bedrock_realtime: Final = BedrockRealtime()xai_realtime: Final = XAIRealtime()vertex_llm_base: Final = VertexBase()base_llm_http_handler = BaseLLMHTTPHandler()+_EMPTY_MODEL_PARAMS: Final[Mapping[str, Any]] = MappingProxyType({})def _with_resolved_session_model(session: dict[str, Any], model_name: str) -> dict[str, Any]:@@ -412,10 +415,8 @@ async def _arealtime(if realtime_protocol is None and (query_params or {}).get("intent") == "transcription":realtime_protocol = "GA"realtime_protocol = realtime_protocol or "beta"- resolved_azure_ad_token = (- None- if api_key- else get_azure_ad_token(GenericLiteLLMParams(**{**kwargs, "azure_ad_token": azure_ad_token}))+ resolved_azure_ad_token: Final = (+ None if api_key else get_azure_ad_token(GenericLiteLLMParams(**kwargs, azure_ad_token=azure_ad_token)))await azure_realtime.async_realtime(model=model,@@ -556,6 +557,17 @@ async def _arealtime(raise ValueError(f"Unsupported model: {model}")+def _realtime_health_check_auth_headers(+ custom_llm_provider: str, api_key: str | None, model_params: Mapping[str, Any]+) -> Mapping[str, str | None]:+ if custom_llm_provider != "azure":+ return MappingProxyType({"api-key": api_key})+ return azure_realtime.get_auth_headers(+ api_key=api_key,+ azure_ad_token=(None if api_key else get_azure_ad_token(GenericLiteLLMParams(**model_params))),+ )++async def _realtime_health_check(model: str,custom_llm_provider: str,@@ -584,7 +596,11 @@ async def _realtime_health_check(import websocketsurl: str | None = None- auth_headers: dict[str, str | None] = {"api-key": api_key}+ auth_headers: Final = _realtime_health_check_auth_headers(+ custom_llm_provider=custom_llm_provider,+ api_key=api_key,+ model_params=model_params or _EMPTY_MODEL_PARAMS,+ )if custom_llm_provider == "azure":url = azure_realtime._construct_url(api_base=api_base or "",@@ -592,13 +608,6 @@ async def _realtime_health_check(api_version=api_version or "2024-10-01-preview",realtime_protocol=realtime_protocol,)- azure_litellm_params = GenericLiteLLMParams(**(model_params or {}))- auth_headers = dict(- azure_realtime.get_auth_headers(- api_key=api_key,- azure_ad_token=(None if api_key else get_azure_ad_token(azure_litellm_params)),- )- )elif custom_llm_provider == "openai":url = openai_realtime._construct_url(api_base=api_base or "https://api.openai.com/",diff --git a/tests/test_litellm/llms/azure/realtime/test_azure_realtime_handler.py b/tests/test_litellm/llms/azure/realtime/test_azure_realtime_handler.pyindex 570843da7a8..7d24e604569 100644--- a/tests/test_litellm/llms/azure/realtime/test_azure_realtime_handler.py+++ b/tests/test_litellm/llms/azure/realtime/test_azure_realtime_handler.py@@ -590,7 +590,9 @@ async def test_async_realtime_uses_bearer_token_when_no_api_key():"websockets.connect",return_value=_DummyAsyncContextManager(mock_backend_ws),) as mock_ws_connect,- patch("litellm.llms.azure.realtime.handler.RealTimeStreaming") as mock_realtime_streaming,+ patch( # test-quality-ok: handler owns the streaming loop, only the handshake headers are under test+ "litellm.llms.azure.realtime.handler.RealTimeStreaming"+ ) as mock_realtime_streaming,):mock_realtime_streaming.return_value.bidirectional_forward = AsyncMock()