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/main' into litellm_deepgram_listen_websocket_passthrough

yassin659b85ea8044
diff --cc litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
index 449ae48b0ef,ae123a1002e..84357df109e
--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
@@@ -8,7 -8,8 +8,8 @@@ from base64 import b64encod
from collections.abc import AsyncGenerator, Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
-from itertools import groupby
+from itertools import count, groupby
+ from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, TypedDict, cast
from urllib.parse import urlencode, urlparse
diff --cc tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py
index de13e52498f,e3e7ad618e0..6c5fdbb6b0c
--- 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
@@@ -5362,147 -5365,9 +5368,147 @@@ async def test_websocket_passthrough_do
websocket.close.assert_awaited_once_with(code=1008, reason=upstream_reason)
+DEEPGRAM_LISTEN_TARGET = "wss://api.deepgram.com/v1/listen?model=nova-3&encoding=linear16&sample_rate=16000"
+DEEPGRAM_INTERIM_FRAME = json.dumps(
+ {
+ "type": "Results",
+ "start": 0.0,
+ "duration": 1.02,
+ "is_final": False,
+ "channel": {"alternatives": [{"transcript": "hello wor", "confidence": 0.71}]},
+ }
+)
+DEEPGRAM_FINAL_FRAME = json.dumps(
+ {
+ "type": "Results",
+ "start": 0.0,
+ "duration": 2.5,
+ "is_final": True,
+ "speech_final": True,
+ "channel": {"alternatives": [{"transcript": "hello world, ¿qué tal?", "confidence": 0.98}]},
+ },
+ ensure_ascii=False,
+)
+DEEPGRAM_METADATA_FRAME = json.dumps({"type": "Metadata", "request_id": "req-1", "duration": 2.5, "channels": 1})
+
+
+async def _relay_deepgram_listen(upstream_ws, client_receive):
+ """Runs the generic relay the way the Deepgram route does and returns (client websocket, success handler mock)"""
+ websocket = _client_websocket(client_receive)
+ with (
+ _patched_websocket_passthrough_environment(upstream_ws),
+ patch( # test-quality-ok: pass_through_endpoint_logging is a module global read inside websocket_passthrough_request; there is no injection seam
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints."
+ "pass_through_endpoint_logging.pass_through_async_success_handler",
+ new=AsyncMock(),
+ ) as success_handler,
+ ):
+ await websocket_passthrough_request(
+ websocket=websocket,
+ target=DEEPGRAM_LISTEN_TARGET,
+ custom_headers={"Authorization": "Token dg-provider-key"},
+ user_api_key_dict=UserAPIKeyAuth(),
+ forward_headers=False,
+ endpoint="/deepgram/v1/listen",
+ accept_websocket=False,
+ )
+ return websocket, success_handler
+
+
+async def test_websocket_passthrough_relays_deepgram_transcript_frames_verbatim_and_keeps_them_for_billing():
+ """Interim, final and Metadata frames reach the client byte for byte (no JSON round trip, non-ASCII intact,
+ a binary frame first) and every JSON object frame is what the success handler gets to bill from."""
+ upstream_ws = FakeUpstreamWebSocket(
+ b"\x00\x01binary-first",
+ DEEPGRAM_INTERIM_FRAME,
+ "not json at all",
+ DEEPGRAM_FINAL_FRAME,
+ DEEPGRAM_METADATA_FRAME,
+ )
+
+ websocket, success_handler = await _relay_deepgram_listen(upstream_ws, _pending_receive)
+
+ assert [call.args[0] for call in websocket.send_bytes.await_args_list] == [b"\x00\x01binary-first"]
+ assert [call.args[0] for call in websocket.send_text.await_args_list] == [
+ DEEPGRAM_INTERIM_FRAME,
+ "not json at all",
+ DEEPGRAM_FINAL_FRAME,
+ DEEPGRAM_METADATA_FRAME,
+ ]
+ success_call = success_handler.call_args.kwargs
+ assert success_call["url_route"] == "/deepgram/v1/listen"
+ assert success_call["response_body"] == [
+ json.loads(DEEPGRAM_INTERIM_FRAME),
+ json.loads(DEEPGRAM_FINAL_FRAME),
+ json.loads(DEEPGRAM_METADATA_FRAME),
+ ]
+ assert success_call["httpx_response"].request.url == DEEPGRAM_LISTEN_TARGET
+ assert success_call["logging_obj"].model_call_details.get("custom_llm_provider") is None
+ websocket.close.assert_awaited_once_with()
+
+
+async def test_websocket_passthrough_sends_deepgram_audio_bytes_and_control_text_upstream_unchanged():
+ upstream_ws = RecordingUpstreamWebSocket()
+ audio_chunk = bytes(range(256)) * 4
+ close_stream = json.dumps({"type": "CloseStream"})
+
+ await _relay_deepgram_listen(
+ upstream_ws,
+ AsyncMock(
+ side_effect=[
+ {"type": "websocket.receive", "bytes": audio_chunk},
+ {"type": "websocket.receive", "text": close_stream},
+ {"type": "websocket.disconnect"},
+ ]
+ ),
+ )
+
+ assert [call.args[0] for call in upstream_ws.send.await_args_list] == [audio_chunk, close_stream]
+ assert isinstance(upstream_ws.send.await_args_list[0].args[0], bytes)
+ upstream_ws.close.assert_awaited_once()
+
+
+async def test_websocket_passthrough_vertex_live_setup_ack_names_the_model_but_is_not_billed_as_usage():
+ """Vertex Live keeps its special first frame: the setup acknowledgement is forwarded verbatim, read for the
+ model, and left out of the frames the usage handler sees; later frames are kept as before."""
+ setup_ack = json.dumps(
+ {"setupComplete": {}, "model": "projects/p/locations/global/publishers/google/models/gemini-live-2.5-flash"}
+ )
+ server_content = json.dumps({"serverContent": {"turnComplete": True}, "usageMetadata": {"totalTokenCount": 12}})
+ upstream_ws = FakeUpstreamWebSocket(setup_ack, server_content)
+ websocket = _client_websocket(_pending_receive)
+
+ with (
+ _patched_websocket_passthrough_environment(upstream_ws),
+ patch( # test-quality-ok: pass_through_endpoint_logging is a module global read inside websocket_passthrough_request; there is no injection seam
+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints."
+ "pass_through_endpoint_logging.pass_through_async_success_handler",
+ new=AsyncMock(),
+ ) as success_handler,
+ ):
+ await websocket_passthrough_request(
+ websocket=websocket,
+ target="wss://aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent",
+ custom_headers={"Authorization": "Bearer token"},
+ user_api_key_dict=UserAPIKeyAuth(),
+ forward_headers=False,
+ endpoint="/vertex_ai/live",
+ accept_websocket=False,
+ )
+
+ assert [call.args[0] for call in websocket.send_text.await_args_list] == [setup_ack, server_content]
+ success_call = success_handler.call_args.kwargs
+ assert success_call["response_body"] == [json.loads(server_content)]
+ assert success_call["logging_obj"].model == "gemini-live-2.5-flash"
+ assert success_call["logging_obj"].model_call_details["custom_llm_provider"] == "vertex_ai_language_models"
+
+
def _passthrough_kwargs_for_reservation(
user_api_key_dict: UserAPIKeyAuth,
- parsed_body: Optional[dict] = None,
+ parsed_body: dict | None = None,
user_defined_route: bool = False,
) -> dict:
mock_request = MagicMock(spec=Request)