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 HEAD
yassind0591665b556
diff --cc litellm/proxy/pass_through_endpoints/success_handler.pyindex 2ccb8ad525d,699caae819d..d564dd6efaf--- a/litellm/proxy/pass_through_endpoints/success_handler.py+++ b/litellm/proxy/pass_through_endpoints/success_handler.py@@@ -257,25 -257,25 +258,44 @@@ class PassThroughEndpointLogging)standard_logging_response_object = comprehend_medical_handler_result["result"] # rebind-ok: elif-chainkwargs = comprehend_medical_handler_result["kwargs"] # rebind-ok: elif-chain contract+ elif self.is_azure_speech_route(custom_llm_provider):+ from .llm_provider_handlers.azure_speech_passthrough_logging_handler import (+ AzureSpeechPassthroughLoggingHandler,+ )++ azure_speech_handler_result: Final = AzureSpeechPassthroughLoggingHandler.azure_speech_passthrough_handler(+ httpx_response=httpx_response,+ response_body=response_body,+ logging_obj=logging_obj,+ url_route=url_route,+ result=result,+ start_time=start_time,+ end_time=end_time,+ cache_hit=cache_hit,+ request_body=request_body,+ **kwargs,+ )+ standard_logging_response_object = azure_speech_handler_result["result"] # rebind-ok: elif-chain+ kwargs = azure_speech_handler_result["kwargs"] # rebind-ok: elif-chain contract+ elif self.is_typesafe_route(custom_llm_provider):+ from .llm_provider_handlers.typesafe_passthrough_logging_handler import (+ TypeSafePassthroughLoggingHandler,+ )++ typesafe_handler_result: Final = TypeSafePassthroughLoggingHandler.typesafe_passthrough_handler(+ httpx_response=httpx_response,+ response_body=response_body if isinstance(response_body, dict) else MappingProxyType({}),+ logging_obj=logging_obj,+ url_route=url_route,+ result=result,+ start_time=start_time,+ end_time=end_time,+ cache_hit=cache_hit,+ request_body=request_body,+ **kwargs,+ )+ standard_logging_response_object = typesafe_handler_result["result"]+ kwargs = typesafe_handler_result["kwargs"]elif self.is_vertex_ai_live_route(url_route):from .llm_provider_handlers.vertex_ai_live_passthrough_logging_handler import (VertexAILivePassthroughLoggingHandler,@@@ -409,9 -409,9 +429,12 @@@def is_comprehend_medical_route(self, custom_llm_provider: str | None) -> bool:return custom_llm_provider == "comprehendmedical"+ def is_azure_speech_route(self, custom_llm_provider: str | None) -> bool:+ return custom_llm_provider == AZURE_SPEECH_CUSTOM_LLM_PROVIDER++ def is_typesafe_route(self, custom_llm_provider: str | None) -> bool:+ return custom_llm_provider == "typesafe"+def is_langfuse_route(self, url_route: str):parsed_url: Final = urlparse(url_route)for route in self.TRACKED_LANGFUSE_ROUTES:diff --cc tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.pyindex 0e8a2b9e0e9,901c5318442..7403b5e6efa--- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py@@@ -6139,522 -6140,49 +6141,570 @@@ class TestAzureRelayDeploymentSegmentassert [call["model"] for call in captured] == ["gpt", "gpt"]+AZURE_SPEECH_SHORT_AUDIO_ENDPOINT: Final = "/speech/recognition/conversation/cognitiveservices/v1"+AZURE_SPEECH_BATCH_ENDPOINT: Final = "/speechtotext/v3.2/transcriptions"+AZURE_SPEECH_FAST_ENDPOINT: Final = "/speechtotext/transcriptions:transcribe"+AZURE_SPEECH_PCM16_HEADER: Final = (+ b"RIFF\x24\x0c\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x80\x3e\x00\x00\x00\x7d\x00\x00\x02\x00\x10\x00data\x00\x0c\x00\x00"+)+AZURE_SPEECH_WAV_BYTES: Final = AZURE_SPEECH_PCM16_HEADER + b"\x00" * 3072+AZURE_SPEECH_NON_UTF8_WAV_BYTES: Final = AZURE_SPEECH_PCM16_HEADER + bytes(range(256)) * 12+AZURE_SPEECH_TRANSCRIPT: Final = {"RecognitionStatus": "Success", "DisplayText": "The eagle has landed."}+++def _azure_speech_test_client(monkeypatch: pytest.MonkeyPatch, caller: UserAPIKeyAuth) -> TestClient:+ from litellm.proxy.proxy_server import app++ monkeypatch.setenv("AZURE_SPEECH_API_KEY", "server-subscription-key")+ monkeypatch.setenv("AZURE_SPEECH_REGION", "eastus")+ monkeypatch.delenv("AZURE_SPEECH_API_BASE", raising=False)+ monkeypatch.delenv("SERVER_ROOT_PATH", raising=False)+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()+ monkeypatch.setitem(app.dependency_overrides, user_api_key_auth, lambda: caller)+ return TestClient(app)+++def azure_speech_client(monkeypatch: pytest.MonkeyPatch) -> Iterator[TestClient]:+ yield _azure_speech_test_client(monkeypatch, UserAPIKeyAuth(api_key="sk-virtual"))+++def azure_speech_admin_client(monkeypatch: pytest.MonkeyPatch) -> Iterator[TestClient]:+ yield _azure_speech_test_client(+ monkeypatch, UserAPIKeyAuth(api_key="sk-admin", user_role=LitellmUserRoles.PROXY_ADMIN)+ )+++class TestAzureSpeechProxyRoute:+ """Drives the real FastAPI route with respx standing in for the Azure hosts only."""++ def test_short_audio_forwards_raw_wav_bytes_with_server_key(self, azure_speech_client: TestClient) -> None:+ with respx.mock(assert_all_called=True) as upstream:+ route = upstream.post(+ f"https://eastus.stt.speech.microsoft.com{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}"+ ).mock(return_value=httpx.Response(200, json=AZURE_SPEECH_TRANSCRIPT))++ response = azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}",+ params={"language": "en-US", "format": "detailed"},+ content=AZURE_SPEECH_WAV_BYTES,+ headers={+ "Content-Type": "audio/wav; codecs=audio/pcm; samplerate=16000",+ "Authorization": "Bearer sk-virtual",+ "Ocp-Apim-Subscription-Key": "caller-supplied-key",+ "x-pass-ocp-apim-subscription-key": "caller-supplied-key",+ },+ )++ assert (response.status_code, response.json()) == (200, AZURE_SPEECH_TRANSCRIPT)+ sent = route.calls.last.request+ assert sent.content == AZURE_SPEECH_WAV_BYTES+ assert dict(sent.url.params) == {"language": "en-US", "format": "detailed"}+ assert sent.headers["ocp-apim-subscription-key"] == "server-subscription-key"+ assert sent.headers["content-type"] == "audio/wav; codecs=audio/pcm; samplerate=16000"+ assert "authorization" not in sent.headers+ assert "caller-supplied-key" not in repr(sent.headers)++ def test_admin_batch_job_creation_goes_to_the_cognitive_services_host(+ self, azure_speech_admin_client: TestClient+ ) -> None:+ body: Final = {"contentUrls": ["https://example.com/a.wav"], "locale": "en-US", "displayName": "job"}+ with respx.mock(assert_all_called=True) as upstream:+ route = upstream.post(f"https://eastus.api.cognitive.microsoft.com{AZURE_SPEECH_BATCH_ENDPOINT}").mock(+ return_value=httpx.Response(201, json={"self": "https://eastus.api.cognitive.microsoft.com/x"})+ )++ response = azure_speech_admin_client.post(+ f"/azure_speech{AZURE_SPEECH_BATCH_ENDPOINT}",+ json=body,+ headers={"Authorization": "Bearer sk-admin"},+ )++ assert response.status_code == 201+ sent = route.calls.last.request+ assert json.loads(sent.content) == body+ assert sent.headers["ocp-apim-subscription-key"] == "server-subscription-key"+ assert "authorization" not in sent.headers++ @pytest.mark.parametrize(+ "method,endpoint",+ [+ ("POST", AZURE_SPEECH_BATCH_ENDPOINT),+ ("POST", "/speechtotext/v3.2/models"),+ ("PUT", "/speechtotext/v3.2/endpoints/8a5d3f2c-0b1e-4c7d-9e6f-1234567890ab"),+ ("GET", AZURE_SPEECH_BATCH_ENDPOINT),+ ("GET", f"{AZURE_SPEECH_BATCH_ENDPOINT}/8a5d3f2c-0b1e-4c7d-9e6f-1234567890ab/files"),+ ("PATCH", f"{AZURE_SPEECH_BATCH_ENDPOINT}/8a5d3f2c-0b1e-4c7d-9e6f-1234567890ab"),+ ("DELETE", f"{AZURE_SPEECH_BATCH_ENDPOINT}/8a5d3f2c-0b1e-4c7d-9e6f-1234567890ab"),+ ],+ )+ def test_non_admin_key_cannot_manage_shared_batch_resources(+ self, azure_speech_client: TestClient, method: str, endpoint: str+ ) -> None:+ with respx.mock(assert_all_called=False) as upstream:+ catch_all = upstream.route().mock(return_value=httpx.Response(200, json={"status": "Succeeded"}))++ response = azure_speech_client.request(+ method,+ f"/azure_speech{endpoint}",+ json={"contentUrls": ["https://example.com/a.wav"], "locale": "en-US"},+ headers={"Authorization": "Bearer sk-virtual"},+ )++ assert response.status_code == 403, response.text+ assert AZURE_SPEECH_FAST_ENDPOINT in response.text+ assert not catch_all.called++ def test_non_admin_key_can_still_fast_transcribe_in_the_batch_family(self, azure_speech_client: TestClient) -> None:+ with respx.mock(assert_all_called=True) as upstream:+ upstream.post(f"https://eastus.api.cognitive.microsoft.com{AZURE_SPEECH_FAST_ENDPOINT}").mock(+ return_value=httpx.Response(200, json={"durationMilliseconds": 640, "combinedPhrases": []})+ )++ response = azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_FAST_ENDPOINT}",+ params={"api-version": "2024-11-15"},+ files={"audio": ("eagle.wav", AZURE_SPEECH_WAV_BYTES, "audio/wav")},+ data={"definition": json.dumps({"locales": ["en-US"]})},+ headers={"Authorization": "Bearer sk-virtual"},+ )++ assert response.status_code == 200++ def test_admin_key_reads_and_deletes_batch_jobs(self, azure_speech_admin_client: TestClient) -> None:+ job_path: Final = f"{AZURE_SPEECH_BATCH_ENDPOINT}/8a5d3f2c-0b1e-4c7d-9e6f-1234567890ab"+ with respx.mock(assert_all_called=True) as upstream:+ upstream.get(f"https://eastus.api.cognitive.microsoft.com{job_path}").mock(+ return_value=httpx.Response(200, json={"status": "Succeeded"})+ )+ upstream.delete(f"https://eastus.api.cognitive.microsoft.com{job_path}").mock(+ return_value=httpx.Response(204)+ )++ statuses = [+ azure_speech_admin_client.get(f"/azure_speech{job_path}", headers={"Authorization": "Bearer sk-admin"}),+ azure_speech_admin_client.delete(+ f"/azure_speech{job_path}", headers={"Authorization": "Bearer sk-admin"}+ ),+ ]++ assert [r.status_code for r in statuses] == [200, 204]++ def test_fast_transcription_multipart_upload_is_forwarded_byte_for_byte(+ self, azure_speech_client: TestClient+ ) -> None:+ with respx.mock(assert_all_called=True) as upstream:+ route = upstream.post(f"https://eastus.api.cognitive.microsoft.com{AZURE_SPEECH_FAST_ENDPOINT}").mock(+ return_value=httpx.Response(200, json={"durationMilliseconds": 640, "combinedPhrases": []})+ )++ response = azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_FAST_ENDPOINT}",+ params={"api-version": "2024-11-15"},+ files={"audio": ("eagle.wav", AZURE_SPEECH_NON_UTF8_WAV_BYTES, "audio/wav")},+ data={"definition": json.dumps({"locales": ["en-US"]})},+ headers={"Authorization": "Bearer sk-virtual"},+ )++ assert response.status_code == 200+ sent = route.calls.last.request+ assert sent.headers["content-type"].startswith("multipart/form-data; boundary=")+ assert dict(sent.url.params) == {"api-version": "2024-11-15"}+ assert AZURE_SPEECH_NON_UTF8_WAV_BYTES in sent.content+ assert b'name="definition"' in sent.content+ assert sent.headers["ocp-apim-subscription-key"] == "server-subscription-key"+ assert "authorization" not in sent.headers++ def test_batch_get_is_forwarded_with_the_job_id_path(self, azure_speech_admin_client: TestClient) -> None:+ job_path: Final = f"{AZURE_SPEECH_BATCH_ENDPOINT}/8a5d3f2c-0b1e-4c7d-9e6f-1234567890ab/files"+ with respx.mock(assert_all_called=True) as upstream:+ route = upstream.get(f"https://eastus.api.cognitive.microsoft.com{job_path}").mock(+ return_value=httpx.Response(200, json={"values": []})+ )++ response = azure_speech_admin_client.get(+ f"/azure_speech{job_path}", headers={"Authorization": "Bearer sk-admin"}+ )++ assert (response.status_code, response.json()) == (200, {"values": []})+ assert route.calls.last.request.headers["ocp-apim-subscription-key"] == "server-subscription-key"++ @pytest.mark.parametrize("method", ["GET", "POST"])+ def test_batch_requests_are_logged_as_azure_speech_not_assemblyai(+ self, azure_speech_admin_client: TestClient, monkeypatch: pytest.MonkeyPatch, method: str+ ) -> None:+ from litellm.integrations.custom_logger import CustomLogger++ class _Recorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.payloads: list[dict[str, object]] = [] # mutable-ok: test recorder accumulates callback payloads++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None:+ self.payloads.append(kwargs["standard_logging_object"])++ recorder: Final = _Recorder()+ monkeypatch.setattr(litellm, "_async_success_callback", [*litellm._async_success_callback, recorder])+ with respx.mock(assert_all_called=True) as upstream:+ upstream.request(method, f"https://eastus.api.cognitive.microsoft.com{AZURE_SPEECH_BATCH_ENDPOINT}").mock(+ return_value=httpx.Response(200, json={"values": []})+ )++ response = azure_speech_admin_client.request(+ method,+ f"/azure_speech{AZURE_SPEECH_BATCH_ENDPOINT}",+ json={"locale": "en-US"} if method == "POST" else None,+ headers={"Authorization": "Bearer sk-admin"},+ )++ assert response.status_code == 200+ assert [(p["model"], p["custom_llm_provider"], p["response_cost"]) for p in recorder.payloads] == [+ ("azure_speech/batch-transcription", "azure_speech", 0.0)+ ]++ def test_fast_transcription_spend_is_priced_from_duration_milliseconds(+ self, azure_speech_client: TestClient, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from litellm.integrations.custom_logger import CustomLogger++ class _Recorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.payloads: list[dict[str, object]] = [] # mutable-ok: test recorder accumulates callback payloads++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None:+ self.payloads.append(kwargs["standard_logging_object"])++ recorder: Final = _Recorder()+ monkeypatch.setattr(litellm, "_async_success_callback", [*litellm._async_success_callback, recorder])+ monkeypatch.setitem(+ litellm.model_cost,+ "azure/speech/azure-stt",+ {+ "litellm_provider": "azure",+ "mode": "audio_transcription",+ "input_cost_per_second": 0.25,+ "output_cost_per_second": 0.0,+ },+ )+ with respx.mock(assert_all_called=True) as upstream:+ upstream.post(f"https://eastus.api.cognitive.microsoft.com{AZURE_SPEECH_FAST_ENDPOINT}").mock(+ return_value=httpx.Response(200, json={"durationMilliseconds": 5061, "combinedPhrases": []})+ )++ response = azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_FAST_ENDPOINT}",+ params={"api-version": "2024-11-15"},+ files={"audio": ("eagle.wav", AZURE_SPEECH_WAV_BYTES, "audio/wav")},+ data={"definition": json.dumps({"locales": ["en-US"]})},+ headers={"Authorization": "Bearer sk-virtual"},+ )++ assert response.status_code == 200+ assert [(p["model"], p["custom_llm_provider"]) for p in recorder.payloads] == [+ ("azure_speech/fast-transcription", "azure_speech")+ ]+ assert recorder.payloads[0]["response_cost"] == pytest.approx(5.061 * 0.25)++ def test_short_audio_spend_is_priced_from_the_recognized_duration(+ self, azure_speech_client: TestClient, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from litellm.integrations.custom_logger import CustomLogger++ class _Recorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.payloads: list[dict[str, object]] = [] # mutable-ok: test recorder accumulates callback payloads++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None:+ self.payloads.append(kwargs["standard_logging_object"])++ recorder: Final = _Recorder()+ monkeypatch.setattr(litellm, "_async_success_callback", [*litellm._async_success_callback, recorder])+ monkeypatch.setitem(+ litellm.model_cost,+ "azure/speech/azure-stt",+ {+ "litellm_provider": "azure",+ "mode": "audio_transcription",+ "input_cost_per_second": 0.25,+ "output_cost_per_second": 0.0,+ },+ )+ transcript: Final = {**AZURE_SPEECH_TRANSCRIPT, "Offset": 10_000_000, "Duration": 30_000_000}+ with respx.mock(assert_all_called=True) as upstream:+ upstream.post(f"https://eastus.stt.speech.microsoft.com{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}").mock(+ return_value=httpx.Response(200, json=transcript)+ )++ response = azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}",+ content=AZURE_SPEECH_WAV_BYTES,+ headers={"Content-Type": "audio/wav", "Authorization": "Bearer sk-virtual"},+ )++ assert response.status_code == 200+ assert [(p["model"], p["custom_llm_provider"]) for p in recorder.payloads] == [+ ("azure_speech/short-audio", "azure_speech")+ ]+ assert recorder.payloads[0]["response_cost"] == pytest.approx(4.0 * 0.25)++ def test_api_base_wins_over_region_for_both_families(+ self, azure_speech_client: TestClient, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setenv("AZURE_SPEECH_API_BASE", "https://my-speech.cognitiveservices.azure.com")+ with respx.mock(assert_all_called=True) as upstream:+ short_audio = upstream.post(+ f"https://my-speech.cognitiveservices.azure.com{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}"+ ).mock(return_value=httpx.Response(200, json=AZURE_SPEECH_TRANSCRIPT))+ fast = upstream.post(f"https://my-speech.cognitiveservices.azure.com{AZURE_SPEECH_FAST_ENDPOINT}").mock(+ return_value=httpx.Response(200, json={"durationMilliseconds": 640, "combinedPhrases": []})+ )++ azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}",+ content=AZURE_SPEECH_WAV_BYTES,+ headers={"Content-Type": "audio/wav", "Authorization": "Bearer sk-virtual"},+ )+ azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_FAST_ENDPOINT}",+ params={"api-version": "2024-11-15"},+ files={"audio": ("eagle.wav", AZURE_SPEECH_WAV_BYTES, "audio/wav")},+ data={"definition": json.dumps({"locales": ["en-US"]})},+ headers={"Authorization": "Bearer sk-virtual"},+ )++ assert short_audio.called and fast.called++ @pytest.mark.parametrize("endpoint", ["openai/deployments/whisper/audio/transcriptions", "speech", "speechtotext"])+ def test_unknown_path_family_is_rejected_before_any_upstream_call(+ self, azure_speech_client: TestClient, endpoint: str+ ) -> None:+ with respx.mock(assert_all_called=False) as upstream:+ catch_all = upstream.route().mock(return_value=httpx.Response(200))++ response = azure_speech_client.post(+ f"/azure_speech/{endpoint}", content=b"x", headers={"Authorization": "Bearer sk-virtual"}+ )++ assert response.status_code == 400+ assert not catch_all.called++ def test_missing_region_and_base_is_rejected_before_any_upstream_call(+ self, azure_speech_client: TestClient, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.delenv("AZURE_SPEECH_REGION")+ with respx.mock(assert_all_called=False) as upstream:+ catch_all = upstream.route().mock(return_value=httpx.Response(200))++ response = azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}",+ content=AZURE_SPEECH_WAV_BYTES,+ headers={"Content-Type": "audio/wav", "Authorization": "Bearer sk-virtual"},+ )++ assert response.status_code == 400+ assert "AZURE_SPEECH_REGION" in response.text+ assert not catch_all.called++ def test_missing_api_key_is_rejected_before_any_upstream_call(+ self, azure_speech_client: TestClient, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.delenv("AZURE_SPEECH_API_KEY")+ with respx.mock(assert_all_called=False) as upstream:+ catch_all = upstream.route().mock(return_value=httpx.Response(200))++ response = azure_speech_client.post(+ f"/azure_speech{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}",+ content=AZURE_SPEECH_WAV_BYTES,+ headers={"Content-Type": "audio/wav", "Authorization": "Bearer sk-virtual"},+ )++ assert response.status_code == 400+ assert "AZURE_SPEECH_API_KEY" in response.text+ assert not catch_all.called++ def test_azure_speech_is_a_mapped_pass_through_route(self) -> None:+ from litellm.proxy._types import LiteLLMRoutes++ assert "/azure_speech" in LiteLLMRoutes.mapped_pass_through_routes.value+++def _azure_speech_real_auth_attrs() -> dict[str, object]:+ from litellm.caching.caching import DualCache+ from litellm.proxy.utils import ProxyLogging++ user_api_key_cache: Final = DualCache()+ return {+ "prisma_client": None,+ "user_api_key_cache": user_api_key_cache,+ "proxy_logging_obj": ProxyLogging(user_api_key_cache=user_api_key_cache),+ "master_key": "sk-master-key",+ "general_settings": {},+ "llm_model_list": [],+ "llm_router": None,+ "open_telemetry_logger": None,+ "user_custom_auth": None,+ "jwt_handler": None,+ }+++class TestAzureSpeechRawBodyThroughRealAuth:+ """user_api_key_auth reads the body before the route runs; raw audio must not be parsed as JSON."""++ def _post(+ self, monkeypatch: pytest.MonkeyPatch, path: str, api_key: str, content_type: str, body: bytes+ ) -> httpx.Response:+ from litellm.proxy.proxy_server import app++ monkeypatch.delitem(app.dependency_overrides, user_api_key_auth, raising=False)+ monkeypatch.setenv("AZURE_SPEECH_API_KEY", "server-subscription-key")+ monkeypatch.setenv("AZURE_SPEECH_REGION", "eastus")+ monkeypatch.delenv("AZURE_SPEECH_API_BASE", raising=False)+ monkeypatch.delenv("SERVER_ROOT_PATH", raising=False)+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()+ with patch.multiple( # test-quality-ok: the real user_api_key_auth reads proxy_server module globals (master_key, caches) that have no injection seam+ "litellm.proxy.proxy_server", **_azure_speech_real_auth_attrs()+ ):+ client = TestClient(app)+ return client.post(+ path,+ params={"language": "en-US"},+ content=body,+ headers={"Content-Type": content_type, "Authorization": f"Bearer {api_key}"},+ )++ def _post_wav(+ self, monkeypatch: pytest.MonkeyPatch, path: str, api_key: str, body: bytes = AZURE_SPEECH_WAV_BYTES+ ) -> httpx.Response:+ return self._post(monkeypatch, path, api_key, "audio/wav", body)++ @pytest.mark.parametrize("body", [AZURE_SPEECH_WAV_BYTES, AZURE_SPEECH_NON_UTF8_WAV_BYTES], ids=["ascii", "binary"])+ def test_master_key_with_raw_wav_body_reaches_azure_without_a_parse_attempt(+ self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, body: bytes+ ) -> None:+ with respx.mock(assert_all_called=True) as upstream, caplog.at_level(logging.ERROR, logger="LiteLLM Proxy"):+ route = upstream.post(+ f"https://eastus.stt.speech.microsoft.com{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}"+ ).mock(return_value=httpx.Response(200, json=AZURE_SPEECH_TRANSCRIPT))++ response = self._post_wav(+ monkeypatch, f"/azure_speech{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}", "sk-master-key", body=body+ )++ assert (response.status_code, response.json()) == (200, AZURE_SPEECH_TRANSCRIPT)+ assert route.calls.last.request.content == body+ assert [record.message for record in caplog.records if "request body" in record.message] == []++ def test_wrong_litellm_key_with_raw_wav_body_is_rejected(self, monkeypatch: pytest.MonkeyPatch) -> None:+ with respx.mock(assert_all_called=False) as upstream:+ catch_all = upstream.route().mock(return_value=httpx.Response(200))++ response = self._post_wav(monkeypatch, f"/azure_speech{AZURE_SPEECH_SHORT_AUDIO_ENDPOINT}", "sk-wrong")++ assert response.status_code in (400, 401), response.text+ assert not catch_all.called++ def test_master_key_with_multipart_batch_upload_is_forwarded_byte_for_byte(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ boundary: Final = "lit7939boundary"+ multipart_body: Final = (+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"definition\"\r\n\r\n".encode()+ + json.dumps({"locales": ["en-US"]}).encode()+ + f"\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"audio\"; filename=\"eagle.wav\"\r\n"+ "Content-Type: audio/wav\r\n\r\n".encode()+ + AZURE_SPEECH_NON_UTF8_WAV_BYTES+ + f"\r\n--{boundary}--\r\n".encode()+ )+ with respx.mock(assert_all_called=True) as upstream:+ route = upstream.post(f"https://eastus.api.cognitive.microsoft.com{AZURE_SPEECH_BATCH_ENDPOINT}").mock(+ return_value=httpx.Response(201, json={"status": "NotStarted"})+ )++ response = self._post(+ monkeypatch,+ f"/azure_speech{AZURE_SPEECH_BATCH_ENDPOINT}",+ "sk-master-key",+ f"multipart/form-data; boundary={boundary}",+ multipart_body,+ )++ assert (response.status_code, response.json()) == (201, {"status": "NotStarted"})+ sent = route.calls.last.request+ assert sent.content == multipart_body+ assert sent.headers["content-type"] == f"multipart/form-data; boundary={boundary}"+ assert sent.headers["ocp-apim-subscription-key"] == "server-subscription-key"++ @pytest.mark.parametrize("content_type", ["audio/wav", "multipart/form-data; boundary=x"])+ def test_wrong_litellm_key_with_multipart_batch_upload_is_rejected(+ self, monkeypatch: pytest.MonkeyPatch, content_type: str+ ) -> None:+ with respx.mock(assert_all_called=False) as upstream:+ catch_all = upstream.route().mock(return_value=httpx.Response(200))++ response = self._post(+ monkeypatch, f"/azure_speech{AZURE_SPEECH_BATCH_ENDPOINT}", "sk-wrong", content_type, b"--x--\r\n"+ )++ assert response.status_code in (400, 401), response.text+ assert not catch_all.called++ def test_audio_content_type_off_the_azure_speech_route_is_still_parsed_as_json(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ response = self._post_wav(monkeypatch, "/v1/chat/completions", "sk-master-key", body=b'{}{"model": "gpt-4o"}')++ assert response.status_code == 400+ assert "Invalid JSON payload" in response.text+++++ class TestTypeSafePassthroughRoute:+ @staticmethod+ def _request(body: object, query_params: Mapping[str, str] | None = None) -> MagicMock:+ request = MagicMock(spec=Request)+ request.method = "POST"+ request.query_params = query_params or {}+ request.json = AsyncMock(return_value=body)+ return request++ @pytest.mark.asyncio+ async def test_forwards_target_auth_headers_provider_and_query(self, monkeypatch):+ monkeypatch.setenv("TYPESAFE_API_KEY", "typesafe-test-key")+ monkeypatch.setenv("TYPESAFE_API_BASE", "https://typesafe.example/base")++ async def fake_upstream(request, *_args):+ target: Final = create_route.call_args.kwargs["target"]+ upstream_url: Final = httpx.URL(target).copy_merge_params(request.query_params)+ return {"upstream_query": parse_qs(upstream_url.query.decode())}++ endpoint_func = AsyncMock(side_effect=fake_upstream)+ create_route = Mock(return_value=endpoint_func)+ monkeypatch.setattr(+ "litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints.create_pass_through_route",+ create_route,+ )++ request = self._request({"state": "x"}, {"trace": "yes"})+ result = await typesafe_proxy_route(+ endpoint="v1/systemone",+ request=request,+ fastapi_response=MagicMock(spec=Response),+ user_api_key_dict=UserAPIKeyAuth(api_key="virtual-key"),+ )++ assert result == {"upstream_query": {"trace": ["yes"]}}+ endpoint_func.assert_awaited_once()+ create_route.assert_called_once_with(+ endpoint="v1/systemone",+ target="https://typesafe.example/base/v1/systemone",+ custom_headers={+ "Authorization": "Bearer typesafe-test-key",+ "Content-Type": "application/json",+ },+ custom_llm_provider="typesafe",+ is_streaming_request=False,+ )