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
feat(azure): add speech transcription config support (#27482)
ishaan-berri203b529c9d74
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex 3365abe3256..7c92623358d 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -1877,6 +1877,9 @@ if TYPE_CHECKING:from .llms.azure.completion.transformation import (AzureOpenAITextConfig as AzureOpenAITextConfig,)+ from .llms.azure.audio_transcription.transformation import (+ AzureSpeechAudioTranscriptionConfig as AzureSpeechAudioTranscriptionConfig,+ )from .llms.hosted_vllm.chat.transformation import (HostedVLLMChatConfig as HostedVLLMChatConfig,)diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.pyindex e3656b340fa..17eb6609292 100644--- a/litellm/_lazy_imports_registry.py+++ b/litellm/_lazy_imports_registry.py@@ -273,6 +273,7 @@ LLM_CONFIG_NAMES = ("AzureOpenAIConfig","AzureOpenAIGPT5Config","AzureOpenAITextConfig",+ "AzureSpeechAudioTranscriptionConfig","HostedVLLMChatConfig","HostedVLLMEmbeddingConfig",# Alias for backwards compatibility@@ -1054,6 +1055,10 @@ _LLM_CONFIGS_IMPORT_MAP = {".llms.azure.completion.transformation","AzureOpenAITextConfig",),+ "AzureSpeechAudioTranscriptionConfig": (+ ".llms.azure.audio_transcription.transformation",+ "AzureSpeechAudioTranscriptionConfig",+ ),"HostedVLLMChatConfig": (".llms.hosted_vllm.chat.transformation","HostedVLLMChatConfig",diff --git a/litellm/llms/azure/audio_transcription/__init__.py b/litellm/llms/azure/audio_transcription/__init__.pynew file mode 100644index 00000000000..cedd0c6dbeb--- /dev/null+++ b/litellm/llms/azure/audio_transcription/__init__.py@@ -0,0 +1,3 @@+from .transformation import AzureSpeechAudioTranscriptionConfig++__all__ = ["AzureSpeechAudioTranscriptionConfig"]diff --git a/litellm/llms/azure/audio_transcription/transformation.py b/litellm/llms/azure/audio_transcription/transformation.pynew file mode 100644index 00000000000..e478c8ebf35--- /dev/null+++ b/litellm/llms/azure/audio_transcription/transformation.py@@ -0,0 +1,224 @@+"""+Azure AI Speech (Cognitive Services) speech-to-text transformation.++Maps OpenAI-compatible audio transcription calls to Azure Speech REST+recognition for short audio.+"""++from typing import Any, Dict, List, Optional, Union+from urllib.parse import urlencode, urlparse++import httpx++from litellm.litellm_core_utils.audio_utils.utils import process_audio_file+from litellm.llms.base_llm.audio_transcription.transformation import (+ AudioTranscriptionRequestData,+ BaseAudioTranscriptionConfig,+)+from litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.types.llms.openai import (+ AllMessageValues,+ OpenAIAudioTranscriptionOptionalParams,+)+from litellm.secret_managers.main import get_secret_str+from litellm.types.utils import FileTypes, TranscriptionResponse+++class AzureSpeechAudioTranscriptionException(BaseLLMException):+ pass+++class AzureSpeechAudioTranscriptionConfig(BaseAudioTranscriptionConfig):+ """+ Configuration for Azure AI Speech (Cognitive Services) STT.++ Reference:+ https://learn.microsoft.com/en-us/azure/ai-services/speech-service/rest-speech-to-text-short+ """++ COGNITIVE_SERVICES_DOMAIN = "api.cognitive.microsoft.com"+ STT_SPEECH_DOMAIN = "stt.speech.microsoft.com"+ STT_ENDPOINT_PATH = "/speech/recognition/conversation/cognitiveservices/v1"+ DEFAULT_LANGUAGE = "en-US"++ def get_supported_openai_params(+ self, model: str+ ) -> List[OpenAIAudioTranscriptionOptionalParams]:+ return ["language", "response_format"]++ def map_openai_params(+ self,+ non_default_params: dict,+ optional_params: dict,+ model: str,+ drop_params: bool,+ ) -> dict:+ supported_params = self.get_supported_openai_params(model=model)+ for key, value in non_default_params.items():+ if key in supported_params:+ optional_params[key] = value+ return optional_params++ def validate_environment(+ self,+ headers: dict,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ ) -> dict:+ api_key = api_key or get_secret_str("AZURE_SPEECH_API_KEY")+ if not api_key:+ raise AzureSpeechAudioTranscriptionException(+ message="api_key is required for Azure AI Speech transcription.",+ status_code=401,+ )++ validated_headers = headers.copy()+ validated_headers["Ocp-Apim-Subscription-Key"] = api_key+ validated_headers["Content-Type"] = validated_headers.get(+ "Content-Type", "audio/wav"+ )+ validated_headers["Accept"] = "application/json"+ return validated_headers++ def get_complete_url(+ self,+ api_base: Optional[str],+ api_key: Optional[str],+ model: str,+ optional_params: dict,+ litellm_params: dict,+ stream: Optional[bool] = None,+ ) -> str:+ api_base = api_base or get_secret_str("AZURE_SPEECH_API_BASE")+ if api_base is None:+ raise AzureSpeechAudioTranscriptionException(+ message=(+ "api_base is required for Azure AI Speech transcription. "+ "Use a Cognitive Services endpoint like "+ "https://{region}.api.cognitive.microsoft.com or an STT "+ "endpoint like https://{region}.stt.speech.microsoft.com."+ ),+ status_code=400,+ )++ base_url = self._resolve_stt_base_url(api_base=api_base)+ query_params = {+ "language": optional_params.get("language", self.DEFAULT_LANGUAGE),+ "format": self._get_azure_response_format(+ optional_params.get("response_format")+ ),+ }+ return f"{base_url}{self.STT_ENDPOINT_PATH}?{urlencode(query_params)}"++ def transform_audio_transcription_request(+ self,+ model: str,+ audio_file: FileTypes,+ optional_params: dict,+ litellm_params: dict,+ ) -> AudioTranscriptionRequestData:+ processed_audio = process_audio_file(audio_file)+ return AudioTranscriptionRequestData(+ data=processed_audio.file_content,+ files=None,+ content_type=processed_audio.content_type,+ )++ def transform_audio_transcription_response(+ self,+ raw_response: httpx.Response,+ ) -> TranscriptionResponse:+ response_json = raw_response.json()+ recognition_status = response_json.get("RecognitionStatus")+ if recognition_status is not None and recognition_status != "Success":+ raise AzureSpeechAudioTranscriptionException(+ message=(+ "Azure AI Speech transcription failed with "+ f"RecognitionStatus={recognition_status}."+ ),+ status_code=raw_response.status_code,+ headers=raw_response.headers,+ )++ text = self._extract_text(response_json)+ response = TranscriptionResponse(text=text)+ response._hidden_params = response_json+ return response++ def get_error_class(+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]+ ) -> BaseLLMException:+ return AzureSpeechAudioTranscriptionException(+ message=error_message,+ status_code=status_code,+ headers=headers,+ )++ def _resolve_stt_base_url(self, api_base: str) -> str:+ api_base = api_base.rstrip("/")+ parsed_url = urlparse(api_base)+ hostname = parsed_url.hostname or ""++ if self._is_cognitive_services_endpoint(hostname=hostname):+ region = self._extract_region_from_hostname(+ hostname=hostname, domain=self.COGNITIVE_SERVICES_DOMAIN+ )+ return self._build_stt_base_url(region=region)++ if self._is_stt_endpoint(hostname=hostname):+ return f"{parsed_url.scheme}://{hostname}"++ if self._is_azure_openai_endpoint(hostname=hostname):+ raise AzureSpeechAudioTranscriptionException(+ message=(+ "Azure AI Speech transcription requires a Cognitive Services "+ "or STT Speech endpoint, not an Azure OpenAI endpoint."+ ),+ status_code=400,+ )++ return api_base++ def _is_cognitive_services_endpoint(self, hostname: str) -> bool:+ return hostname == self.COGNITIVE_SERVICES_DOMAIN or hostname.endswith(+ f".{self.COGNITIVE_SERVICES_DOMAIN}"+ )++ def _is_stt_endpoint(self, hostname: str) -> bool:+ return hostname == self.STT_SPEECH_DOMAIN or hostname.endswith(+ f".{self.STT_SPEECH_DOMAIN}"+ )++ def _is_azure_openai_endpoint(self, hostname: str) -> bool:+ return hostname.endswith(".openai.azure.com")++ def _extract_region_from_hostname(self, hostname: str, domain: str) -> str:+ if hostname.endswith(f".{domain}"):+ return hostname[: -len(f".{domain}")]+ return ""++ def _build_stt_base_url(self, region: str) -> str:+ if region:+ return f"https://{region}.{self.STT_SPEECH_DOMAIN}"+ return f"https://{self.STT_SPEECH_DOMAIN}"++ def _get_azure_response_format(self, response_format: Optional[str]) -> str:+ if response_format == "verbose_json":+ return "detailed"+ return "simple"++ def _extract_text(self, response_json: Dict[str, Any]) -> str:+ if isinstance(response_json.get("DisplayText"), str):+ return response_json["DisplayText"]++ nbest = response_json.get("NBest")+ if isinstance(nbest, list) and nbest:+ best = nbest[0]+ if isinstance(best, dict):+ return best.get("Display") or best.get("Lexical") or ""++ return ""diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 74e55b9debb..c9ab3c648ac 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -1207,6 +1207,8 @@ class BaseLLMHTTPHandler:data = transformed_result.datafiles = transformed_result.files+ if transformed_result.content_type is not None:+ headers["Content-Type"] = transformed_result.content_type## LOGGINGlogging_obj.pre_call(diff --git a/litellm/main.py b/litellm/main.pyindex 510e6e424a2..09c70998cf7 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -6615,8 +6615,7 @@ def transcription(api_key=api_key,) # type: ignore- if dynamic_api_key is not None:- api_key = dynamic_api_key+ api_key = dynamic_api_key if dynamic_api_key is not None else api_keyoptional_params = get_optional_params_transcription(model=model,@@ -6656,7 +6655,7 @@ def transcription(provider=LlmProviders(custom_llm_provider),)- if custom_llm_provider == "azure":+ if custom_llm_provider == "azure" and provider_config is None:# azure configsapi_base = api_base or litellm.api_base or get_secret_str("AZURE_API_BASE")diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 08c06b17ddf..62e576ea0f7 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -6054,6 +6054,17 @@"mode": "audio_speech","source": "https://azure.microsoft.com/en-us/pricing/calculator/"},+ "azure/speech/azure-stt": {+ "audio_transcription_config": "azure_speech",+ "input_cost_per_second": 0.0002777778,+ "litellm_provider": "azure",+ "mode": "audio_transcription",+ "output_cost_per_second": 0.0,+ "source": "https://azure.microsoft.com/en-us/pricing/details/cognitive-services/speech-services/",+ "supported_endpoints": [+ "/v1/audio/transcriptions"+ ]+ },"azure/tts-1": {"input_cost_per_character": 1.5e-05,"litellm_provider": "azure",diff --git a/litellm/utils.py b/litellm/utils.pyindex 2a94941f656..2ba6ef9cae8 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -8146,6 +8146,35 @@ def validate_openai_optional_params(return stop+@lru_cache(maxsize=1)+def _get_bundled_model_cost_map() -> Dict[str, Any]:+ try:+ model_cost_path = resources.files("litellm").joinpath(+ "model_prices_and_context_window_backup.json"+ )+ return json.loads(model_cost_path.read_text())+ except Exception:+ return {}+++def _get_model_cost_entry_for_provider_config(+ model: str,+ provider: LlmProviders,+) -> Dict[str, Any]:+ candidate_keys = (model, f"{provider.value}/{model}")+ for model_key in candidate_keys:+ model_info = litellm.model_cost.get(model_key)+ if model_info is not None:+ return model_info++ bundled_model_cost = _get_bundled_model_cost_map()+ for model_key in candidate_keys:+ model_info = bundled_model_cost.get(model_key)+ if model_info is not None:+ return model_info+ return {}++class ProviderConfigManager:# Dictionary mapping for O(1) provider lookup# Stores tuples of (factory_function, needs_model_parameter)@@ -8621,6 +8650,19 @@ class ProviderConfigManager:model: str,provider: LlmProviders,) -> Optional[BaseAudioTranscriptionConfig]:+ model_cost_entry = _get_model_cost_entry_for_provider_config(+ model=model,+ provider=provider,+ )+ if (+ litellm.LlmProviders.AZURE == provider+ and model_cost_entry.get("audio_transcription_config") == "azure_speech"+ ):+ from litellm.llms.azure.audio_transcription.transformation import (+ AzureSpeechAudioTranscriptionConfig,+ )++ return AzureSpeechAudioTranscriptionConfig()if litellm.LlmProviders.FIREWORKS_AI == provider:return litellm.FireworksAIAudioTranscriptionConfig()elif litellm.LlmProviders.DEEPGRAM == provider:diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 514862516e8..62553e46ac1 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -6067,6 +6067,17 @@"mode": "audio_speech","source": "https://azure.microsoft.com/en-us/pricing/calculator/"},+ "azure/speech/azure-stt": {+ "audio_transcription_config": "azure_speech",+ "input_cost_per_second": 0.0002777778,+ "litellm_provider": "azure",+ "mode": "audio_transcription",+ "output_cost_per_second": 0.0,+ "source": "https://azure.microsoft.com/en-us/pricing/details/cognitive-services/speech-services/",+ "supported_endpoints": [+ "/v1/audio/transcriptions"+ ]+ },"azure/tts-1": {"input_cost_per_character": 1.5e-05,"litellm_provider": "azure",diff --git a/tests/test_litellm/llms/azure/test_azure_speech_audio_transcription.py b/tests/test_litellm/llms/azure/test_azure_speech_audio_transcription.pynew file mode 100644index 00000000000..6ed6be6f34f--- /dev/null+++ b/tests/test_litellm/llms/azure/test_azure_speech_audio_transcription.py@@ -0,0 +1,239 @@+import io+import json+from pathlib import Path+from unittest.mock import MagicMock++import httpx+import pytest++import litellm+from litellm.llms.azure.audio_transcription.transformation import (+ AzureSpeechAudioTranscriptionConfig,+ AzureSpeechAudioTranscriptionException,+)+from litellm.llms.base_llm.audio_transcription.transformation import (+ AudioTranscriptionRequestData,+ BaseAudioTranscriptionConfig,+)+from litellm.types.utils import TranscriptionResponse+from litellm.utils import ProviderConfigManager+++def test_azure_speech_audio_transcription_config_installed():+ config = ProviderConfigManager.get_provider_audio_transcription_config(+ model="speech/azure-stt",+ provider=litellm.LlmProviders.AZURE,+ )++ assert isinstance(config, BaseAudioTranscriptionConfig)+ assert isinstance(config, AzureSpeechAudioTranscriptionConfig)+++def test_azure_speech_audio_transcription_builds_stt_url_from_cognitive_endpoint():+ config = AzureSpeechAudioTranscriptionConfig()++ url = config.get_complete_url(+ api_base="https://eastus.api.cognitive.microsoft.com/",+ api_key="test-key",+ model="speech/azure-stt",+ optional_params={"language": "fr-FR", "response_format": "verbose_json"},+ litellm_params={},+ )++ assert (+ url+ == "https://eastus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=fr-FR&format=detailed"+ )+++def test_azure_speech_audio_transcription_accepts_stt_endpoint_base():+ config = AzureSpeechAudioTranscriptionConfig()++ url = config.get_complete_url(+ api_base="https://westus.stt.speech.microsoft.com",+ api_key="test-key",+ model="speech/azure-stt",+ optional_params={},+ litellm_params={},+ )++ assert (+ url+ == "https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=simple"+ )+++def test_azure_speech_audio_transcription_uses_dedicated_api_base_env(monkeypatch):+ config = AzureSpeechAudioTranscriptionConfig()++ monkeypatch.setattr(+ "litellm.llms.azure.audio_transcription.transformation.get_secret_str",+ lambda key: (+ "https://centralus.api.cognitive.microsoft.com"+ if key == "AZURE_SPEECH_API_BASE"+ else None+ ),+ )++ url = config.get_complete_url(+ api_base=None,+ api_key="test-key",+ model="speech/azure-stt",+ optional_params={},+ litellm_params={},+ )++ assert (+ url+ == "https://centralus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US&format=simple"+ )+++def test_azure_speech_audio_transcription_rejects_azure_openai_endpoint():+ config = AzureSpeechAudioTranscriptionConfig()++ with pytest.raises(+ AzureSpeechAudioTranscriptionException,+ match="not an Azure OpenAI endpoint",+ ):+ config.get_complete_url(+ api_base="https://example.openai.azure.com",+ api_key="test-key",+ model="speech/azure-stt",+ optional_params={},+ litellm_params={},+ )+++def test_azure_speech_audio_transcription_validate_environment():+ config = AzureSpeechAudioTranscriptionConfig()++ headers = config.validate_environment(+ headers={},+ model="speech/azure-stt",+ messages=[],+ optional_params={},+ litellm_params={},+ api_key="test-key",+ )++ assert headers["Ocp-Apim-Subscription-Key"] == "test-key"+ assert headers["Content-Type"] == "audio/wav"+ assert headers["Accept"] == "application/json"+++def test_azure_speech_audio_transcription_uses_dedicated_api_key_env(monkeypatch):+ config = AzureSpeechAudioTranscriptionConfig()++ monkeypatch.setattr(+ "litellm.llms.azure.audio_transcription.transformation.get_secret_str",+ lambda key: "speech-key" if key == "AZURE_SPEECH_API_KEY" else None,+ )++ headers = config.validate_environment(+ headers={},+ model="speech/azure-stt",+ messages=[],+ optional_params={},+ litellm_params={},+ api_key=None,+ )++ assert headers["Ocp-Apim-Subscription-Key"] == "speech-key"+++def test_azure_speech_audio_transcription_request_transform():+ config = AzureSpeechAudioTranscriptionConfig()+ audio = io.BytesIO(b"RIFF....WAVE")++ request_data = config.transform_audio_transcription_request(+ model="speech/azure-stt",+ audio_file=audio,+ optional_params={},+ litellm_params={},+ )++ assert isinstance(request_data, AudioTranscriptionRequestData)+ assert request_data.data == b"RIFF....WAVE"+ assert request_data.files is None+ assert request_data.content_type == "audio/wav"+++ "payload,expected_text",+ [+ ({"DisplayText": "hello world"}, "hello world"),+ (+ {+ "RecognitionStatus": "Success",+ "NBest": [{"Display": "best text", "Confidence": 0.91}],+ },+ "best text",+ ),+ ],+)+def test_azure_speech_audio_transcription_response_transform(payload, expected_text):+ config = AzureSpeechAudioTranscriptionConfig()+ response = httpx.Response(200, json=payload)++ result = config.transform_audio_transcription_response(response)++ assert isinstance(result, TranscriptionResponse)+ assert result.text == expected_text+ assert result._hidden_params == payload+++def test_azure_speech_audio_transcription_response_raises_on_failed_status():+ config = AzureSpeechAudioTranscriptionConfig()+ response = httpx.Response(+ 200,+ json={+ "RecognitionStatus": "NoMatch",+ "Offset": 0,+ "Duration": 0,+ },+ )++ with pytest.raises(+ AzureSpeechAudioTranscriptionException,+ match="RecognitionStatus=NoMatch",+ ):+ config.transform_audio_transcription_response(response)+++def test_azure_speech_transcription_routes_through_provider_config(monkeypatch):+ expected = TranscriptionResponse(text="hello")+ audio_handler = MagicMock(return_value=expected)++ monkeypatch.setattr(+ litellm.main.base_llm_http_handler,+ "audio_transcriptions",+ audio_handler,+ )++ response = litellm.transcription(+ model="azure/speech/azure-stt",+ file=io.BytesIO(b"RIFF....WAVE"),+ api_base="https://eastus.api.cognitive.microsoft.com",+ api_key="test-key",+ language="en-US",+ )++ assert response is expected+ audio_handler.assert_called_once()+ assert isinstance(+ audio_handler.call_args.kwargs["provider_config"],+ AzureSpeechAudioTranscriptionConfig,+ )+ assert audio_handler.call_args.kwargs["custom_llm_provider"] == "azure"+++def test_azure_speech_stt_has_non_zero_input_pricing():+ pricing_path = Path(__file__).parents[4] / "model_prices_and_context_window.json"+ pricing = json.loads(pricing_path.read_text())++ assert pricing["azure/speech/azure-stt"]["input_cost_per_second"] > 0+ assert (+ pricing["azure/speech/azure-stt"]["audio_transcription_config"]+ == "azure_speech"+ )