Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions litellm/litellm_core_utils/audio_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,34 @@ def process_audio_file(audio_file: FileTypes) -> ProcessedAudioFile:
return ProcessedAudioFile(file_content=file_content, filename=filename, content_type=content_type)


BARE_ISO_639_1_TO_BCP47 = {
"en": "en-US",
"es": "es-ES",
"de": "de-DE",
"fr": "fr-FR",
"it": "it-IT",
"pt": "pt-BR",
"ja": "ja-JP",
"ko": "ko-KR",
"zh": "zh-CN",
"ru": "ru-RU",
"hi": "hi-IN",
"ar": "ar-SA",
}


def normalize_transcription_language_to_bcp47(language: str) -> str:
"""
OpenAI's transcription `language` param accepts bare ISO-639-1 codes like
``en``; speech APIs such as Google Speech-to-Text and NVIDIA Riva require
BCP-47 like ``en-US``. Map the most common bare codes and pass through
anything already region-qualified (or unknown, for a clear provider error).
"""
if "-" in language:
return language
return BARE_ISO_639_1_TO_BCP47.get(language.lower(), language)


def get_audio_file_name(file_obj: FileTypes) -> str:
"""
Safely get the name of a file-like object or return its string representation.
Expand Down
18 changes: 8 additions & 10 deletions litellm/llms/custom_httpx/llm_http_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1300,16 +1300,15 @@ def audio_transcriptions(
if client is None or not isinstance(client, HTTPHandler):
client = _get_httpx_client()

json_data = data if files is None and isinstance(data, dict) else None

try:
# Make the POST request - clean and simple, always use data and files
response = client.post(
url=complete_url,
headers=headers,
data=data,
data=data if json_data is None else None,
files=files,
json=(
data if files is None and isinstance(data, dict) else None
), # Use json param only when no files and data is dict
json=json_data,
timeout=timeout,
)
except Exception as e:
Expand Down Expand Up @@ -1373,16 +1372,15 @@ async def async_audio_transcriptions(
else:
async_httpx_client = client

json_data = data if files is None and isinstance(data, dict) else None

try:
# Make the async POST request - clean and simple, always use data and files
response = await async_httpx_client.post(
url=complete_url,
headers=headers,
data=data,
data=data if json_data is None else None,
files=files,
json=(
data if files is None and isinstance(data, dict) else None
), # Use json param only when no files and data is dict
json=json_data,
timeout=timeout,
)
except Exception as e:
Expand Down
178 changes: 178 additions & 0 deletions litellm/llms/vertex_ai/audio_transcription/transformation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import base64
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

from httpx import Headers, Response

from litellm.litellm_core_utils.audio_utils.utils import (
normalize_transcription_language_to_bcp47,
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.llms.vertex_ai.common_utils import VertexAIError, validate_vertex_location
from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
from litellm.types.llms.openai import (
AllMessageValues,
OpenAIAudioTranscriptionOptionalParams,
)
from litellm.types.llms.vertex_ai_speech_to_text import (
VertexSpeechToTextAutoDecodingConfig,
VertexSpeechToTextRecognitionConfig,
VertexSpeechToTextRecognitionFeatures,
VertexSpeechToTextRecognizeRequest,
VertexSpeechToTextRecognizeResponse,
)
from litellm.types.utils import FileTypes, TranscriptionResponse

DEFAULT_SPEECH_TO_TEXT_LOCATION = "us"
AUTO_LANGUAGE_CODE = "auto"
_URL_UNSAFE_PROJECT_CHARS = ("/", "?", "#", "\\", ":", " ", "\t", "\n", "\r")


class VertexAIAudioTranscriptionConfig(BaseAudioTranscriptionConfig, VertexBase):
def __init__(self) -> None:
BaseAudioTranscriptionConfig.__init__(self)
VertexBase.__init__(self)

def get_supported_openai_params(self, model: str) -> list[OpenAIAudioTranscriptionOptionalParams]:
return ["language", "response_format"]
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

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)
return {
**optional_params,
**{k: v for k, v in non_default_params.items() if k in supported_params},
}

def get_error_class(self, error_message: str, status_code: int, headers: dict | Headers) -> BaseLLMException:
return VertexAIError(status_code=status_code, message=error_message, headers=headers)

def validate_environment(
self,
headers: dict,
model: str,
messages: list[AllMessageValues],
optional_params: dict,
litellm_params: dict,
api_key: str | None = None,
api_base: str | None = None,
) -> dict:
access_token, project_id = self._ensure_access_token(
credentials=self.safe_get_vertex_ai_credentials(litellm_params),
project_id=self.safe_get_vertex_ai_project(litellm_params),
custom_llm_provider="vertex_ai",
)
return {
**headers,
"Authorization": f"Bearer {access_token}",
"x-goog-user-project": project_id,
"Content-Type": "application/json",
}

def get_complete_url(
self,
api_base: str | None,
api_key: str | None,
model: str,
optional_params: dict,
litellm_params: dict,
stream: bool | None = None,
) -> str:
location = self._validate_location(self.safe_get_vertex_ai_location(litellm_params))
project_id = self._validate_project_id(
self.safe_get_vertex_ai_project(litellm_params) or self._resolve_project_id_from_credentials(litellm_params)
)
host = "speech.googleapis.com" if location == "global" else f"{location}-speech.googleapis.com"
base_url = (api_base or f"https://{host}").rstrip("/")
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
return f"{base_url}/v2/projects/{project_id}/locations/{location}/recognizers/_:recognize"

@staticmethod
def _validate_location(location: str | None) -> str:
try:
return validate_vertex_location(location or DEFAULT_SPEECH_TO_TEXT_LOCATION)
except ValueError as e:
raise VertexAIError(status_code=400, message=str(e)) from e

@staticmethod
def _validate_project_id(project_id: str) -> str:
if not project_id or ".." in project_id or any(c in project_id for c in _URL_UNSAFE_PROJECT_CHARS):
raise VertexAIError(status_code=400, message=f"Invalid vertex_project format: {project_id!r}")
return project_id

def _resolve_project_id_from_credentials(self, litellm_params: dict) -> str:
_, project_id = self._ensure_access_token(
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
credentials=self.safe_get_vertex_ai_credentials(litellm_params),
project_id=None,
custom_llm_provider="vertex_ai",
)
return project_id

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)
language = optional_params.get("language")
language_codes = (
[normalize_transcription_language_to_bcp47(language)]
if isinstance(language, str) and language
else [AUTO_LANGUAGE_CODE]
)
request_body = VertexSpeechToTextRecognizeRequest(
config=VertexSpeechToTextRecognitionConfig(
model=model.removeprefix("vertex_ai/"),
languageCodes=language_codes,
features=VertexSpeechToTextRecognitionFeatures(enableAutomaticPunctuation=True),
autoDecodingConfig=VertexSpeechToTextAutoDecodingConfig(),
),
content=base64.b64encode(processed_audio.file_content).decode("utf-8"),
)
return AudioTranscriptionRequestData(data=dict(request_body))

def transform_audio_transcription_response(
self,
raw_response: Response,
) -> TranscriptionResponse:
try:
response_json = raw_response.json()
except ValueError:
raise VertexAIError(
status_code=raw_response.status_code,
message=f"Received non-JSON response from Google Speech-to-Text: {raw_response.text}",
)
parsed = VertexSpeechToTextRecognizeResponse.model_validate(response_json)
transcripts = tuple(
result.alternatives[0].transcript
for result in parsed.results
if result.alternatives and result.alternatives[0].transcript
)
response = TranscriptionResponse(text=" ".join(transcripts))
response["task"] = "transcribe"
detected_language = next((result.languageCode for result in parsed.results if result.languageCode), None)
if detected_language is not None:
response["language"] = detected_language
billed_duration = _parse_duration_seconds(parsed.metadata.totalBilledDuration if parsed.metadata else None)
if billed_duration is not None:
response["duration"] = billed_duration
response._hidden_params = response_json
return response


def _parse_duration_seconds(duration: str | None) -> float | None:
if duration is None or not duration.endswith("s"):
return None
try:
return float(duration[:-1])
except ValueError:
return None
35 changes: 27 additions & 8 deletions litellm/llms/vertex_ai/common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,28 @@ def get_vertex_base_model_name(model: str) -> str:
return model


def validate_vertex_location(vertex_location: Optional[str]) -> str:
"""
Validate a Vertex AI location before interpolating it into a request host or
URL path.

``vertex_location`` is client-controllable on the proxy (it flows in from the
request body), so it must never be trusted verbatim in a URL or an attacker
could point the host at their own server and exfiltrate the admin's Google
access token. Allow the special ``global`` control plane and otherwise require
a lowercase alphanumeric-plus-hyphen token (e.g. ``us``, ``us-central1``,
``eu``), which rejects host injection like ``attacker.example/`` or
``evil.com#``.
"""
if vertex_location == "global":
return vertex_location
if vertex_location is None:
raise ValueError("vertex_location is required")
if not re.match(r"^[a-z][a-z0-9-]*$", vertex_location):
raise ValueError("Invalid vertex_location format")
return vertex_location


def get_vertex_base_url(
vertex_location: Optional[str],
) -> str:
Expand All @@ -321,15 +343,12 @@ def get_vertex_base_url(
- Multi-region geographies (e.g. ``us``, ``eu``) use ``aiplatform.{geo}.rep.googleapis.com``.
- Regional locations (e.g. ``us-central1``) use ``{region}-aiplatform.googleapis.com``.
"""
if vertex_location == "global":
validated_location = validate_vertex_location(vertex_location)
if validated_location == "global":
return "https://aiplatform.googleapis.com"
if vertex_location is None:
raise ValueError("vertex_location is required")
if not re.match(r"^[a-z][a-z0-9-]*$", vertex_location):
raise ValueError("Invalid vertex_location format")
if "-" not in vertex_location:
return f"https://aiplatform.{vertex_location}.rep.googleapis.com"
return f"https://{vertex_location}-aiplatform.googleapis.com"
if "-" not in validated_location:
return f"https://aiplatform.{validated_location}.rep.googleapis.com"
return f"https://{validated_location}-aiplatform.googleapis.com"


def _get_embedding_url(
Expand Down
13 changes: 13 additions & 0 deletions litellm/model_prices_and_context_window_backup.json
Original file line number Diff line number Diff line change
Expand Up @@ -34655,6 +34655,19 @@
"/v1/audio/speech"
]
},
"vertex_ai/chirp_3": {
"input_cost_per_second": 0.00026667,
"litellm_provider": "vertex_ai",
"metadata": {
"calculation": "$0.016/60 seconds = $0.00026667 per second",
"original_pricing_per_minute": 0.016
},
"mode": "audio_transcription",
"source": "https://cloud.google.com/speech-to-text/pricing",
"supported_endpoints": [
"/v1/audio/transcriptions"
]
},
"vertex_ai/claude-3-5-haiku": {
"input_cost_per_token": 1e-06,
"litellm_provider": "vertex_ai-anthropic_models",
Expand Down
40 changes: 40 additions & 0 deletions litellm/types/llms/vertex_ai_speech_to_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from pydantic import BaseModel
from typing_extensions import TypedDict


class VertexSpeechToTextAutoDecodingConfig(TypedDict):
pass


class VertexSpeechToTextRecognitionFeatures(TypedDict):
enableAutomaticPunctuation: bool


class VertexSpeechToTextRecognitionConfig(TypedDict):
model: str
languageCodes: list[str]
features: VertexSpeechToTextRecognitionFeatures
autoDecodingConfig: VertexSpeechToTextAutoDecodingConfig


class VertexSpeechToTextRecognizeRequest(TypedDict):
config: VertexSpeechToTextRecognitionConfig
content: str


class VertexSpeechToTextAlternative(BaseModel):
transcript: str | None = None


class VertexSpeechToTextResult(BaseModel):
alternatives: list[VertexSpeechToTextAlternative] = []
languageCode: str | None = None


class VertexSpeechToTextResponseMetadata(BaseModel):
totalBilledDuration: str | None = None


class VertexSpeechToTextRecognizeResponse(BaseModel):
results: list[VertexSpeechToTextResult] = []
metadata: VertexSpeechToTextResponseMetadata | None = None
6 changes: 6 additions & 0 deletions litellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8097,6 +8097,12 @@ def get_provider_audio_transcription_config(
)

return SonioxAudioTranscriptionConfig()
elif litellm.LlmProviders.VERTEX_AI == provider:
from litellm.llms.vertex_ai.audio_transcription.transformation import (
VertexAIAudioTranscriptionConfig,
)

return VertexAIAudioTranscriptionConfig()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vertex transcription routes all models

Medium Severity

get_provider_audio_transcription_config returns VertexAIAudioTranscriptionConfig for every vertex_ai transcription call, without checking that the model is an audio-transcription entry (for example mode in the cost map). Before this change those calls failed as unmapped; now they are sent to Google Speech-to-Text with the chat model id in the payload.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2b87067. Configure here.

@mateo-berri mateo-berri Jul 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

every provider branch there routes unconditionally (OpenAI sends any model to whisper), nothing working is shadowed, and misuse now gets Google's clear 400 instead of "Unmapped provider"

return None

@staticmethod
Expand Down
13 changes: 13 additions & 0 deletions model_prices_and_context_window.json
Original file line number Diff line number Diff line change
Expand Up @@ -34829,6 +34829,19 @@
"/v1/audio/speech"
]
},
"vertex_ai/chirp_3": {
"input_cost_per_second": 0.00026667,
"litellm_provider": "vertex_ai",
"metadata": {
"calculation": "$0.016/60 seconds = $0.00026667 per second",
"original_pricing_per_minute": 0.016
},
"mode": "audio_transcription",
"source": "https://cloud.google.com/speech-to-text/pricing",
"supported_endpoints": [
"/v1/audio/transcriptions"
]
},
"vertex_ai/claude-3-5-haiku": {
"input_cost_per_token": 1e-06,
"litellm_provider": "vertex_ai-anthropic_models",
Expand Down
Loading
Loading