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
fix: tested e2e implementation and added sample config.
abi_jey98344417ab30
diff --git a/litellm/llms/azure/realtime/handler.py b/litellm/llms/azure/realtime/handler.pyindex 14f772ac074..0dc42dad43e 100644--- a/litellm/llms/azure/realtime/handler.py+++ b/litellm/llms/azure/realtime/handler.py@@ -28,57 +28,38 @@ async def forward_messages(client_ws: Any, backend_ws: Any):class AzureOpenAIRealtime(AzureChatCompletion):- def _get_realtime_protocol(self) -> str:- """Return the configured realtime protocol.-- Supported values (case-insensitive):- - "beta" -> use legacy `/openai/realtime` (current default)- - "v1" -> use `/openai/v1/realtime`- - "ga" -> alias for "v1" (GA path is v1)-- If the parameter is missing or invalid, we fall back to the current- behavior for full backwards compatibility.- """-- # `litellm_params` is the standard place to configure provider-specific- # behavior. We keep this defensive in case the attribute isn't set.- params: Any = getattr(self, "litellm_params", None)- if not isinstance(params, dict):- return "beta"-- value = params.get("realtime_protocol")- if not isinstance(value, str):- return "beta"-- value_normalized = value.lower()- if value_normalized in {"v1", "ga"}:- return "v1"-- # Treat anything else (including explicit "beta") as current default- return "beta"-def _construct_url(self,api_base: str,model: str,api_version: str,+ realtime_protocol: Optional[str] = None,) -> str:- """Construct the websocket URL for Azure OpenAI realtime.-- Example default output (beta / legacy behavior):- "wss://my-endpoint-sweden-berri992.openai.azure.com/openai/realtime?api-version=2024-10-01-preview&deployment=gpt-4o-realtime-preview";-- When `realtime_protocol` is set to "v1" or "GA" via `litellm_params`,- this switches to `/openai/v1/realtime`."""-+ Construct Azure realtime WebSocket URL.++ Args:+ api_base: Azure API base URL (will be converted from https:// to wss://)+ model: Model deployment name+ api_version: Azure API version+ realtime_protocol: Protocol version to use:+ - "GA" or "v1": Uses /openai/v1/realtime (GA path)+ - "beta" or None: Uses /openai/realtime (beta path, default)++ Returns:+ WebSocket URL string++ Examples:+ beta/default: "wss://.../openai/realtime?api-version=2024-10-01-preview&deployment=gpt-4o-realtime-preview"+ GA/v1: "wss://.../openai/v1/realtime?api-version=2024-10-01-preview&deployment=gpt-4o-realtime-preview"+ """api_base = api_base.replace("https://", "wss://")- protocol = self._get_realtime_protocol()- if protocol == "v1":+ # Determine path based on realtime_protocol+ if realtime_protocol in ("GA", "v1"):path = "/openai/v1/realtime"else:- # default / beta behavior+ # Default to beta path for backwards compatibilitypath = "/openai/realtime"return f"{api_base}{path}?api-version={api_version}&deployment={model}"@@ -94,6 +75,7 @@ class AzureOpenAIRealtime(AzureChatCompletion):azure_ad_token: Optional[str] = None,client: Optional[Any] = None,timeout: Optional[float] = None,+ realtime_protocol: Optional[str] = None,):import websocketsfrom websockets.asyncio.client import ClientConnection@@ -103,7 +85,9 @@ class AzureOpenAIRealtime(AzureChatCompletion):if api_version is None:raise ValueError("api_version is required for Azure OpenAI calls")- url = self._construct_url(api_base, model, api_version)+ url = self._construct_url(+ api_base, model, api_version, realtime_protocol=realtime_protocol+ )try:ssl_context = get_shared_realtime_ssl_context()diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.pyindex 93d6269b517..e73004c5e1f 100644--- a/litellm/realtime_api/main.py+++ b/litellm/realtime_api/main.py@@ -102,16 +102,27 @@ async def _arealtime(or get_secret_str("AZURE_API_KEY"))+ api_version = (+ api_version+ or litellm_params.api_version+ or "2024-10-01-preview"+ )++ realtime_protocol = (+ kwargs.get("realtime_protocol")+ or "beta"+ )await azure_realtime.async_realtime(model=model,websocket=websocket,api_base=api_base,api_key=api_key,- api_version="2024-10-01-preview",+ api_version=api_version,azure_ad_token=None,client=None,timeout=timeout,logging_obj=litellm_logging_obj,+ realtime_protocol=realtime_protocol,)elif _custom_llm_provider == "openai":api_base = (@@ -148,6 +159,7 @@ async def _realtime_health_check(api_key: Optional[str],api_base: Optional[str] = None,api_version: Optional[str] = None,+ realtime_protocol: Optional[str] = None,):"""Health check for realtime API - tries connection to the realtime API websocket@@ -158,6 +170,7 @@ async def _realtime_health_check(api_version: Optional[str] - api versionapi_key: str - api keycustom_llm_provider: str - custom llm provider+ realtime_protocol: Optional[str] - protocol version ("GA"/"v1" for GA path, "beta"/None for beta path)Returns:bool - True if connection is successful, False otherwise@@ -172,6 +185,7 @@ async def _realtime_health_check(api_base=api_base or "",model=model,api_version=api_version or "2024-10-01-preview",+ realtime_protocol=realtime_protocol,)elif custom_llm_provider == "openai":url = openai_realtime._construct_url(diff --git a/proxy_server_config.yaml b/proxy_server_config.yamlindex 02edb07ebf3..ba18512bd89 100644--- a/proxy_server_config.yaml+++ b/proxy_server_config.yaml@@ -98,6 +98,17 @@ model_list:litellm_params:model: openai/*api_key: os.environ/OPENAI_API_KEY+ - model_name: realtime-v1+ litellm_params:+ model: azure/gpt-realtime-20250828-standard+ api_version: "2025-08-28"+ realtime_protocol: GA # Possible values: "GA"/ "v1", "beta"++ - model_name: realtime-beta+ litellm_params:+ model: azure/gpt-realtime-20250828-standard+ api_version: 2025-04-01-preview+# provider specific wildcard routing@@ -179,8 +190,8 @@ finetune_settings:# for /files endpointsfiles_settings:- custom_llm_provider: azure- api_base: os.environ/AZURE_API_BASE- api_key: os.environ/AZURE_API_KEY+ api_base: my-azure-endpoint.openai.azure.com+ api_key: my-azure-api-keyapi_version: "2023-03-15-preview"- custom_llm_provider: openaiapi_key: os.environ/OPENAI_API_KEY@@ -194,7 +205,7 @@ router_settings:model_group_alias: {"my-special-fake-model-alias-name": "fake-openai-endpoint-3"}general_settings:- master_key: sk-1234 # [OPTIONAL] Use to enforce auth on proxy. See - https://docs.litellm.ai/docs/proxy/virtual_keys+ master_key: sk-PASS # [OPTIONAL] Use to enforce auth on proxy. See - https://docs.litellm.ai/docs/proxy/virtual_keysstore_model_in_db: Trueproxy_budget_rescheduler_min_time: 60proxy_budget_rescheduler_max_time: 64@@ -203,7 +214,7 @@ general_settings:# background_health_checks: true# use_shared_health_check: true# health_check_interval: 30- # database_url: "postgresql://<user>:<password>@<host>:<port>/<dbname>" # [OPTIONAL] use for token-based auth to proxy+ database_url: "postgresql://postgres:[email protected]/litellm?ssl=disable" # [OPTIONAL] use for token-based auth to proxypass_through_endpoints:- path: "/v1/rerank" # route you want to add to LiteLLM Proxy Serverdiff --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 1446bc3df79..ca8d01e158f 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@@ -73,57 +73,186 @@ async def test_async_realtime_uses_max_size_parameter():@pytest.mark.asyncio-async def test_construct_url_uses_legacy_realtime_by_default():- """By default we should keep using `/openai/realtime` (beta behavior)."""+async def test_construct_url_default_beta_protocol():+ """+ Test that _construct_url uses /openai/realtime (beta) by default.+ This maintains backwards compatibility.+ """+ from litellm.llms.azure.realtime.handler import AzureOpenAIRealtime++ handler = AzureOpenAIRealtime()+ url = handler._construct_url(+ api_base="https://my-endpoint.openai.azure.com",+ model="gpt-4o-realtime-preview",+ api_version="2024-10-01-preview",+ )++ assert url.startswith("wss://my-endpoint.openai.azure.com/openai/realtime?")+ assert "/openai/realtime?" in url+ assert "/openai/v1/realtime" not in url+ assert "api-version=2024-10-01-preview" in url+ assert "deployment=gpt-4o-realtime-preview" in url+++async def test_construct_url_beta_protocol_explicit():+ """+ Test that realtime_protocol='beta' explicitly uses /openai/realtime.+ """+ from litellm.llms.azure.realtime.handler import AzureOpenAIRealtime+ handler = AzureOpenAIRealtime()+ url = handler._construct_url(+ api_base="https://my-endpoint.openai.azure.com",+ model="gpt-4o-realtime-preview",+ api_version="2024-10-01-preview",+ realtime_protocol="beta",+ )++ assert "/openai/realtime?" in url+ assert "/openai/v1/realtime" not in url+++async def test_construct_url_ga_protocol():+ """+ Test that realtime_protocol='GA' uses /openai/v1/realtime (GA path).+ """+ from litellm.llms.azure.realtime.handler import AzureOpenAIRealtime++ handler = AzureOpenAIRealtime()+ url = handler._construct_url(+ api_base="https://my-endpoint.openai.azure.com",+ model="gpt-4o-realtime-preview",+ api_version="2024-10-01-preview",+ realtime_protocol="GA",+ )++ assert url.startswith("wss://my-endpoint.openai.azure.com/openai/v1/realtime?")+ assert "/openai/v1/realtime?" in url+ # Ensure it doesn't have both paths+ assert url.count("/realtime") == 1+ assert "api-version=2024-10-01-preview" in url+ assert "deployment=gpt-4o-realtime-preview" in url+++async def test_construct_url_v1_protocol():+ """+ Test that realtime_protocol='v1' also uses /openai/v1/realtime.+ """+ from litellm.llms.azure.realtime.handler import AzureOpenAIRealtime++ handler = AzureOpenAIRealtime()+ url = handler._construct_url(+ api_base="https://my-endpoint.openai.azure.com",+ model="gpt-4o-realtime-preview",+ api_version="2024-10-01-preview",+ realtime_protocol="v1",+ )++ assert "/openai/v1/realtime?" in url+ assert url.count("/realtime") == 1+++async def test_async_realtime_uses_ga_protocol_end_to_end():+ """+ Test that realtime_protocol='GA' flows through async_realtime to construct the correct URL.+ This is the end-to-end test ensuring the parameter is properly used.+ """from litellm.llms.azure.realtime.handler import AzureOpenAIRealtimehandler = AzureOpenAIRealtime()api_base = "https://my-endpoint.openai.azure.com"+ api_key = "test-key"api_version = "2024-10-01-preview"model = "gpt-4o-realtime-preview"- url = handler._construct_url(api_base=api_base, model=model, api_version=api_version)+ dummy_websocket = AsyncMock()+ dummy_logging_obj = MagicMock()+ mock_backend_ws = AsyncMock()- assert url.startswith("wss://my-endpoint.openai.azure.com")- assert "/openai/realtime" in url- assert "/openai/v1/realtime" not in url+ class DummyAsyncContextManager:+ def __init__(self, value):+ self.value = value+ async def __aenter__(self):+ return self.value+ async def __aexit__(self, exc_type, exc, tb):+ return None+ with patch("websockets.connect", return_value=DummyAsyncContextManager(mock_backend_ws)) as mock_ws_connect, \+ patch("litellm.llms.azure.realtime.handler.RealTimeStreaming") as mock_realtime_streaming:++ mock_streaming_instance = MagicMock()+ mock_realtime_streaming.return_value = mock_streaming_instance+ mock_streaming_instance.bidirectional_forward = AsyncMock()-async def test_construct_url_uses_v1_when_realtime_protocol_v1_or_ga():- """Setting `realtime_protocol` to v1/GA should switch to `/openai/v1/realtime`."""+ await handler.async_realtime(+ model=model,+ websocket=dummy_websocket,+ logging_obj=dummy_logging_obj,+ api_base=api_base,+ api_key=api_key,+ api_version=api_version,+ realtime_protocol="GA",+ )++ # Verify websockets.connect was called with GA URL+ mock_ws_connect.assert_called_once()+ called_url = mock_ws_connect.call_args[0][0]+ assert "/openai/v1/realtime" in called_url+ assert called_url.startswith("wss://")+ assert "api-version=2024-10-01-preview" in called_url+ assert "deployment=gpt-4o-realtime-preview" in called_url++async def test_async_realtime_default_maintains_backwards_compatibility():+ """+ Test that not passing realtime_protocol maintains the original beta behavior.+ This ensures backwards compatibility for existing deployments.+ """from litellm.llms.azure.realtime.handler import AzureOpenAIRealtime+ handler = AzureOpenAIRealtime()api_base = "https://my-endpoint.openai.azure.com"+ api_key = "test-key"api_version = "2024-10-01-preview"model = "gpt-4o-realtime-preview"- # Helper to construct handler URL with a specific realtime_protocol.- # We avoid mutating handler attributes directly since type checkers don't- # know about `litellm_params` on this class. Instead, we patch the- # `_get_realtime_protocol` helper which is what `_construct_url` uses.-- # v1 -> /openai/v1/realtime- handler_v1 = AzureOpenAIRealtime()- with patch.object(handler_v1, "_get_realtime_protocol", return_value="v1"):- url_v1 = handler_v1._construct_url(api_base=api_base, model=model, api_version=api_version)- assert "/openai/v1/realtime" in url_v1- assert "/openai/realtime" not in url_v1-- # GA (case-insensitive) -> /openai/v1/realtime- handler_ga = AzureOpenAIRealtime()- with patch.object(handler_ga, "_get_realtime_protocol", return_value="v1"):- url_ga = handler_ga._construct_url(api_base=api_base, model=model, api_version=api_version)- assert "/openai/v1/realtime" in url_ga- assert "/openai/realtime" not in url_ga-- # beta or any other value keeps legacy path- handler_beta = AzureOpenAIRealtime()- with patch.object(handler_beta, "_get_realtime_protocol", return_value="beta"):- url_beta = handler_beta._construct_url(api_base=api_base, model=model, api_version=api_version)- assert "/openai/realtime" in url_beta- assert "/openai/v1/realtime" not in url_beta+ dummy_websocket = AsyncMock()+ dummy_logging_obj = MagicMock()+ mock_backend_ws = AsyncMock()++ class DummyAsyncContextManager:+ def __init__(self, value):+ self.value = value+ async def __aenter__(self):+ return self.value+ async def __aexit__(self, exc_type, exc, tb):+ return None++ with patch("websockets.connect", return_value=DummyAsyncContextManager(mock_backend_ws)) as mock_ws_connect, \+ patch("litellm.llms.azure.realtime.handler.RealTimeStreaming") as mock_realtime_streaming:++ mock_streaming_instance = MagicMock()+ mock_realtime_streaming.return_value = mock_streaming_instance+ mock_streaming_instance.bidirectional_forward = AsyncMock()++ # Call without realtime_protocol parameter+ await handler.async_realtime(+ model=model,+ websocket=dummy_websocket,+ logging_obj=dummy_logging_obj,+ api_base=api_base,+ api_key=api_key,+ api_version=api_version,+ )++ # Verify it still uses the beta path+ called_url = mock_ws_connect.call_args[0][0]+ assert "/openai/realtime?" in called_url+ assert "/openai/v1/realtime" not in called_url