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(proxy): route realtime HTTP endpoints through router for credential resolution

Shivam Rawatef758e6a888e
diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.py
index 63c6baf9ebc..8c980f33b01 100644
--- a/litellm/proxy/route_llm_request.py
+++ b/litellm/proxy/route_llm_request.py
@@ -435,9 +435,6 @@ async def route_request(
"aget_run",
"acancel_run",
"adelete_run",
- "acreate_realtime_client_secret",
- "arealtime_calls",
- "acreate_realtime_transcription_session",
]:
# If a model is provided, get its credentials from the router
model = data.get("model")
diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.py
index a6fec4729ad..6d0759e64cd 100644
--- a/litellm/realtime_api/main.py
+++ b/litellm/realtime_api/main.py
@@ -40,6 +40,24 @@ vertex_llm_base = VertexBase()
base_llm_http_handler = BaseLLMHTTPHandler()
+def _with_resolved_session_model(session: dict[str, Any], model_name: str) -> dict[str, Any]:
+ updated = {**session}
+ if "model" in updated:
+ updated["model"] = model_name
+ flat_transcription = updated.get("input_audio_transcription")
+ if isinstance(flat_transcription, dict) and "model" in flat_transcription:
+ updated["input_audio_transcription"] = {**flat_transcription, "model": model_name}
+ audio = updated.get("audio")
+ audio_input = audio.get("input") if isinstance(audio, dict) else None
+ transcription = audio_input.get("transcription") if isinstance(audio_input, dict) else None
+ if isinstance(transcription, dict) and "model" in transcription:
+ updated["audio"] = {
+ **audio,
+ "input": {**audio_input, "transcription": {**transcription, "model": model_name}},
+ }
+ return updated
+
+
def _build_litellm_metadata(kwargs: dict) -> dict:
"""Build the litellm_metadata dict for guardrail checking (internal only, not forwarded to provider)."""
metadata: dict = {**(kwargs.get("litellm_metadata") or {})}
@@ -102,7 +120,7 @@ async def acreate_realtime_client_secret(
session=RealtimeSessionConfig(**session) if session else None,
expires_after=RealtimeExpiresAfter(**expires_after) if expires_after else None,
)
- model_name = (req.session.model if req.session is not None else None) or req.model or "gpt-4o-realtime-preview"
+ model_name = req.model or (req.session.model if req.session is not None else None) or "gpt-4o-realtime-preview"
litellm_logging_obj: LiteLLMLogging = kwargs.get("litellm_logging_obj") # type: ignore
litellm_params = GenericLiteLLMParams(**kwargs)
@@ -134,6 +152,8 @@ async def acreate_realtime_client_secret(
custom_llm_provider=custom_llm_provider,
)
request_data = req.model_dump(exclude_none=True, exclude={"model"})
+ if isinstance(request_data.get("session"), dict):
+ request_data["session"] = _with_resolved_session_model(request_data["session"], model_name)
return await base_llm_http_handler.async_realtime_client_secret_handler(
api_base=resolved_api_base,
api_key=resolved_api_key,
@@ -249,6 +269,8 @@ async def arealtime_calls(
dynamic_api_key=dynamic_api_key,
litellm_params=litellm_params,
)
+ if session is not None:
+ session = _with_resolved_session_model(session, model_name)
litellm_logging_obj.update_from_kwargs(
kwargs=kwargs,
model=model_name,
diff --git a/litellm/router.py b/litellm/router.py
index 2d66bc3158d..d776a45b4b8 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -1114,6 +1114,13 @@ class Router:
self.adelete_responses = self.factory_function(litellm.adelete_responses, call_type="adelete_responses")
self.alist_input_items = self.factory_function(litellm.alist_input_items, call_type="alist_input_items")
self._arealtime = self.factory_function(litellm._arealtime, call_type="_arealtime")
+ self.acreate_realtime_client_secret = self.factory_function(
+ litellm.acreate_realtime_client_secret, call_type="acreate_realtime_client_secret"
+ )
+ self.arealtime_calls = self.factory_function(litellm.arealtime_calls, call_type="arealtime_calls")
+ self.acreate_realtime_transcription_session = self.factory_function(
+ litellm.acreate_realtime_transcription_session, call_type="acreate_realtime_transcription_session"
+ )
self._aresponses_websocket = self.factory_function(
litellm._aresponses_websocket, call_type="_aresponses_websocket"
)
@@ -5346,6 +5353,9 @@ class Router:
"afile_delete",
"afile_content",
"_arealtime",
+ "acreate_realtime_client_secret",
+ "arealtime_calls",
+ "acreate_realtime_transcription_session",
"_aresponses_websocket",
"acreate_fine_tuning_job",
"acancel_fine_tuning_job",
@@ -5585,6 +5595,16 @@ class Router:
original_function=original_function,
**kwargs,
)
+ elif call_type in (
+ "acreate_realtime_client_secret",
+ "arealtime_calls",
+ "acreate_realtime_transcription_session",
+ ):
+ return await self._ageneric_api_call_with_fallbacks(
+ original_function=original_function,
+ client=client,
+ **kwargs,
+ )
elif call_type in (
"anthropic_messages",
"_arealtime",
diff --git a/tests/test_litellm/proxy/test_route_llm_request.py b/tests/test_litellm/proxy/test_route_llm_request.py
index 47dc6e6d37d..54565d6263b 100644
--- a/tests/test_litellm/proxy/test_route_llm_request.py
+++ b/tests/test_litellm/proxy/test_route_llm_request.py
@@ -3,9 +3,7 @@ import sys
import pytest
-sys.path.insert(
- 0, os.path.abspath("../../..")
-) # Adds the parent directory to the system path
+sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system path
from unittest.mock import MagicMock
@@ -169,9 +167,7 @@ async def test_route_request_no_model_required_with_router_settings_and_no_route
"messages": [{"role": "user", "content": "what llm are you"}],
}
- with patch.object(
- litellm, "acompletion", return_value="fake_response"
- ) as mock_completion:
+ with patch.object(litellm, "acompletion", return_value="fake_response") as mock_completion:
await route_request(data, None, "gpt-3.5-turbo", "acompletion")
mock_completion.assert_called_once_with(**data)
@@ -209,9 +205,7 @@ async def test_route_request_with_router_settings_override():
assert call_kwargs["fallbacks"] == [{"gpt-3.5-turbo": ["gpt-4"]}]
assert call_kwargs["num_retries"] == 5
assert call_kwargs["timeout"] == 30
- assert call_kwargs["model_group_retry_policy"] == {
- "gpt-3.5-turbo": {"RateLimitErrorRetries": 3}
- }
+ assert call_kwargs["model_group_retry_policy"] == {"gpt-3.5-turbo": {"RateLimitErrorRetries": 3}}
# Verify unsupported settings were NOT merged
assert "routing_strategy" not in call_kwargs
assert "model_group_alias" not in call_kwargs
@@ -292,9 +286,7 @@ def test_mock_testing_kwarg_names_matches_dataclass():
from litellm.proxy.route_llm_request import _MOCK_TESTING_KWARG_NAMES
from litellm.types.router import MockRouterTestingParams
- assert set(_MOCK_TESTING_KWARG_NAMES) == {
- f.name for f in fields(MockRouterTestingParams)
- }
+ assert set(_MOCK_TESTING_KWARG_NAMES) == {f.name for f in fields(MockRouterTestingParams)}
@pytest.mark.asyncio
@@ -329,9 +321,7 @@ async def test_route_request_strips_mock_testing_flags(mock_flag):
assert mock_flag not in data
- "route_type", ["agenerate_content", "agenerate_content_stream"]
-)
[email protected]("route_type", ["agenerate_content", "agenerate_content_stream"])
@pytest.mark.asyncio
async def test_route_request_maps_generation_config_for_google_routes(route_type):
"""For Google generate_content routes, route_request must rename
@@ -359,9 +349,7 @@ async def test_route_request_maps_generation_config_for_google_routes(route_type
assert call_kwargs["config"]["imageConfig"]["imageSize"] == "4K"
- "route_type", ["agenerate_content", "agenerate_content_stream"]
-)
[email protected]("route_type", ["agenerate_content", "agenerate_content_stream"])
@pytest.mark.asyncio
async def test_route_request_preserves_existing_config_for_google_routes(route_type):
"""If the caller already supplies `config`, route_request must not
@@ -379,3 +367,180 @@ async def test_route_request_preserves_existing_config_for_google_routes(route_t
call_kwargs = getattr(llm_router, route_type).call_args[1]
assert call_kwargs["config"] == {"existing": True}
+
+
+async def _invoke_realtime_route(
+ data: dict,
+ llm_router,
+ route_type: str = "acreate_realtime_client_secret",
+):
+ llm_call = await route_request(data, llm_router, None, route_type)
+ return await llm_call
+
+
+def openai_realtime_credential():
+ import litellm
+ from litellm.types.utils import CredentialItem
+
+ litellm.credential_list = [
+ CredentialItem(
+ credential_name="openai-realtime-cred",
+ credential_info={"custom_llm_provider": "openai"},
+ credential_values={"api_key": "resolved-credential-key"},
+ )
+ ]
+ yield
+ litellm.credential_list = []
+
+
+async def test_route_request_realtime_wildcard_model_resolves_credentials(
+ monkeypatch,
+):
+ """
+ POST /realtime/client_secrets with a request model like openai/gpt-realtime
+ must match an openai/* deployment and forward its api_key upstream.
+ """
+ import httpx
+ import litellm
+ from unittest.mock import AsyncMock, patch
+
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "openai/*",
+ "litellm_params": {
+ "model": "openai/*",
+ "api_key": "wildcard-realtime-key",
+ },
+ }
+ ]
+ )
+ with patch(
+ "litellm.realtime_api.main.base_llm_http_handler.async_realtime_client_secret_handler",
+ new_callable=AsyncMock,
+ ) as mock_handler:
+ mock_handler.return_value = httpx.Response(200, json={"value": "ephemeral"})
+ await _invoke_realtime_route(
+ {"model": "openai/gpt-realtime"},
+ router,
+ )
+
+ assert mock_handler.call_args.kwargs["api_key"] == "wildcard-realtime-key"
+
+
+async def test_route_request_realtime_team_scoped_model_resolves_credentials(
+ monkeypatch,
+):
+ """
+ Team-scoped deployments (team_public_model_name) must be selected when
+ user_api_key_team_id is present, same as /chat/completions.
+ """
+ import httpx
+ import litellm
+ from unittest.mock import AsyncMock, patch
+
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "internal-realtime",
+ "litellm_params": {
+ "model": "openai/gpt-realtime",
+ "api_key": "team-realtime-key",
+ },
+ "model_info": {
+ "team_id": "team-a",
+ "team_public_model_name": "team-realtime",
+ },
+ }
+ ]
+ )
+ with patch(
+ "litellm.realtime_api.main.base_llm_http_handler.async_realtime_client_secret_handler",
+ new_callable=AsyncMock,
+ ) as mock_handler:
+ mock_handler.return_value = httpx.Response(200, json={"value": "ephemeral"})
+ await _invoke_realtime_route(
+ {
+ "model": "team-realtime",
+ "metadata": {"user_api_key_team_id": "team-a"},
+ },
+ router,
+ )
+
+ assert mock_handler.call_args.kwargs["api_key"] == "team-realtime-key"
+
+
+async def test_route_request_realtime_litellm_credential_name_resolves_api_key(
+ openai_realtime_credential,
+ monkeypatch,
+):
+ """
+ litellm_credential_name on a wildcard deployment must resolve to the stored
+ api_key when routing acreate_realtime_client_secret through the router.
+ """
+ import httpx
+ import litellm
+ from unittest.mock import AsyncMock, patch
+
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "openai/*",
+ "litellm_params": {
+ "model": "openai/*",
+ "litellm_credential_name": "openai-realtime-cred",
+ },
+ }
+ ]
+ )
+ with patch(
+ "litellm.realtime_api.main.base_llm_http_handler.async_realtime_client_secret_handler",
+ new_callable=AsyncMock,
+ ) as mock_handler:
+ mock_handler.return_value = httpx.Response(200, json={"value": "ephemeral"})
+ await _invoke_realtime_route({"model": "openai/gpt-realtime"}, router)
+
+ assert mock_handler.call_args.kwargs["api_key"] == "resolved-credential-key"
+
+
+async def test_route_request_realtime_unresolvable_model_raises_not_found(
+ monkeypatch,
+):
+ """
+ An unknown model must not silently fall through to litellm with an empty
+ OPENAI_API_KEY env var.
+ """
+ import litellm
+ from unittest.mock import AsyncMock, patch
+
+ from litellm.proxy.route_llm_request import ProxyModelNotFoundError
+
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "other-model",
+ "litellm_params": {"model": "openai/gpt-4", "api_key": "other-key"},
+ }
+ ]
+ )
+ with patch(
+ "litellm.realtime_api.main.base_llm_http_handler.async_realtime_client_secret_handler",
+ new_callable=AsyncMock,
+ ) as mock_handler:
+ with pytest.raises(ProxyModelNotFoundError):
+ await _invoke_realtime_route({"model": "nonexistent-realtime-model"}, router)
+
+ mock_handler.assert_not_called()