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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_pr36151_ws_passthrough

mateo-berri81aefe4b3c71
diff --cc litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
index 22c2a2a8f16,8c76b9d4e1b..d9c76aaeae3
--- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
@@@ -1934,83 -1972,6 +1972,101 @@@ async def openai_proxy_route
)
++def _join_url_paths(base_url: httpx.URL, path: str, custom_llm_provider: litellm.LlmProviders) -> str:
++ """
++ Properly joins a base URL with a path, preserving any existing path in the base URL.
++ """
++ # Combine paths via the shared helper so any '..' in the path cannot
++ # climb above the configured base path.
++ joined_path_str = str(
++ base_url.copy_with(path=HttpPassThroughEndpointHelpers.join_base_and_endpoint_path(base_url, path))
++ )
++
++ # Apply OpenAI-specific path handling for both branches
++ if custom_llm_provider == litellm.LlmProviders.OPENAI and "/v1/" not in joined_path_str:
++ # Insert v1 after api.openai.com for OpenAI requests
++ joined_path_str = joined_path_str.replace("api.openai.com/", "api.openai.com/v1/")
++
++ return joined_path_str
++
++
+_OPENAI_WS_ALL_MODEL_ACCESS: Final = frozenset(
+ {
+ SpecialModelNames.all_proxy_models.value,
+ SpecialModelNames.all_team_models.value,
+ "*",
+ }
+)
+
+
+def _key_has_model_restrictions(user_api_key_dict: UserAPIKeyAuth) -> bool:
+ scoped_models: Final = (*user_api_key_dict.models, *user_api_key_dict.team_models)
+ return any(str(model) not in _OPENAI_WS_ALL_MODEL_ACCESS for model in scoped_models)
+
+
[email protected]("/openai_passthrough/{endpoint:path}")
[email protected]("/openai/{endpoint:path}")
+async def openai_websocket_proxy_route(
+ websocket: WebSocket,
+ endpoint: str,
+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth_websocket)],
+) -> None:
+ """WebSocket passthrough for OpenAI prefixes (realtime / responses.connect)."""
+ if _key_has_model_restrictions(user_api_key_dict):
+ await websocket.close(
+ code=1008,
+ reason="Keys with model restrictions cannot use OpenAI websocket passthrough",
+ )
+ return
+
+ base_target_url: Final = os.getenv("OPENAI_API_BASE") or "https://api.openai.com/"
+ openai_api_key: Final = passthrough_endpoint_router.get_credentials(
+ custom_llm_provider=litellm.LlmProviders.OPENAI.value,
+ region_name=None,
+ )
+ if openai_api_key is None:
+ await websocket.close(code=1011)
+ raise ValueError("Required 'OPENAI_API_KEY' in environment to make pass-through calls to OpenAI.")
+
+ raw_path: Final = httpx.URL(endpoint).path
+ encoded_endpoint: Final = raw_path if raw_path.startswith("/") else f"/{raw_path}"
+ base_url: Final = httpx.URL(base_target_url)
- updated_url: Final = BaseOpenAIPassThroughHandler._join_url_paths(
++ updated_url: Final = _join_url_paths(
+ base_url=base_url,
+ path=encoded_endpoint,
+ custom_llm_provider=litellm.LlmProviders.OPENAI,
+ )
+ wss_base: Final = (
+ "wss://" + updated_url[len("https://") :]
+ if updated_url.startswith("https://")
+ else "ws://" + updated_url[len("http://") :]
+ if updated_url.startswith("http://")
+ else updated_url
+ )
+ query_string: Final = websocket.url.query
+ wss_target: Final = f"{wss_base}{'&' if '?' in wss_base else '?'}{query_string}" if query_string else wss_base
+ custom_headers: Final = { # mutable-ok: websocket_passthrough_request requires a plain dict of upstream headers
+ "Authorization": f"Bearer {openai_api_key}"
+ }
+
+ requested_subprotocols: Final = tuple(
+ protocol.strip()
+ for protocol in (websocket.headers.get("sec-websocket-protocol") or "").split(",")
+ if protocol.strip()
+ )
+ await websocket.accept(subprotocol=requested_subprotocols[0] if requested_subprotocols else None)
+
+ await websocket_passthrough_request(
+ websocket=websocket,
+ target=wss_target,
+ custom_headers=custom_headers,
+ user_api_key_dict=user_api_key_dict,
+ forward_headers=False,
+ endpoint=websocket.url.path,
+ accept_websocket=False,
+ )
+
+
class BaseOpenAIPassThroughHandler:
@staticmethod
async def _base_openai_pass_through_handler(
@@@ -2091,21 -2052,21 +2147,7 @@@
@staticmethod
def _join_url_paths(base_url: httpx.URL, path: str, custom_llm_provider: litellm.LlmProviders) -> str:
-- """
-- Properly joins a base URL with a path, preserving any existing path in the base URL.
-- """
-- # Combine paths via the shared helper so any '..' in the path cannot
-- # climb above the configured base path.
-- joined_path_str = str(
-- base_url.copy_with(path=HttpPassThroughEndpointHelpers.join_base_and_endpoint_path(base_url, path))
-- )
--
-- # Apply OpenAI-specific path handling for both branches
-- if custom_llm_provider == litellm.LlmProviders.OPENAI and "/v1/" not in joined_path_str:
-- # Insert v1 after api.openai.com for OpenAI requests
-- joined_path_str = joined_path_str.replace("api.openai.com/", "api.openai.com/v1/")
--
-- return joined_path_str
++ return _join_url_paths(base_url=base_url, path=path, custom_llm_provider=custom_llm_provider)
@router.api_route(
diff --cc litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
index f0845940ce8,ca35be52fad..627df3a873d
--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
@@@ -2085,8 -2091,8 +2091,8 @@@ async def websocket_passthrough_request
raw_response = await upstream_ws.recv(decode=False)
# Ensure raw_response is bytes before decoding
if isinstance(raw_response, str):
- raw_response = raw_response.encode("ascii")
- setup_response: Final[Mapping[str, object]] = json.loads(raw_response.decode("ascii"))
+ raw_response = raw_response.encode("utf-8")
- setup_response: Final = json.loads(raw_response.decode("utf-8"))
++ setup_response: Final[Mapping[str, object]] = json.loads(raw_response.decode("utf-8"))
verbose_proxy_logger.debug("Setup response: %s", setup_response)
# Extract model and provider from setup response for Vertex AI Live
diff --cc tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py
index fe470aa6500,6681558f8da..40b4dfa6d15
--- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py
+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py
@@@ -4880,78 -4879,117 +4880,194 @@@ async def test_unusable_upstream_cost_r
assert payloads[0]["total_tokens"] == 1874
+class FakeUpstreamWebSocket:
+ def __init__(self, first_frame: bytes):
+ self._first_frame = first_frame
+ self.close = AsyncMock()
+
+ async def recv(self, decode: bool = True):
+ return self._first_frame
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ raise StopAsyncIteration
+
+
+class FakeUpstreamConnect:
+ def __init__(self, upstream_ws: FakeUpstreamWebSocket):
+ self._upstream_ws = upstream_ws
+
+ async def __aenter__(self):
+ return self._upstream_ws
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+
+async def test_websocket_passthrough_forwards_non_ascii_first_frame():
+ from starlette.websockets import WebSocketState
+
+ first_frame = json.dumps(
+ {"type": "session.created", "session": {"instructions": "Hablas español, ¿sí?"}},
+ ensure_ascii=False,
+ ).encode("utf-8")
+ upstream_ws = FakeUpstreamWebSocket(first_frame)
+
+ websocket = MagicMock()
+ websocket.accept = AsyncMock()
+ websocket.send_text = AsyncMock()
+ websocket.send_bytes = AsyncMock()
+ websocket.close = AsyncMock()
+ websocket.receive = AsyncMock(return_value={"type": "websocket.disconnect"})
+ websocket.headers = {}
+ websocket.client_state = WebSocketState.CONNECTED
+
+ with (
+ patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy_logging,
+ patch(
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints.connect",
+ return_value=FakeUpstreamConnect(upstream_ws),
+ ),
+ patch(
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints.GLOBAL_LOGGING_WORKER"
+ ) as mock_worker,
+ ):
+ mock_proxy_logging.pre_call_hook = AsyncMock(return_value={})
+ mock_proxy_logging.post_call_success_hook = AsyncMock()
+ mock_proxy_logging.post_call_failure_hook = AsyncMock()
+ mock_worker.ensure_initialized_and_enqueue = MagicMock(
+ side_effect=lambda async_coroutine: async_coroutine.close()
+ )
+ await websocket_passthrough_request(
+ websocket=websocket,
+ target="wss://api.openai.com/v1/realtime?model=gpt-realtime",
+ custom_headers={"Authorization": "Bearer sk-test"},
+ user_api_key_dict=UserAPIKeyAuth(),
+ forward_headers=False,
+ endpoint="/openai/v1/realtime",
+ accept_websocket=True,
+ )
+
+ websocket.send_text.assert_awaited_once()
+ forwarded = json.loads(websocket.send_text.await_args.args[0])
+ assert forwarded["session"]["instructions"] == "Hablas español, ¿sí?"
+ assert all(call.kwargs.get("code") != 1011 for call in websocket.close.await_args_list)
++
++
+ def _passthrough_kwargs_for_reservation(
+ user_api_key_dict: UserAPIKeyAuth, parsed_body: Optional[dict] = None
+ ) -> dict:
+ mock_request = MagicMock(spec=Request)
+ mock_request.method = "POST"
+ mock_request.url = (
+ "http://0.0.0.0:4000/gemini/v1beta/models/gemini-2.5-flash:generateContent"
+ )
+ mock_request.headers = Headers({})
+
+ return HttpPassThroughEndpointHelpers._init_kwargs_for_pass_through_endpoint(
+ request=mock_request,
+ user_api_key_dict=user_api_key_dict,
+ passthrough_logging_payload=MagicMock(),
+ logging_obj=MagicMock(),
+ _parsed_body=parsed_body if parsed_body is not None else {},
+ litellm_call_id="lit-5425-call-id",
+ )
+
+
+ async def _track_cost_for_passthrough_kwargs(kwargs: dict) -> AsyncMock:
+ from datetime import datetime
+
+ from litellm.proxy.hooks.proxy_track_cost_callback import _ProxyDBLogger
+
+ callback_kwargs = {
+ **kwargs,
+ "stream": False,
+ "standard_logging_object": {
+ "response_cost": 0.002,
+ "request_tags": None,
+ },
+ }
+
+ increment_spend_counters = AsyncMock()
+ with (
+ patch("litellm.proxy.proxy_server.proxy_logging_obj") as mock_proxy_logging,
+ patch(
+ "litellm.proxy.proxy_server.increment_spend_counters",
+ increment_spend_counters,
+ ),
+ patch("litellm.proxy.proxy_server.update_cache", new_callable=AsyncMock),
+ ):
+ mock_proxy_logging.db_spend_update_writer.update_database = AsyncMock()
+ mock_proxy_logging.slack_alerting_instance.customer_spend_alert = AsyncMock()
+
+ await _ProxyDBLogger()._PROXY_track_cost_callback(
+ kwargs=callback_kwargs,
+ completion_response=None,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+
+ return increment_spend_counters
+
+
+ @pytest.mark.asyncio
+ async def test_passthrough_success_reconciles_budget_reservation():
+ """
+ A successful pass-through request must hand its pre-call budget reservation
+ to the spend-counter update so the reserved amount is reconciled down to the
+ actual cost. Without it the reservation stays in the shared Redis counter and
+ the actual cost is added on top, so the counter drifts above real spend until
+ the key falsely trips BudgetExceededError.
+ """
+ budget_reservation = {
+ "reserved_cost": 0.5,
+ "entries": [{"counter_key": "spend:key:hashed-token", "reserved_cost": 0.5}],
+ }
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-token",
+ user_id="u1",
+ budget_reservation=budget_reservation,
+ )
+
+ reservation = user_api_key_dict.budget_reservation
+ kwargs = _passthrough_kwargs_for_reservation(user_api_key_dict)
+ assert (
+ kwargs["litellm_params"]["metadata"]["user_api_key_budget_reservation"]
+ is reservation
+ )
+
+ increment_spend_counters = await _track_cost_for_passthrough_kwargs(kwargs)
+
+ increment_spend_counters.assert_awaited_once()
+ assert increment_spend_counters.await_args.kwargs["budget_reservation"] is reservation
+ assert increment_spend_counters.await_args.kwargs["budget_reservation"] == budget_reservation
+
+
+ @pytest.mark.asyncio
+ async def test_passthrough_body_cannot_forge_budget_reservation():
+ """
+ The reservation is an internal counter handle: a client-supplied metadata
+ field naming arbitrary counter keys must never reach the spend-counter
+ update, or a caller could decrement another entity's Redis counter.
+ """
+ forged = {
+ "reserved_cost": 99.0,
+ "entries": [{"counter_key": "spend:team:victim", "reserved_cost": 99.0}],
+ }
+ user_api_key_dict = UserAPIKeyAuth(api_key="hashed-token", user_id="u1")
+
+ kwargs = _passthrough_kwargs_for_reservation(
+ user_api_key_dict,
+ parsed_body={"litellm_metadata": {"user_api_key_budget_reservation": forged}},
+ )
+ assert (
+ kwargs["litellm_params"]["metadata"]["user_api_key_budget_reservation"] is None
+ )
+
+ increment_spend_counters = await _track_cost_for_passthrough_kwargs(kwargs)
+
+ increment_spend_counters.assert_awaited_once()
+ assert increment_spend_counters.await_args.kwargs["budget_reservation"] is None
diff --cc tests/test_litellm/proxy/test_openai_ws_passthrough_routes.py
index d59468dcad6,00000000000..82422d35b9f
mode 100644,000000..100644
--- a/tests/test_litellm/proxy/test_openai_ws_passthrough_routes.py
+++ b/tests/test_litellm/proxy/test_openai_ws_passthrough_routes.py
@@@ -1,155 -1,0 +1,155 @@@
+"""OpenAI passthrough must register WebSocket catch-all routes (#36088)."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from starlette.routing import WebSocketRoute
+
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (
+ openai_websocket_proxy_route,
+ router,
+)
+
+
+def test_openai_websocket_passthrough_routes_registered():
+ ws_paths = {route.path for route in router.routes if isinstance(route, WebSocketRoute)}
+ assert "/openai/{endpoint:path}" in ws_paths
+ assert "/openai_passthrough/{endpoint:path}" in ws_paths
+
+
+def _mock_websocket(path: str, query: str, headers: dict[str, str] | None = None) -> MagicMock:
+ websocket = MagicMock()
+ websocket.url.path = path
+ websocket.url.query = query
+ websocket.headers = headers or {}
+ websocket.accept = AsyncMock()
+ websocket.close = AsyncMock()
+ return websocket
+
+
[email protected]("prefix", ["openai", "openai_passthrough"])
+async def test_openai_websocket_forwards_query_and_keeps_provider_auth(prefix):
+ websocket = _mock_websocket(f"/{prefix}/v1/realtime", "model=gpt-4o-realtime-preview")
+
+ with (
+ patch(
+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.passthrough_endpoint_router.get_credentials",
+ return_value="sk-provider",
+ ),
+ patch(
- "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.BaseOpenAIPassThroughHandler._join_url_paths",
++ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints._join_url_paths",
+ return_value="https://api.openai.com/v1/realtime",
+ ),
+ patch(
+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.websocket_passthrough_request",
+ new_callable=AsyncMock,
+ ) as mock_ws,
+ ):
+ await openai_websocket_proxy_route(
+ websocket=websocket,
+ endpoint="v1/realtime",
+ user_api_key_dict=UserAPIKeyAuth(),
+ )
+
+ kwargs = mock_ws.await_args.kwargs
+ assert kwargs["target"] == "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview"
+ assert kwargs["custom_headers"] == {"Authorization": "Bearer sk-provider"}
+ assert kwargs["forward_headers"] is False
+ assert kwargs["endpoint"] == f"/{prefix}/v1/realtime"
+ assert kwargs["accept_websocket"] is False
+ websocket.accept.assert_awaited_once_with(subprotocol=None)
+ websocket.close.assert_not_awaited()
+
+
+async def test_openai_websocket_accepts_first_client_subprotocol():
+ websocket = _mock_websocket(
+ "/openai/v1/realtime",
+ "model=gpt-4o-realtime-preview",
+ headers={
+ "sec-websocket-protocol": "realtime, openai-insecure-api-key.sk-abc, openai-beta.realtime-v1"
+ },
+ )
+
+ with (
+ patch(
+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.passthrough_endpoint_router.get_credentials",
+ return_value="sk-provider",
+ ),
+ patch(
+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.websocket_passthrough_request",
+ new_callable=AsyncMock,
+ ) as mock_ws,
+ ):
+ await openai_websocket_proxy_route(
+ websocket=websocket,
+ endpoint="v1/realtime",
+ user_api_key_dict=UserAPIKeyAuth(),
+ )
+
+ websocket.accept.assert_awaited_once_with(subprotocol="realtime")
+ assert mock_ws.await_args.kwargs["accept_websocket"] is False
+ websocket.close.assert_not_awaited()
+
+
+ "user_api_key_dict",
+ [
+ UserAPIKeyAuth(models=["gpt-4o"]),
+ UserAPIKeyAuth(team_models=["gpt-4o-realtime-preview"]),
+ UserAPIKeyAuth(models=["all-team-models"], team_models=["gpt-4o"]),
+ ],
+)
+async def test_openai_websocket_rejects_model_restricted_keys(user_api_key_dict):
+ websocket = _mock_websocket("/openai/v1/realtime", "model=gpt-4o-realtime-preview")
+
+ with patch(
+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.websocket_passthrough_request",
+ new_callable=AsyncMock,
+ ) as mock_ws:
+ await openai_websocket_proxy_route(
+ websocket=websocket,
+ endpoint="v1/realtime",
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ websocket.close.assert_awaited_once()
+ assert websocket.close.await_args.kwargs["code"] == 1008
+ websocket.accept.assert_not_awaited()
+ mock_ws.assert_not_awaited()
+
+
+ "user_api_key_dict",
+ [
+ UserAPIKeyAuth(),
+ UserAPIKeyAuth(models=["all-proxy-models"]),
+ UserAPIKeyAuth(models=["*"]),
+ UserAPIKeyAuth(models=["all-team-models"], team_models=["all-proxy-models"]),
+ ],
+)
+async def test_openai_websocket_allows_unrestricted_keys(user_api_key_dict):
+ websocket = _mock_websocket("/openai/v1/responses", "")
+
+ with (
+ patch(
+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.passthrough_endpoint_router.get_credentials",
+ return_value="sk-provider",
+ ),
+ patch(
+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.websocket_passthrough_request",
+ new_callable=AsyncMock,
+ ) as mock_ws,
+ ):
+ await openai_websocket_proxy_route(
+ websocket=websocket,
+ endpoint="v1/responses",
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ mock_ws.assert_awaited_once()
+ websocket.close.assert_not_awaited()