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]

feat(speech/): working gemini tts support via openai's `/v1/speech` endpoint (#11832)

Krish Dholakia0319adbf5d9f
diff --git a/litellm/endpoints/speech/speech_to_completion_bridge/handler.py b/litellm/endpoints/speech/speech_to_completion_bridge/handler.py
new file mode 100644
index 00000000000..3035c5065c5
--- /dev/null
+++ b/litellm/endpoints/speech/speech_to_completion_bridge/handler.py
@@ -0,0 +1,126 @@
+"""
+Handler for transforming /chat/completions api requests to litellm.responses requests
+"""
+
+from typing import TYPE_CHECKING, Optional, TypedDict, Union
+
+if TYPE_CHECKING:
+ from litellm import LiteLLMLoggingObj
+ from litellm.types.llms.openai import HttpxBinaryResponseContent
+
+
+class SpeechToCompletionBridgeHandlerInputKwargs(TypedDict):
+ model: str
+ input: str
+ voice: Optional[Union[str, dict]]
+ optional_params: dict
+ litellm_params: dict
+ logging_obj: "LiteLLMLoggingObj"
+ headers: dict
+ custom_llm_provider: str
+
+
+class SpeechToCompletionBridgeHandler:
+ def __init__(self):
+ from .transformation import SpeechToCompletionBridgeTransformationHandler
+
+ super().__init__()
+ self.transformation_handler = SpeechToCompletionBridgeTransformationHandler()
+
+ def validate_input_kwargs(
+ self, kwargs: dict
+ ) -> SpeechToCompletionBridgeHandlerInputKwargs:
+ from litellm import LiteLLMLoggingObj
+
+ model = kwargs.get("model")
+ if model is None or not isinstance(model, str):
+ raise ValueError("model is required")
+
+ custom_llm_provider = kwargs.get("custom_llm_provider")
+ if custom_llm_provider is None or not isinstance(custom_llm_provider, str):
+ raise ValueError("custom_llm_provider is required")
+
+ input = kwargs.get("input")
+ if input is None or not isinstance(input, str):
+ raise ValueError("input is required")
+
+ optional_params = kwargs.get("optional_params")
+ if optional_params is None or not isinstance(optional_params, dict):
+ raise ValueError("optional_params is required")
+
+ litellm_params = kwargs.get("litellm_params")
+ if litellm_params is None or not isinstance(litellm_params, dict):
+ raise ValueError("litellm_params is required")
+
+ headers = kwargs.get("headers")
+ if headers is None or not isinstance(headers, dict):
+ raise ValueError("headers is required")
+
+ headers = kwargs.get("headers")
+ if headers is None or not isinstance(headers, dict):
+ raise ValueError("headers is required")
+
+ logging_obj = kwargs.get("logging_obj")
+ if logging_obj is None or not isinstance(logging_obj, LiteLLMLoggingObj):
+ raise ValueError("logging_obj is required")
+
+ return SpeechToCompletionBridgeHandlerInputKwargs(
+ model=model,
+ input=input,
+ voice=kwargs.get("voice"),
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ custom_llm_provider=custom_llm_provider,
+ headers=headers,
+ )
+
+ def speech(
+ self,
+ model: str,
+ input: str,
+ voice: Optional[Union[str, dict]],
+ optional_params: dict,
+ litellm_params: dict,
+ headers: dict,
+ logging_obj: "LiteLLMLoggingObj",
+ custom_llm_provider: str,
+ ) -> "HttpxBinaryResponseContent":
+ received_args = locals()
+ from litellm import completion
+ from litellm.types.utils import ModelResponse
+
+ validated_kwargs = self.validate_input_kwargs(received_args)
+ model = validated_kwargs["model"]
+ input = validated_kwargs["input"]
+ optional_params = validated_kwargs["optional_params"]
+ litellm_params = validated_kwargs["litellm_params"]
+ headers = validated_kwargs["headers"]
+ logging_obj = validated_kwargs["logging_obj"]
+ custom_llm_provider = validated_kwargs["custom_llm_provider"]
+ voice = validated_kwargs["voice"]
+
+ request_data = self.transformation_handler.transform_request(
+ model=model,
+ input=input,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ headers=headers,
+ litellm_logging_obj=logging_obj,
+ custom_llm_provider=custom_llm_provider,
+ voice=voice,
+ )
+
+ result = completion(
+ **request_data,
+ )
+
+ if isinstance(result, ModelResponse):
+ return self.transformation_handler.transform_response(
+ model_response=result,
+ )
+ else:
+ raise Exception("Unmapped response type. Got type: {}".format(type(result)))
+
+
+speech_to_completion_bridge_handler = SpeechToCompletionBridgeHandler()
diff --git a/litellm/endpoints/speech/speech_to_completion_bridge/transformation.py b/litellm/endpoints/speech/speech_to_completion_bridge/transformation.py
new file mode 100644
index 00000000000..5dce467d443
--- /dev/null
+++ b/litellm/endpoints/speech/speech_to_completion_bridge/transformation.py
@@ -0,0 +1,134 @@
+from typing import TYPE_CHECKING, Optional, Union, cast
+
+from litellm.constants import OPENAI_CHAT_COMPLETION_PARAMS
+
+if TYPE_CHECKING:
+ from litellm import Logging as LiteLLMLoggingObj
+ from litellm.types.llms.openai import HttpxBinaryResponseContent
+ from litellm.types.utils import ModelResponse
+
+
+class SpeechToCompletionBridgeTransformationHandler:
+ def transform_request(
+ self,
+ model: str,
+ input: str,
+ voice: Optional[Union[str, dict]],
+ optional_params: dict,
+ litellm_params: dict,
+ headers: dict,
+ litellm_logging_obj: "LiteLLMLoggingObj",
+ custom_llm_provider: str,
+ ) -> dict:
+ passed_optional_params = {}
+ for op in optional_params:
+ if op in OPENAI_CHAT_COMPLETION_PARAMS:
+ passed_optional_params[op] = optional_params[op]
+
+ if voice is not None:
+ if isinstance(voice, str):
+ passed_optional_params["audio"] = {"voice": voice}
+ if "response_format" in optional_params:
+ passed_optional_params["audio"]["format"] = optional_params[
+ "response_format"
+ ]
+
+ return_kwargs = {
+ "model": model,
+ "messages": [
+ {
+ "role": "user",
+ "content": input,
+ }
+ ],
+ "modalities": ["audio"],
+ **passed_optional_params,
+ **litellm_params,
+ "headers": headers,
+ "litellm_logging_obj": litellm_logging_obj,
+ "custom_llm_provider": custom_llm_provider,
+ }
+
+ # filter out None values
+ return_kwargs = {k: v for k, v in return_kwargs.items() if v is not None}
+ return return_kwargs
+
+ def _convert_pcm16_to_wav(
+ self, pcm_data: bytes, sample_rate: int = 24000, channels: int = 1
+ ) -> bytes:
+ """
+ Convert raw PCM16 data to WAV format.
+
+ Args:
+ pcm_data: Raw PCM16 audio data
+ sample_rate: Sample rate in Hz (Gemini TTS typically uses 24000)
+ channels: Number of audio channels (1 for mono)
+
+ Returns:
+ bytes: WAV formatted audio data
+ """
+ import struct
+
+ # WAV header parameters
+ byte_rate = sample_rate * channels * 2 # 2 bytes per sample (16-bit)
+ block_align = channels * 2
+ data_size = len(pcm_data)
+ file_size = 36 + data_size
+
+ # Create WAV header
+ wav_header = struct.pack(
+ "<4sI4s4sIHHIIHH4sI",
+ b"RIFF", # Chunk ID
+ file_size, # Chunk Size
+ b"WAVE", # Format
+ b"fmt ", # Subchunk1 ID
+ 16, # Subchunk1 Size (PCM)
+ 1, # Audio Format (PCM)
+ channels, # Number of Channels
+ sample_rate, # Sample Rate
+ byte_rate, # Byte Rate
+ block_align, # Block Align
+ 16, # Bits per Sample
+ b"data", # Subchunk2 ID
+ data_size, # Subchunk2 Size
+ )
+
+ return wav_header + pcm_data
+
+ def _is_gemini_tts_model(self, model: str) -> bool:
+ """Check if the model is a Gemini TTS model that returns PCM16 data."""
+ return "gemini" in model.lower() and (
+ "tts" in model.lower() or "preview-tts" in model.lower()
+ )
+
+ def transform_response(
+ self, model_response: "ModelResponse"
+ ) -> "HttpxBinaryResponseContent":
+ import base64
+
+ import httpx
+
+ from litellm.types.llms.openai import HttpxBinaryResponseContent
+ from litellm.types.utils import Choices
+
+ audio_part = cast(Choices, model_response.choices[0]).message.audio
+ if audio_part is None:
+ raise ValueError("No audio part found in the response")
+ audio_content = audio_part.data
+
+ # Decode base64 to get binary content
+ binary_data = base64.b64decode(audio_content)
+
+ # Check if this is a Gemini TTS model that returns raw PCM16 data
+ model = getattr(model_response, "model", "")
+ headers = {}
+ if self._is_gemini_tts_model(model):
+ # Convert PCM16 to WAV format for proper audio file playback
+ binary_data = self._convert_pcm16_to_wav(binary_data)
+ headers["Content-Type"] = "audio/wav"
+ else:
+ headers["Content-Type"] = "audio/mpeg"
+
+ # Create an httpx.Response object
+ response = httpx.Response(status_code=200, content=binary_data, headers=headers)
+ return HttpxBinaryResponseContent(response)
diff --git a/litellm/llms/gemini/chat/transformation.py b/litellm/llms/gemini/chat/transformation.py
index 10bfe94c1a0..37217ebfaab 100644
--- a/litellm/llms/gemini/chat/transformation.py
+++ b/litellm/llms/gemini/chat/transformation.py
@@ -1,12 +1,11 @@
-from typing import Dict, List, Optional
+from typing import List, Optional
-import litellm
from litellm.litellm_core_utils.prompt_templates.factory import (
convert_generic_image_chunk_to_openai_image_obj,
convert_to_anthropic_image_obj,
)
from litellm.types.llms.openai import AllMessageValues
-from litellm.types.llms.vertex_ai import ContentType, PartType, SpeechConfig, VoiceConfig, PrebuiltVoiceConfig
+from litellm.types.llms.vertex_ai import ContentType, PartType
from litellm.utils import supports_reasoning
from ...vertex_ai.gemini.transformation import _gemini_convert_messages_with_history
@@ -96,56 +95,6 @@ class GoogleAIStudioGeminiConfig(VertexGeminiConfig):
supported_params.append("audio")
return supported_params
- def map_openai_params(
- self,
- non_default_params: Dict,
- optional_params: Dict,
- model: str,
- drop_params: bool,
- ) -> Dict:
- # Handle audio parameter for TTS models
- if self.is_model_gemini_audio_model(model):
- for param, value in non_default_params.items():
- if param == "audio" and isinstance(value, dict):
- # Validate audio format - Gemini TTS only supports pcm16
- audio_format = value.get("format")
- if audio_format is not None and audio_format != "pcm16":
- raise ValueError(
- f"Unsupported audio format for Gemini TTS models: {audio_format}. "
- f"Gemini TTS models only support 'pcm16' format as they return audio data in L16 PCM format. "
- f"Please set audio format to 'pcm16'."
- )
-
- # Map OpenAI audio parameter to Gemini speech config
- speech_config: SpeechConfig = {}
-
- if "voice" in value:
- prebuilt_voice_config: PrebuiltVoiceConfig = {
- "voiceName": value["voice"]
- }
- voice_config: VoiceConfig = {
- "prebuiltVoiceConfig": prebuilt_voice_config
- }
- speech_config["voiceConfig"] = voice_config
-
- if speech_config:
- optional_params["speechConfig"] = speech_config
-
- # Ensure audio modality is set
- if "responseModalities" not in optional_params:
- optional_params["responseModalities"] = ["AUDIO"]
- elif "AUDIO" not in optional_params["responseModalities"]:
- optional_params["responseModalities"].append("AUDIO")
-
- if litellm.vertex_ai_safety_settings is not None:
- optional_params["safety_settings"] = litellm.vertex_ai_safety_settings
- return super().map_openai_params(
- model=model,
- non_default_params=non_default_params,
- optional_params=optional_params,
- drop_params=drop_params,
- )
-
def _transform_messages(
self, messages: List[AllMessageValues]
) -> List[ContentType]:
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index be9f5d5eb66..e20236e772d 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -304,9 +304,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
return None
for tool in value:
- openai_function_object: Optional[
- ChatCompletionToolParamFunctionChunk
- ] = None
+ openai_function_object: Optional[ChatCompletionToolParamFunctionChunk] = (
+ None
+ )
if "function" in tool: # tools list
_openai_function_object = ChatCompletionToolParamFunctionChunk( # type: ignore
**tool["function"]
@@ -489,7 +489,49 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
status_code=400,
)
- def map_openai_params(
+ def _map_audio_params(self, value: dict) -> dict:
+ """
+ Expected input:
+ {
+ "voice": "alloy",
+ "format": "mp3",
+ }
+
+ Expected output:
+ speechConfig = {
+ voiceConfig: {
+ prebuiltVoiceConfig: {
+ voiceName: "alloy",
+ }
+ }
+ }
+ """
+ from litellm.types.llms.vertex_ai import (
+ PrebuiltVoiceConfig,
+ SpeechConfig,
+ VoiceConfig,
+ )
+
+ # Validate audio format - Gemini TTS only supports pcm16
+ audio_format = value.get("format")
+ if audio_format is not None and audio_format != "pcm16":
+ raise ValueError(
+ f"Unsupported audio format for Gemini TTS models: {audio_format}. "
+ f"Gemini TTS models only support 'pcm16' format as they return audio data in L16 PCM format. "
+ f"Please set audio format to 'pcm16'."
+ )
+
+ # Map OpenAI audio parameter to Gemini speech config
+ speech_config: SpeechConfig = {}
+
+ if "voice" in value:
+ prebuilt_voice_config: PrebuiltVoiceConfig = {"voiceName": value["voice"]}
+ voice_config: VoiceConfig = {"prebuiltVoiceConfig": prebuilt_voice_config}
+ speech_config["voiceConfig"] = voice_config
+
+ return cast(dict, speech_config)
+
+ def map_openai_params( # noqa: PLR0915
self,
non_default_params: Dict,
optional_params: Dict,
@@ -507,6 +549,8 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
optional_params["stream"] = value
elif param == "n":
optional_params["candidate_count"] = value
+ elif param == "audio" and isinstance(value, dict):
+ optional_params["speechConfig"] = self._map_audio_params(value)
elif param == "stop":
if isinstance(value, str):
optional_params["stop_sequences"] = [value]
@@ -552,14 +596,14 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
elif param == "seed":
optional_params["seed"] = value
elif param == "reasoning_effort" and isinstance(value, str):
- optional_params[
- "thinkingConfig"
- ] = VertexGeminiConfig._map_reasoning_effort_to_thinking_budget(value)
+ optional_params["thinkingConfig"] = (
+ VertexGeminiConfig._map_reasoning_effort_to_thinking_budget(value)
+ )
elif param == "thinking":
- optional_params[
- "thinkingConfig"
- ] = VertexGeminiConfig._map_thinking_param(
- cast(AnthropicThinkingParam, value)
+ optional_params["thinkingConfig"] = (
+ VertexGeminiConfig._map_thinking_param(
+ cast(AnthropicThinkingParam, value)
+ )
)
elif param == "modalities" and isinstance(value, list):
response_modalities = self.map_response_modalities(value)
@@ -571,6 +615,15 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
)
if litellm.vertex_ai_safety_settings is not None:
optional_params["safety_settings"] = litellm.vertex_ai_safety_settings
+
+ # if audio param is set, ensure responseModalities is set to AUDIO
+ audio_param = optional_params.get("speechConfig")
+ if audio_param is not None:
+ if "responseModalities" not in optional_params:
+ optional_params["responseModalities"] = ["AUDIO"]
+ elif "AUDIO" not in optional_params["responseModalities"]:
+ optional_params["responseModalities"].append("AUDIO")
+
return optional_params
def get_mapped_special_auth_params(self) -> dict:
@@ -1263,28 +1316,28 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
## ADD METADATA TO RESPONSE ##
setattr(model_response, "vertex_ai_grounding_metadata", grounding_metadata)
- model_response._hidden_params[
- "vertex_ai_grounding_metadata"
- ] = grounding_metadata
+ model_response._hidden_params["vertex_ai_grounding_metadata"] = (
+ grounding_metadata
+ )
setattr(
model_response, "vertex_ai_url_context_metadata", url_context_metadata
)
- model_response._hidden_params[
- "vertex_ai_url_context_metadata"
- ] = url_context_metadata
+ model_response._hidden_params["vertex_ai_url_context_metadata"] = (
+ url_context_metadata
+ )
setattr(model_response, "vertex_ai_safety_results", safety_ratings)
- model_response._hidden_params[
- "vertex_ai_safety_results"
- ] = safety_ratings # older approach - maintaining to prevent regressions
+ model_response._hidden_params["vertex_ai_safety_results"] = (
+ safety_ratings # older approach - maintaining to prevent regressions
+ )
## ADD CITATION METADATA ##
setattr(model_response, "vertex_ai_citation_metadata", citation_metadata)
- model_response._hidden_params[
- "vertex_ai_citation_metadata"
- ] = citation_metadata # older approach - maintaining to prevent regressions
+ model_response._hidden_params["vertex_ai_citation_metadata"] = (
+ citation_metadata # older approach - maintaining to prevent regressions
+ )
except Exception as e:
raise VertexAIError(
diff --git a/litellm/main.py b/litellm/main.py
index 59a7764d31a..41294d84f35 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -2810,9 +2810,9 @@ def completion( # type: ignore # noqa: PLR0915
"aws_region_name" not in optional_params
or optional_params["aws_region_name"] is None
):
- optional_params[
- "aws_region_name"
- ] = aws_bedrock_client.meta.region_name
+ optional_params["aws_region_name"] = (
+ aws_bedrock_client.meta.region_name
+ )
bedrock_route = BedrockModelInfo.get_bedrock_route(model)
if bedrock_route == "converse":
@@ -4589,9 +4589,9 @@ def adapter_completion(
new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs)
response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore
- translated_response: Optional[
- Union[BaseModel, AdapterCompletionStreamWrapper]
- ] = None
+ translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = (
+ None
+ )
if isinstance(response, ModelResponse):
translated_response = translation_obj.translate_completion_output_params(
response=response
@@ -5192,6 +5192,21 @@ def speech( # noqa: PLR0915
model=model,
llm_provider=custom_llm_provider,
)
+ if "gemini" in model:
+ from .endpoints.speech.speech_to_completion_bridge.handler import (
+ speech_to_completion_bridge_handler,
+ )
+
+ return speech_to_completion_bridge_handler.speech(
+ model=model,
+ input=input,
+ voice=voice,
+ optional_params=optional_params,
+ litellm_params=litellm_params_dict,
+ headers=headers or {},
+ logging_obj=logging_obj,
+ custom_llm_provider=custom_llm_provider,
+ )
response = vertex_text_to_speech.audio_speech(
_is_async=aspeech,
vertex_credentials=vertex_credentials,
@@ -5206,6 +5221,21 @@ def speech( # noqa: PLR0915
kwargs=kwargs,
logging_obj=logging_obj,
)
+ elif custom_llm_provider == "gemini":
+ from .endpoints.speech.speech_to_completion_bridge.handler import (
+ speech_to_completion_bridge_handler,
+ )
+
+ return speech_to_completion_bridge_handler.speech(
+ model=model,
+ input=input,
+ voice=voice,
+ optional_params=optional_params,
+ litellm_params=litellm_params_dict,
+ headers=headers or {},
+ logging_obj=logging_obj,
+ custom_llm_provider=custom_llm_provider,
+ )
if response is None:
raise Exception(
@@ -5549,9 +5579,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(content_chunks) > 0:
- response["choices"][0]["message"][
- "content"
- ] = processor.get_combined_content(content_chunks)
+ response["choices"][0]["message"]["content"] = (
+ processor.get_combined_content(content_chunks)
+ )
reasoning_chunks = [
chunk
@@ -5562,9 +5592,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(reasoning_chunks) > 0:
- response["choices"][0]["message"][
- "reasoning_content"
- ] = processor.get_combined_reasoning_content(reasoning_chunks)
+ response["choices"][0]["message"]["reasoning_content"] = (
+ processor.get_combined_reasoning_content(reasoning_chunks)
+ )
audio_chunks = [
chunk
diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml
index 763d984ca4f..107769c26ae 100644
--- a/litellm/proxy/_new_secret_config.yaml
+++ b/litellm/proxy/_new_secret_config.yaml
@@ -3,6 +3,14 @@ model_list:
litellm_params:
model: codex-mini-latest
api_key: os.environ/OPENAI_API_KEY
+ - model_name: "gemini/gemini-2.5-flash-preview-tts"
+ litellm_params:
+ model: gemini/gemini-2.5-flash-preview-tts
+ api_key: os.environ/GEMINI_API_KEY
+ - model_name: "gpt-4o-mini-tts"
+ litellm_params:
+ model: openai/gpt-4o-mini-tts
+ api_key: os.environ/OPENAI_API_KEY
- model_name: "gpt-4o-mini-openai"
litellm_params:
model: gpt-4o-mini
@@ -97,16 +105,6 @@ general_settings:
token_rate_limit_type: "output"
# master_key: os.environ/PROXY_MASTER_KEY
-litellm_settings:
- # cache: true
- # cache_params:
- # type: redis
- # ttl: 600
- # password: os.environ/REDIS_PASSWORD
- # supported_call_types: ["acompletion", "completion"]
- callbacks: ["prometheus", "langfuse"]
-
-
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index f8753d10f98..55d3d895741 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -421,9 +421,9 @@ except ImportError:
server_root_path = os.getenv("SERVER_ROOT_PATH", "")
_license_check = LicenseCheck()
premium_user: bool = _license_check.is_premium()
-premium_user_data: Optional[
- "EnterpriseLicenseData"
-] = _license_check.airgapped_license_data
+premium_user_data: Optional["EnterpriseLicenseData"] = (
+ _license_check.airgapped_license_data
+)
global_max_parallel_request_retries_env: Optional[str] = os.getenv(
"LITELLM_GLOBAL_MAX_PARALLEL_REQUEST_RETRIES"
)
@@ -883,9 +883,9 @@ model_max_budget_limiter = _PROXY_VirtualKeyModelMaxBudgetLimiter(
dual_cache=user_api_key_cache
)
litellm.logging_callback_manager.add_litellm_callback(model_max_budget_limiter)
-redis_usage_cache: Optional[
- RedisCache
-] = None # redis cache used for tracking spend, tpm/rpm limits
+redis_usage_cache: Optional[RedisCache] = (
+ None # redis cache used for tracking spend, tpm/rpm limits
+)
user_custom_auth = None
user_custom_key_generate = None
user_custom_sso = None
@@ -1212,9 +1212,9 @@ async def update_cache( # noqa: PLR0915
_id = "team_id:{}".format(team_id)
try:
# Fetch the existing cost for the given user
- existing_spend_obj: Optional[
- LiteLLM_TeamTable
- ] = await user_api_key_cache.async_get_cache(key=_id)
+ existing_spend_obj: Optional[LiteLLM_TeamTable] = (
+ await user_api_key_cache.async_get_cache(key=_id)
+ )
if existing_spend_obj is None:
# do nothing if team not in api key cache
return
@@ -2790,10 +2790,10 @@ class ProxyConfig:
)
try:
- guardrails_in_db: List[
- Guardrail
- ] = await GuardrailRegistry.get_all_guardrails_from_db(
- prisma_client=prisma_client
+ guardrails_in_db: List[Guardrail] = (
+ await GuardrailRegistry.get_all_guardrails_from_db(
+ prisma_client=prisma_client
+ )
)
verbose_proxy_logger.debug(
"guardrails from the DB %s", str(guardrails_in_db)
@@ -3020,9 +3020,9 @@ async def initialize( # noqa: PLR0915
user_api_base = api_base
dynamic_config[user_model]["api_base"] = api_base
if api_version:
- os.environ[
- "AZURE_API_VERSION"
- ] = api_version # set this for azure - litellm can read this from the env
+ os.environ["AZURE_API_VERSION"] = (
+ api_version # set this for azure - litellm can read this from the env
+ )
if max_tokens: # model-specific param
dynamic_config[user_model]["max_tokens"] = max_tokens
if temperature: # model-specific param
@@ -4263,8 +4263,16 @@ async def audio_speech(
user_api_key_dict=user_api_key_dict,
request_data=data,
)
+ # Determine media type based on model type
+ media_type = "audio/mpeg" # Default for OpenAI TTS
+ request_model = data.get("model", "")
+ if "gemini" in request_model.lower() and (
+ "tts" in request_model.lower() or "preview-tts" in request_model.lower()
+ ):
+ media_type = "audio/wav" # Gemini TTS returns WAV format after conversion
+
return StreamingResponse(
- generate(response), media_type="audio/mpeg", headers=custom_headers # type: ignore
+ generate(response), media_type=media_type, headers=custom_headers # type: ignore
)
except Exception as e:
@@ -7882,9 +7890,9 @@ async def get_config_list(
hasattr(sub_field_info, "description")
and sub_field_info.description is not None
):
- nested_fields[
- idx
- ].field_description = sub_field_info.description
+ nested_fields[idx].field_description = (
+ sub_field_info.description
+ )
idx += 1
_stored_in_db = None
diff --git a/tests/local_testing/test_audio_speech.py b/tests/local_testing/test_audio_speech.py
index da8872a785e..9e8817d6e62 100644
--- a/tests/local_testing/test_audio_speech.py
+++ b/tests/local_testing/test_audio_speech.py
@@ -315,3 +315,13 @@ def test_audio_speech_cost_calc():
]
print(f"standard_logging_payload: {standard_logging_payload}")
assert standard_logging_payload["response_cost"] > 0
+
+
+def test_audio_speech_gemini():
+ result = litellm.speech(
+ model="gemini/gemini-2.5-flash-preview-tts",
+ input="the quick brown fox jumped over the lazy dogs",
+ api_key=os.getenv("GEMINI_API_KEY"),
+ )
+
+ print(result)