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(vertex_ai): add Google Cloud Speech-to-Text Chirp 3 transcription support (#32274)

Mateo Wang43b0a25f07ad
diff --git a/litellm/litellm_core_utils/audio_utils/utils.py b/litellm/litellm_core_utils/audio_utils/utils.py
index f86243c73b7..e5007ceec34 100644
--- a/litellm/litellm_core_utils/audio_utils/utils.py
+++ b/litellm/litellm_core_utils/audio_utils/utils.py
@@ -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.
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 05401488f27..e48011f23f1 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -1300,16 +1300,15 @@ class BaseLLMHTTPHandler:
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:
@@ -1373,16 +1372,15 @@ class BaseLLMHTTPHandler:
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:
diff --git a/litellm/llms/vertex_ai/audio_transcription/transformation.py b/litellm/llms/vertex_ai/audio_transcription/transformation.py
new file mode 100644
index 00000000000..03769bf2601
--- /dev/null
+++ b/litellm/llms/vertex_ai/audio_transcription/transformation.py
@@ -0,0 +1,194 @@
+import base64
+
+from httpx import Headers, Response
+
+import litellm
+from litellm.exceptions import UnsupportedParamsError
+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"
+SUPPORTED_RESPONSE_FORMATS = ("json", "text")
+_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"]
+
+ 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)
+ mapped = {
+ **optional_params,
+ **{k: v for k, v in non_default_params.items() if k in supported_params},
+ }
+ response_format = mapped.get("response_format")
+ if response_format is None or response_format in SUPPORTED_RESPONSE_FORMATS:
+ return mapped
+ if drop_params or litellm.drop_params:
+ return {k: v for k, v in mapped.items() if k != "response_format"}
+ raise UnsupportedParamsError(
+ status_code=400,
+ message=(
+ f"Google Speech-to-Text does not support response_format={response_format!r}. "
+ f"Supported values: {', '.join(SUPPORTED_RESPONSE_FORMATS)}. "
+ "To drop unsupported openai params from the call, set `litellm.drop_params = True`"
+ ),
+ )
+
+ 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("/")
+ 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(
+ 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
diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py
index 36522dfe396..7dcb4dcf2e8 100644
--- a/litellm/llms/vertex_ai/common_utils.py
+++ b/litellm/llms/vertex_ai/common_utils.py
@@ -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:
@@ -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(
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index b8b9d0c6877..cbca0744ed9 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -34957,6 +34957,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",
diff --git a/litellm/types/llms/vertex_ai_speech_to_text.py b/litellm/types/llms/vertex_ai_speech_to_text.py
new file mode 100644
index 00000000000..8995d98385b
--- /dev/null
+++ b/litellm/types/llms/vertex_ai_speech_to_text.py
@@ -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
diff --git a/litellm/utils.py b/litellm/utils.py
index 83d129339a4..f9bb84101e7 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -8097,6 +8097,12 @@ class ProviderConfigManager:
)
return SonioxAudioTranscriptionConfig()
+ elif litellm.LlmProviders.VERTEX_AI == provider:
+ from litellm.llms.vertex_ai.audio_transcription.transformation import (
+ VertexAIAudioTranscriptionConfig,
+ )
+
+ return VertexAIAudioTranscriptionConfig()
return None
@staticmethod
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index aa439f4d8c2..6cfa7c9e8be 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -35131,6 +35131,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",
diff --git a/tests/test_litellm/litellm_core_utils/test_audio_utils.py b/tests/test_litellm/litellm_core_utils/test_audio_utils.py
index b2645c8f2ce..0e8176fffce 100644
--- a/tests/test_litellm/litellm_core_utils/test_audio_utils.py
+++ b/tests/test_litellm/litellm_core_utils/test_audio_utils.py
@@ -326,3 +326,24 @@ class TestGetAudioFileContentHash:
assert isinstance(hash_result, str)
assert len(hash_result) == 64, "Should return valid hash even on fallback"
+
+
+class TestNormalizeTranscriptionLanguageToBcp47:
+ @pytest.mark.parametrize(
+ "language,expected",
+ [
+ ("en", "en-US"),
+ ("EN", "en-US"),
+ ("ja", "ja-JP"),
+ ("en-US", "en-US"),
+ ("en-GB", "en-GB"),
+ ("auto", "auto"),
+ ("xx", "xx"),
+ ],
+ )
+ def test_normalization(self, language, expected):
+ from litellm.litellm_core_utils.audio_utils.utils import (
+ normalize_transcription_language_to_bcp47,
+ )
+
+ assert normalize_transcription_language_to_bcp47(language) == expected
diff --git a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
index 0b4187d1bcf..961f95a0659 100644
--- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
+++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
@@ -1,4 +1,5 @@
import asyncio
+import json
import os
import sys
from unittest.mock import AsyncMock, Mock, patch
@@ -12,6 +13,11 @@ from litellm.integrations.code_interpreter_interception.handler import (
CodeInterpreterInterceptionLogger,
LITELLM_CODE_EXECUTION_TOOL_NAME,
)
+from litellm.llms.base_llm.audio_transcription.transformation import (
+ AudioTranscriptionRequestData,
+ BaseAudioTranscriptionConfig,
+)
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
from litellm.llms.custom_httpx.llm_http_handler import (
BaseLLMHTTPHandler,
@@ -19,6 +25,7 @@ from litellm.llms.custom_httpx.llm_http_handler import (
)
from litellm.types.llms.openai import ResponsesAPIResponse
from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import TranscriptionResponse
_ACTIVE_KEY = "_code_interpreter_interception_active"
_SANDBOX_KEY = "_code_interpreter_interception_sandbox_key"
@@ -1585,3 +1592,96 @@ async def test_realtime_backend_open_does_not_retry_auth_failure(rejection):
await BaseLLMHTTPHandler._open_realtime_backend_ws(fake, "wss://backend.example/live", {}, None)
assert fake.attempts == 1
+
+
+class _JSONBodyAudioTranscriptionConfig(BaseAudioTranscriptionConfig):
+ def get_supported_openai_params(self, model):
+ return []
+
+ def map_openai_params(self, non_default_params, optional_params, model, drop_params):
+ return optional_params
+
+ def validate_environment(
+ self,
+ headers,
+ model,
+ messages,
+ optional_params,
+ litellm_params,
+ api_key=None,
+ api_base=None,
+ ):
+ return {**headers, "Authorization": "Bearer test-token"}
+
+ def get_complete_url(self, api_base, api_key, model, optional_params, litellm_params, stream=None):
+ return "https://transcription.example/recognize"
+
+ def transform_audio_transcription_request(self, model, audio_file, optional_params, litellm_params):
+ return AudioTranscriptionRequestData(data={"config": {"model": model}, "content": "YXVkaW8="})
+
+ def transform_audio_transcription_response(self, raw_response):
+ return TranscriptionResponse(text=raw_response.json()["text"])
+
+ def get_error_class(self, error_message, status_code, headers):
+ return BaseLLMException(message=error_message, status_code=status_code, headers=headers)
+
+
+def _json_transcription_call_kwargs(provider_config):
+ return {
+ "model": "test-model",
+ "audio_file": b"raw-audio",
+ "optional_params": {},
+ "litellm_params": {},
+ "model_response": TranscriptionResponse(),
+ "timeout": 10.0,
+ "max_retries": 0,
+ "logging_obj": Mock(),
+ "api_key": None,
+ "api_base": None,
+ "custom_llm_provider": "custom",
+ "headers": {},
+ "provider_config": provider_config,
+ }
+
+
+def _capture_json_transcription_request(captured):
+ def respond(request):
+ captured["content_type"] = request.headers.get("content-type")
+ captured["body"] = json.loads(request.content)
+ return httpx.Response(200, json={"text": "transcribed"})
+
+ return respond
+
+
+def test_audio_transcriptions_sends_dict_data_as_json_body():
+ """Regression: dict request data was passed to httpx's data= param, which
+ form-encodes it and silently ignores json=; JSON-body providers (e.g.
+ Google Speech-to-Text) need an application/json body."""
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_json_transcription_request(captured))))
+
+ response = BaseLLMHTTPHandler().audio_transcriptions(
+ client=client,
+ atranscription=False,
+ **_json_transcription_call_kwargs(_JSONBodyAudioTranscriptionConfig()),
+ )
+
+ assert captured["content_type"] == "application/json"
+ assert captured["body"] == {"config": {"model": "test-model"}, "content": "YXVkaW8="}
+ assert response.text == "transcribed"
+
+
+async def test_async_audio_transcriptions_sends_dict_data_as_json_body():
+ captured = {}
+ client = AsyncHTTPHandler()
+ client.client = httpx.AsyncClient(transport=httpx.MockTransport(_capture_json_transcription_request(captured)))
+
+ response = await BaseLLMHTTPHandler().async_audio_transcriptions(
+ client=client,
+ **_json_transcription_call_kwargs(_JSONBodyAudioTranscriptionConfig()),
+ )
+
+ assert captured["content_type"] == "application/json"
+ assert captured["body"] == {"config": {"model": "test-model"}, "content": "YXVkaW8="}
+ assert response.text == "transcribed"
diff --git a/tests/test_litellm/llms/vertex_ai/audio_transcription/__init__.py b/tests/test_litellm/llms/vertex_ai/audio_transcription/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/test_litellm/llms/vertex_ai/audio_transcription/test_vertex_ai_audio_transcription_transformation.py b/tests/test_litellm/llms/vertex_ai/audio_transcription/test_vertex_ai_audio_transcription_transformation.py
new file mode 100644
index 00000000000..3fa28699f73
--- /dev/null
+++ b/tests/test_litellm/llms/vertex_ai/audio_transcription/test_vertex_ai_audio_transcription_transformation.py
@@ -0,0 +1,336 @@
+import base64
+import json
+import os
+import sys
+from urllib.parse import urlparse
+
+import httpx
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../../../.."))
+
+import litellm
+from litellm.llms.vertex_ai.audio_transcription.transformation import (
+ VertexAIAudioTranscriptionConfig,
+)
+from litellm.llms.vertex_ai.common_utils import VertexAIError
+from litellm.types.utils import LlmProviders
+from litellm.utils import ProviderConfigManager, get_optional_params_transcription
+
+
+def config():
+ return VertexAIAudioTranscriptionConfig()
+
+
+class TestGetCompleteUrl:
+ def test_defaults_to_us_regional_host(self, config):
+ url = config.get_complete_url(
+ api_base=None,
+ api_key=None,
+ model="chirp_3",
+ optional_params={},
+ litellm_params={"vertex_project": "test-project"},
+ )
+ assert url == "https://us-speech.googleapis.com/v2/projects/test-project/locations/us/recognizers/_:recognize"
+
+ def test_uses_vertex_location_for_regional_host(self, config):
+ url = config.get_complete_url(
+ api_base=None,
+ api_key=None,
+ model="chirp_3",
+ optional_params={},
+ litellm_params={"vertex_project": "test-project", "vertex_location": "eu"},
+ )
+ assert url == "https://eu-speech.googleapis.com/v2/projects/test-project/locations/eu/recognizers/_:recognize"
+
+ def test_global_location_uses_unprefixed_host(self, config):
+ url = config.get_complete_url(
+ api_base=None,
+ api_key=None,
+ model="chirp_3",
+ optional_params={},
+ litellm_params={"vertex_project": "test-project", "vertex_location": "global"},
+ )
+ assert url == "https://speech.googleapis.com/v2/projects/test-project/locations/global/recognizers/_:recognize"
+
+ def test_api_base_override(self, config):
+ url = config.get_complete_url(
+ api_base="http://localhost:8080/",
+ api_key=None,
+ model="chirp_3",
+ optional_params={},
+ litellm_params={"vertex_project": "test-project"},
+ )
+ assert url == "http://localhost:8080/v2/projects/test-project/locations/us/recognizers/_:recognize"
+
+ @pytest.mark.parametrize(
+ "location,expected_netloc",
+ [
+ ("us", "us-speech.googleapis.com"),
+ ("us-central1", "us-central1-speech.googleapis.com"),
+ ("eu", "eu-speech.googleapis.com"),
+ ("global", "speech.googleapis.com"),
+ ],
+ )
+ def test_valid_location_netloc_always_google(self, config, location, expected_netloc):
+ url = config.get_complete_url(
+ api_base=None,
+ api_key=None,
+ model="chirp_3",
+ optional_params={},
+ litellm_params={"vertex_project": "test-project", "vertex_location": location},
+ )
+ netloc = urlparse(url).netloc
+ assert netloc == expected_netloc
+ assert netloc.endswith("speech.googleapis.com")
+
+ @pytest.mark.parametrize(
+ "malicious_location",
+ [
+ "attacker.example/",
+ "evil.com#",
+ "us.attacker.example",
+ "us/../..",
+ "US",
+ "us_central1",
+ "us central1",
+ "attacker.example:443",
+ "-us",
+ ],
+ )
+ def test_malicious_location_is_rejected(self, config, malicious_location):
+ """SSRF/credential-exfil guard: vertex_location is client-controllable on
+ the proxy, so a host-injecting value must raise rather than steer the
+ request (and its admin-minted Google bearer token) at another host."""
+ with pytest.raises(VertexAIError):
+ config.get_complete_url(
+ api_base=None,
+ api_key=None,
+ model="chirp_3",
+ optional_params={},
+ litellm_params={"vertex_project": "test-project", "vertex_location": malicious_location},
+ )
+
+ @pytest.mark.parametrize(
+ "malicious_project",
+ [
+ "proj/../../locations",
+ "proj/evil",
+ "proj#frag",
+ "proj?a=b",
+ "proj:evil",
+ "proj space",
+ ],
+ )
+ def test_malicious_project_is_rejected(self, config, malicious_project):
+ with pytest.raises(VertexAIError):
+ config.get_complete_url(
+ api_base=None,
+ api_key=None,
+ model="chirp_3",
+ optional_params={},
+ litellm_params={"vertex_project": malicious_project, "vertex_location": "us"},
+ )
+
+
+class TestTransformRequest:
+ def test_request_body_shape(self, config):
+ audio_bytes = b"fake-audio-bytes"
+ request_data = config.transform_audio_transcription_request(
+ model="chirp_3",
+ audio_file=audio_bytes,
+ optional_params={},
+ litellm_params={},
+ )
+ assert request_data.files is None
+ assert request_data.data == {
+ "config": {
+ "model": "chirp_3",
+ "languageCodes": ["auto"],
+ "features": {"enableAutomaticPunctuation": True},
+ "autoDecodingConfig": {},
+ },
+ "content": base64.b64encode(audio_bytes).decode("utf-8"),
+ }
+
+ @pytest.mark.parametrize(
+ "language,expected_language_codes",
+ [
+ ("en", ["en-US"]),
+ ("en-US", ["en-US"]),
+ ("es-ES", ["es-ES"]),
+ ("fr", ["fr-FR"]),
+ (None, ["auto"]),
+ ],
+ )
+ def test_language_param_maps_to_language_codes(self, config, language, expected_language_codes):
+ request_data = config.transform_audio_transcription_request(
+ model="chirp_3",
+ audio_file=b"fake-audio-bytes",
+ optional_params={"language": language} if language is not None else {},
+ litellm_params={},
+ )
+ assert request_data.data["config"]["languageCodes"] == expected_language_codes
+
+ def test_model_prefix_is_stripped(self, config):
+ request_data = config.transform_audio_transcription_request(
+ model="vertex_ai/chirp_3",
+ audio_file=b"fake-audio-bytes",
+ optional_params={},
+ litellm_params={},
+ )
+ assert request_data.data["config"]["model"] == "chirp_3"
+
+ def test_body_is_json_serializable(self, config):
+ request_data = config.transform_audio_transcription_request(
+ model="chirp_3",
+ audio_file=b"fake-audio-bytes",
+ optional_params={},
+ litellm_params={},
+ )
+ json.dumps(request_data.data)
+
+
+class TestTransformResponse:
+ def test_multi_result_transcripts_are_joined(self, config):
+ raw_response = httpx.Response(
+ status_code=200,
+ json={
+ "results": [
+ {"alternatives": [{"transcript": "Hello world.", "confidence": 0.98}], "languageCode": "en-US"},
+ {"alternatives": [{"transcript": "How are you?", "confidence": 0.97}], "languageCode": "en-US"},
+ ],
+ "metadata": {"totalBilledDuration": "15s"},
+ },
+ )
+ response = config.transform_audio_transcription_response(raw_response)
+ assert response.text == "Hello world. How are you?"
+ assert response["task"] == "transcribe"
+ assert response["language"] == "en-US"
+ assert response["duration"] == 15.0
+
+ def test_results_without_alternatives_are_skipped(self, config):
+ raw_response = httpx.Response(
+ status_code=200,
+ json={
+ "results": [
+ {"alternatives": [{"transcript": "First."}]},
+ {"alternatives": []},
+ {},
+ {"alternatives": [{"transcript": "Last."}]},
+ ]
+ },
+ )
+ response = config.transform_audio_transcription_response(raw_response)
+ assert response.text == "First. Last."
+
+ def test_empty_results_returns_empty_text(self, config):
+ raw_response = httpx.Response(status_code=200, json={})
+ response = config.transform_audio_transcription_response(raw_response)
+ assert response.text == ""
+
+ def test_fractional_billed_duration(self, config):
+ raw_response = httpx.Response(
+ status_code=200,
+ json={
+ "results": [{"alternatives": [{"transcript": "Hi."}]}],
+ "metadata": {"totalBilledDuration": "3.5s"},
+ },
+ )
+ response = config.transform_audio_transcription_response(raw_response)
+ assert response["duration"] == 3.5
+
+
+class TestValidateEnvironment:
+ def test_sets_oauth_headers(self):
+ class StubbedConfig(VertexAIAudioTranscriptionConfig):
+ def _ensure_access_token(self, credentials, project_id, custom_llm_provider):
+ return "fake-token", "resolved-project"
+
+ headers = StubbedConfig().validate_environment(
+ headers={},
+ model="chirp_3",
+ messages=[],
+ optional_params={},
+ litellm_params={"vertex_project": "resolved-project"},
+ )
+ assert headers["Authorization"] == "Bearer fake-token"
+ assert headers["x-goog-user-project"] == "resolved-project"
+ assert headers["Content-Type"] == "application/json"
+
+
+class TestProviderRouting:
+ def test_provider_config_manager_returns_vertex_config(self):
+ provider_config = ProviderConfigManager.get_provider_audio_transcription_config(
+ model="chirp_3",
+ provider=LlmProviders.VERTEX_AI,
+ )
+ assert isinstance(provider_config, VertexAIAudioTranscriptionConfig)
+
+ def test_get_optional_params_transcription_maps_language(self):
+ optional_params = get_optional_params_transcription(
+ model="chirp_3",
+ custom_llm_provider="vertex_ai",
+ language="fr-FR",
+ response_format="json",
+ )
+ assert optional_params["language"] == "fr-FR"
+ assert optional_params["response_format"] == "json"
+
+ def test_get_optional_params_transcription_rejects_unsupported_param(self):
+ with pytest.raises(litellm.utils.UnsupportedParamsError):
+ get_optional_params_transcription(
+ model="chirp_3",
+ custom_llm_provider="vertex_ai",
+ temperature=1,
+ )
+
+ @pytest.mark.parametrize("response_format", ["json", "text"])
+ def test_supported_response_formats_pass_through(self, response_format):
+ optional_params = get_optional_params_transcription(
+ model="chirp_3",
+ custom_llm_provider="vertex_ai",
+ response_format=response_format,
+ )
+ assert optional_params["response_format"] == response_format
+
+ @pytest.mark.parametrize("response_format", ["verbose_json", "srt", "vtt"])
+ def test_unsupported_response_format_raises(self, response_format):
+ with pytest.raises(litellm.utils.UnsupportedParamsError, match="response_format"):
+ get_optional_params_transcription(
+ model="chirp_3",
+ custom_llm_provider="vertex_ai",
+ response_format=response_format,
+ )
+
+ @pytest.mark.parametrize("response_format", ["verbose_json", "srt", "vtt"])
+ def test_unsupported_response_format_dropped_with_drop_params(self, response_format):
+ optional_params = get_optional_params_transcription(
+ model="chirp_3",
+ custom_llm_provider="vertex_ai",
+ language="fr-FR",
+ response_format=response_format,
+ drop_params=True,
+ )
+ assert "response_format" not in optional_params
+ assert optional_params["language"] == "fr-FR"
+
+
+class TestModelCostEntry:
+ REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../.."))
+
+ @pytest.mark.parametrize(
+ "cost_map_path",
+ [
+ "model_prices_and_context_window.json",
+ "litellm/model_prices_and_context_window_backup.json",
+ ],
+ )
+ def test_chirp_3_registered_as_audio_transcription(self, cost_map_path):
+ with open(os.path.join(self.REPO_ROOT, cost_map_path)) as f:
+ entry = json.load(f)["vertex_ai/chirp_3"]
+ assert entry["mode"] == "audio_transcription"
+ assert entry["litellm_provider"] == "vertex_ai"
+ assert entry["input_cost_per_second"] == pytest.approx(0.016 / 60, rel=1e-3)
+ assert entry["supported_endpoints"] == ["/v1/audio/transcriptions"]
diff --git a/tests/test_litellm/llms/vertex_ai/test_vertex_ai_common_utils.py b/tests/test_litellm/llms/vertex_ai/test_vertex_ai_common_utils.py
index bebf856ee6e..b83d4742b64 100644
--- a/tests/test_litellm/llms/vertex_ai/test_vertex_ai_common_utils.py
+++ b/tests/test_litellm/llms/vertex_ai/test_vertex_ai_common_utils.py
@@ -18,10 +18,25 @@ from litellm.llms.vertex_ai.common_utils import (
pop_vertex_request_labels,
set_schema_property_ordering,
supports_response_json_schema,
+ validate_vertex_location,
vertex_request_labels_from_litellm_params,
)
[email protected]("location", ["us", "eu", "us-central1", "europe-west1", "global"])
+def test_validate_vertex_location_accepts_valid(location):
+ assert validate_vertex_location(location) == location
+
+
+ "location",
+ ["attacker.example/", "evil.com#", "us.attacker.example", "us/../..", "US", "us_central1", "-us", "", None],
+)
+def test_validate_vertex_location_rejects_invalid(location):
+ with pytest.raises(ValueError):
+ validate_vertex_location(location)
+
+
@pytest.mark.asyncio
async def test_get_vertex_project_id_from_url():
"""Test _get_vertex_project_id_from_url with various URLs"""
diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py
index 7f1ceba532c..93bdb40ae2b 100644
--- a/tests/test_litellm/test_cost_calculator.py
+++ b/tests/test_litellm/test_cost_calculator.py
@@ -347,6 +347,30 @@ def test_transcription_cost_falls_back_to_duration():
assert pytest.approx(cost, rel=1e-6) == expected_cost
+def test_vertex_chirp_3_transcription_cost_from_duration():
+ """Regression: the chirp_3 cost map entry shipped with output_cost_per_second 0.0,
+ and cost_per_second prefers output_cost_per_second whenever it is not None, so
+ every transcription priced to $0.00 instead of using input_cost_per_second."""
+ from litellm import completion_cost
+
+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+
+ response = TranscriptionResponse(text="demo text")
+ response.duration = 18.0
+
+ cost = completion_cost(
+ completion_response=response,
+ model="vertex_ai/chirp_3",
+ custom_llm_provider="vertex_ai",
+ call_type="atranscription",
+ )
+
+ expected_cost = 18.0 * 0.00026667
+ assert cost > 0
+ assert pytest.approx(cost, rel=1e-6) == expected_cost
+
+
def test_handle_realtime_stream_cost_calculation():
from litellm.cost_calculator import RealtimeAPITokenUsageProcessor