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
Merge remote-tracking branch 'origin/main' into pr-41560
ryan-crabbe-berriddb236b7e26a
diff --cc litellm/llms/custom_httpx/llm_http_handler.pyindex 50420ab3301,7f1ff5298ba..db821f42a90--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@@ -1,12 -1,23 +1,24 @@@import asyncioimport jsonimport ssl- from collections.abc import AsyncIterator, Coroutine, Iterator, Mapping, Sequence+ from collections.abc import AsyncGenerator, AsyncIterator, Coroutine, Iterator, Mapping, Sequencefrom contextlib import asynccontextmanagerfrom functools import lru_cache+from itertools import chainfrom types import MappingProxyType, ModuleType- from typing import TYPE_CHECKING, Any, Final, Literal, Optional, TypedDict, TypeVar, Union, cast, get_type_hints+ from typing import (+ TYPE_CHECKING,+ Any,+ Final,+ Literal,+ NamedTuple,+ Optional,+ TypedDict,+ TypeVar,+ Union,+ cast,+ get_type_hints,+ )from urllib.parse import parse_qs, urlencode, urlparse, urlunparseimport httpxdiff --cc tests/test_litellm/llms/custom_httpx/test_llm_http_handler.pyindex 5d6060c7666,420adc9338e..fa4b7439dd8--- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py+++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py@@@ -3715,45 -3863,147 +3863,191 @@@ def test_image_edit_handler_keeps_the_sassert response.data[0].b64_json == "sync"+ class _ScriptedClientWebSocket(_FakeClientWebSocket):+ def __init__(self, messages: list[str], last_event_type: str) -> None:+ super().__init__()+ self._messages: Final = list(messages)+ self._last_event_type: Final = last_event_type+ self._backend_done: Final = asyncio.Event()++ async def receive_text(self) -> str:+ if self._messages:+ return self._messages.pop(0)+ await asyncio.wait_for(self._backend_done.wait(), timeout=5)+ raise RuntimeError("client went away")++ async def send_text(self, payload: str) -> None:+ await super().send_text(payload)+ if json.loads(payload).get("type") == self._last_event_type:+ self._backend_done.set()++ def sent_events(self) -> list[dict[str, object]]:+ return [json.loads(payload) for name, payload in self.events if name == "send_text"]+++ @pytest.mark.asyncio+ async def test_async_realtime_bridges_a_transcription_session_through_the_provider_backend():+ import websockets.exceptions # noqa: F401 # binds the submodule so async_realtime's except clause resolves, as in the proxy process++ from datetime import timedelta++ from google.cloud.speech_v2.types import (+ RecognitionResponseMetadata,+ SpeechRecognitionAlternative,+ StreamingRecognitionResult,+ StreamingRecognizeResponse,+ )++ from litellm.llms.vertex_ai.audio_transcription.realtime_backend import SpeechStreamingBackend+ from litellm.llms.vertex_ai.audio_transcription.realtime_transformation import VertexChirpRealtimeConfig++ def google_response(transcript: str, is_final: bool, billed: float) -> StreamingRecognizeResponse:+ return StreamingRecognizeResponse(+ results=[+ StreamingRecognitionResult(+ alternatives=[SpeechRecognitionAlternative(transcript=transcript)], is_final=is_final+ )+ ],+ metadata=RecognitionResponseMetadata(total_billed_duration=timedelta(seconds=billed)),+ )++ class FakeTransport:+ async def close(self) -> None:+ return None++ class FakeSpeechClient:+ transport = FakeTransport()++ def __init__(self) -> None:+ self.requests: Final[list[object]] = []++ async def streaming_recognize(self, requests=None):+ return self._respond(requests)++ async def _respond(self, requests):+ script = [google_response("four score", False, 0.0), google_response("Four score and seven", True, 2.0)]+ async for request in requests:+ self.requests.append(request)+ if request.audio and script:+ yield script.pop(0)++ speech_client = FakeSpeechClient()++ async def resolve_access_token() -> str:+ return "token"++ provider_config = VertexChirpRealtimeConfig(+ resolve_access_token=resolve_access_token,+ project="proj-1",+ location="us",+ backend_factory=lambda target: SpeechStreamingBackend(+ target, client_factory=lambda target, access_token: speech_client+ ),+ )+ audio = base64.b64encode(b"\x00\x01" * 800).decode()+ client_ws = _ScriptedClientWebSocket(+ [+ json.dumps(+ {+ "type": "session.update",+ "session": {+ "type": "transcription",+ "audio": {+ "input": {+ "format": {"type": "audio/pcm", "rate": 16000},+ "transcription": {"model": "chirp_3", "language": "en"},+ "turn_detection": {"type": "server_vad"},+ }+ },+ },+ }+ ),+ json.dumps({"type": "input_audio_buffer.append", "audio": audio}),+ json.dumps({"type": "input_audio_buffer.append", "audio": audio}),+ json.dumps({"type": "input_audio_buffer.commit"}),+ ],+ last_event_type="conversation.item.input_audio_transcription.completed",+ )+ logging_obj = Mock()+ logging_obj.litellm_trace_id = "trace_1"+ logging_obj.model_call_details = {}+ logging_obj.dispatch_success_handlers = AsyncMock()+ logging_obj.dispatch_failure_handlers = AsyncMock()+ handler = BaseLLMHTTPHandler()++ with patch.object(handler, "_open_realtime_backend_ws", AsyncMock(side_effect=AssertionError("dialed a websocket"))) as dial:+ await handler.async_realtime(+ model="chirp_3",+ websocket=client_ws,+ logging_obj=logging_obj,+ provider_config=provider_config,+ headers={},+ query_params={"model": "chirp_3", "intent": "transcription"},+ )++ dial.assert_not_awaited()+ events = client_ws.sent_events()+ assert [event["type"] for event in events] == [+ "session.created",+ "session.updated",+ "input_audio_buffer.speech_started",+ "conversation.item.input_audio_transcription.delta",+ "conversation.item.input_audio_transcription.delta",+ "input_audio_buffer.speech_stopped",+ "conversation.item.input_audio_transcription.completed",+ ]+ assert events[0]["session"]["audio"]["input"]["transcription"] == {"model": "chirp_3"}+ assert events[1]["session"]["audio"]["input"] == {+ "format": {"type": "audio/pcm", "rate": 16000},+ "transcription": {"model": "chirp_3", "language": "en-US"},+ "turn_detection": {"type": "server_vad"},+ }+ assert [event["delta"] for event in events[3:5]] == ["four score", " and seven"]+ assert events[6]["transcript"] == "Four score and seven"+ assert events[6]["usage"] == {"type": "duration", "seconds": 2.0}+ assert speech_client.requests[0].streaming_config.config.model == "chirp_3"+ assert [bytes(request.audio) for request in speech_client.requests[1:]] == [b"\x00\x01" * 800, b"\x00\x01" * 800]+++++async def test_responses_agentic_followup_does_not_repeat_request_params_from_plan_kwargs(monkeypatch):+ """A plan whose kwargs repeat a request param must not crash the Responses follow-up with a duplicate keyword"""+ from litellm.integrations.custom_logger import CustomLogger+ from litellm.types.integrations.custom_logger import AgenticLoopPlan, AgenticLoopRequestPatch++ followup_calls: list[dict[str, object]] = []++ async def fake_aresponses(**kwargs: object) -> str:+ followup_calls.append(kwargs)+ return "followup-response"++ monkeypatch.setattr(litellm, "aresponses", fake_aresponses)+ request_kwargs: Final = {"prompt_cache_key": "thread-1", "metadata": {"user": "u1"}}+ plan: Final = AgenticLoopPlan(+ run_agentic_loop=True,+ request_patch=AgenticLoopRequestPatch(+ model="gpt-5",+ messages=[{"role": "user", "content": "x"}],+ optional_params={"prompt_cache_key": "thread-1"},+ kwargs=dict(request_kwargs),+ ),+ )++ response: Final = await BaseLLMHTTPHandler()._execute_responses_agentic_plan(+ plan=plan,+ model="gpt-5",+ response_api_optional_request_params={"prompt_cache_key": "thread-1"},+ logging_obj=Mock(litellm_call_id="call-1"),+ kwargs=dict(request_kwargs),+ depth=0,+ max_loops=3,+ fingerprints=[],+ fingerprint="fp",+ callback=CustomLogger(),+ )++ assert response == "followup-response"+ assert len(followup_calls) == 1+ assert followup_calls[0]["prompt_cache_key"] == "thread-1"+ assert followup_calls[0]["metadata"] == {"user": "u1"}+ assert followup_calls[0]["_agentic_loop_depth"] == 1