From e4ddb553eff34e9031ad54b2e0036309804ac33c Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Mon, 6 Jul 2026 14:06:54 -0700 Subject: [PATCH 1/6] fix(llm_http_handler): send dict transcription request data as a JSON body httpx form-encodes dicts passed via data= and silently ignores json=, so the generic audio transcription path never actually sent a JSON body. No provider hit this before; JSON-body speech APIs need it. --- litellm/llms/custom_httpx/llm_http_handler.py | 18 ++-- .../custom_httpx/test_llm_http_handler.py | 100 ++++++++++++++++++ 2 files changed, 108 insertions(+), 10 deletions(-) diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index 05401488f272..e48011f23f1b 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -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: @@ -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: 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 0b4187d1bcf3..961f95a06595 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 @@ 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.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" + + +@pytest.mark.asyncio +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" From 573d5b7ca67c4be2092bd2dc0afea849bbc12b2b Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Mon, 6 Jul 2026 14:06:55 -0700 Subject: [PATCH 2/6] feat(vertex_ai): add Google Cloud Speech-to-Text Chirp 3 transcription support Adds a VertexAIAudioTranscriptionConfig wired through ProviderConfigManager so vertex_ai/chirp_3 works on /v1/audio/transcriptions (sync and async) via the Speech-to-Text v2 recognize API. Auth reuses the standard Vertex credential resolution (vertex_project/vertex_location/vertex_credentials or ADC); the location defaults to the us multi-region since chirp_3 is only served from the us and eu multi-regions, and non-global locations use the regional -speech.googleapis.com host. Maps language to languageCodes (auto language detection by default), joins all result alternatives into the transcript, and tracks cost from totalBilledDuration with a vertex_ai/chirp_3 price entry at Google's published $0.016/min. --- .../audio_transcription/transformation.py | 157 ++++++++++++ ...odel_prices_and_context_window_backup.json | 14 ++ .../types/llms/vertex_ai_speech_to_text.py | 40 ++++ litellm/utils.py | 6 + model_prices_and_context_window.json | 14 ++ .../vertex_ai/audio_transcription/__init__.py | 0 ...x_ai_audio_transcription_transformation.py | 225 ++++++++++++++++++ 7 files changed, 456 insertions(+) create mode 100644 litellm/llms/vertex_ai/audio_transcription/transformation.py create mode 100644 litellm/types/llms/vertex_ai_speech_to_text.py create mode 100644 tests/test_litellm/llms/vertex_ai/audio_transcription/__init__.py create mode 100644 tests/test_litellm/llms/vertex_ai/audio_transcription/test_vertex_ai_audio_transcription_transformation.py 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 000000000000..61194704203b --- /dev/null +++ b/litellm/llms/vertex_ai/audio_transcription/transformation.py @@ -0,0 +1,157 @@ +import base64 + +from httpx import Headers, Response + +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.llms.vertex_ai.common_utils import VertexAIError +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" + + +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) + 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.safe_get_vertex_ai_location(litellm_params) or DEFAULT_SPEECH_TO_TEXT_LOCATION + 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" + + 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 = [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 Exception: + 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/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 26d54c05ffb9..140ccb0e8ac4 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -34655,6 +34655,20 @@ "/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", + "output_cost_per_second": 0.0, + "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 000000000000..8995d98385ba --- /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 83d129339a43..f9bb84101e7a 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -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() return None @staticmethod diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index a3dcdaed3f70..d7f9dc3462b4 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -34829,6 +34829,20 @@ "/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", + "output_cost_per_second": 0.0, + "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/llms/vertex_ai/audio_transcription/__init__.py b/tests/test_litellm/llms/vertex_ai/audio_transcription/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 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 000000000000..53462ab6a208 --- /dev/null +++ b/tests/test_litellm/llms/vertex_ai/audio_transcription/test_vertex_ai_audio_transcription_transformation.py @@ -0,0 +1,225 @@ +import base64 +import json +import os +import sys + +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.types.utils import LlmProviders +from litellm.utils import ProviderConfigManager, get_optional_params_transcription + + +@pytest.fixture +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" + + +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"), + } + + def test_language_param_maps_to_language_codes(self, config): + request_data = config.transform_audio_transcription_request( + model="chirp_3", + audio_file=b"fake-audio-bytes", + optional_params={"language": "es-ES"}, + litellm_params={}, + ) + assert request_data.data["config"]["languageCodes"] == ["es-ES"] + + 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, + ) + + +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"] From 3a8ec61315f6ec2f74c768923934a74338d94d8a Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Mon, 6 Jul 2026 14:29:02 -0700 Subject: [PATCH 3/6] fix(vertex_ai): map bare ISO-639-1 language codes to BCP-47 for Speech-to-Text OpenAI clients send language codes like "en", which Google rejects with 400 ("not supported by the model chirp_3 in the location us"); Speech-to-Text wants region-qualified BCP-47 like "en-US". Adds a shared normalize_transcription_language_to_bcp47 helper in audio_utils (NVIDIA Riva's transcription config already hand-rolled the same table privately) that maps common bare codes and passes region-qualified ones through, and applies it in the Vertex transcription request. Also narrows the response JSON parse guard to ValueError. --- .../litellm_core_utils/audio_utils/utils.py | 28 +++++++++++++++++++ .../audio_transcription/transformation.py | 13 +++++++-- .../litellm_core_utils/test_audio_utils.py | 21 ++++++++++++++ ...x_ai_audio_transcription_transformation.py | 16 +++++++++-- 4 files changed, 72 insertions(+), 6 deletions(-) diff --git a/litellm/litellm_core_utils/audio_utils/utils.py b/litellm/litellm_core_utils/audio_utils/utils.py index f86243c73b78..e5007ceec346 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/vertex_ai/audio_transcription/transformation.py b/litellm/llms/vertex_ai/audio_transcription/transformation.py index 61194704203b..c01c3792ccb3 100644 --- a/litellm/llms/vertex_ai/audio_transcription/transformation.py +++ b/litellm/llms/vertex_ai/audio_transcription/transformation.py @@ -2,7 +2,10 @@ from httpx import Headers, Response -from litellm.litellm_core_utils.audio_utils.utils import process_audio_file +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, @@ -107,7 +110,11 @@ def transform_audio_transcription_request( ) -> AudioTranscriptionRequestData: processed_audio = process_audio_file(audio_file) language = optional_params.get("language") - language_codes = [language] if isinstance(language, str) and language else [AUTO_LANGUAGE_CODE] + 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/"), @@ -125,7 +132,7 @@ def transform_audio_transcription_response( ) -> TranscriptionResponse: try: response_json = raw_response.json() - except Exception: + except ValueError: raise VertexAIError( status_code=raw_response.status_code, message=f"Received non-JSON response from Google Speech-to-Text: {raw_response.text}", 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 b2645c8f2ced..0e8176fffced 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 @@ def __init__(self, name): 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/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 index 53462ab6a208..32680b876227 100644 --- 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 @@ -83,14 +83,24 @@ def test_request_body_shape(self, config): "content": base64.b64encode(audio_bytes).decode("utf-8"), } - def test_language_param_maps_to_language_codes(self, config): + @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": "es-ES"}, + optional_params={"language": language} if language is not None else {}, litellm_params={}, ) - assert request_data.data["config"]["languageCodes"] == ["es-ES"] + assert request_data.data["config"]["languageCodes"] == expected_language_codes def test_model_prefix_is_stripped(self, config): request_data = config.transform_audio_transcription_request( From 646807fd4357643d3a0efb682498b7a0e872e881 Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Mon, 6 Jul 2026 14:29:02 -0700 Subject: [PATCH 4/6] fix(vertex_ai): drop zero output_cost_per_second so chirp_3 cost tracking works cost_per_second prefers output_cost_per_second whenever it is not None, so the 0.0 in the chirp_3 entry priced every transcription at $0.00 instead of using input_cost_per_second. Remove it from both cost maps and pin the behavior with a regression test computing 18s of chirp_3 audio to ~$0.0048. --- ...odel_prices_and_context_window_backup.json | 1 - model_prices_and_context_window.json | 1 - tests/test_litellm/test_cost_calculator.py | 24 +++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 140ccb0e8ac4..d57e5476abe2 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -34663,7 +34663,6 @@ "original_pricing_per_minute": 0.016 }, "mode": "audio_transcription", - "output_cost_per_second": 0.0, "source": "https://cloud.google.com/speech-to-text/pricing", "supported_endpoints": [ "/v1/audio/transcriptions" diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index d7f9dc3462b4..d95f9f7f007c 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -34837,7 +34837,6 @@ "original_pricing_per_minute": 0.016 }, "mode": "audio_transcription", - "output_cost_per_second": 0.0, "source": "https://cloud.google.com/speech-to-text/pricing", "supported_endpoints": [ "/v1/audio/transcriptions" diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py index 7f1ceba532c9..93bdb40ae2b0 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 From aaf8b1f0abaa36cde7afb511c2661aa7af9178fb Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Mon, 6 Jul 2026 15:19:30 -0700 Subject: [PATCH 5/6] fix(vertex_ai): validate client-controllable location to prevent SSRF in Speech-to-Text get_complete_url interpolated vertex_location straight into the request host, and vertex_location is client-controllable on the proxy (it flows from the request body and is not on the request-body blocklist). An authenticated caller could send vertex_location="attacker.example/" to point the host at their own server, so the proxy would POST the audio plus its admin-minted Google bearer token and x-goog-user-project header to the attacker, exfiltrating a cloud-platform-scoped OAuth token minted from the admin's credentials. Factor the location validation the rest of vertex_ai already applied in get_vertex_base_url (^[a-z][a-z0-9-]*$ plus the global allowance) into a shared validate_vertex_location helper in common_utils and call it from both the chat host builder and the new speech host builder. Invalid locations now raise a 400 VertexAIError instead of building a host. Also reject vertex_project values that carry URL-structural characters, since it lands in the URL path. Regression tests assert on the parsed netloc so the security property is pinned: valid locations always resolve to a *speech.googleapis.com host and injection inputs are rejected. --- .../audio_transcription/transformation.py | 22 ++++-- litellm/llms/vertex_ai/common_utils.py | 35 ++++++--- ...x_ai_audio_transcription_transformation.py | 71 +++++++++++++++++++ .../vertex_ai/test_vertex_ai_common_utils.py | 15 ++++ 4 files changed, 131 insertions(+), 12 deletions(-) diff --git a/litellm/llms/vertex_ai/audio_transcription/transformation.py b/litellm/llms/vertex_ai/audio_transcription/transformation.py index c01c3792ccb3..f348307ebb98 100644 --- a/litellm/llms/vertex_ai/audio_transcription/transformation.py +++ b/litellm/llms/vertex_ai/audio_transcription/transformation.py @@ -11,7 +11,7 @@ BaseAudioTranscriptionConfig, ) from litellm.llms.base_llm.chat.transformation import BaseLLMException -from litellm.llms.vertex_ai.common_utils import VertexAIError +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, @@ -28,6 +28,7 @@ DEFAULT_SPEECH_TO_TEXT_LOCATION = "us" AUTO_LANGUAGE_CODE = "auto" +_URL_UNSAFE_PROJECT_CHARS = ("/", "?", "#", "\\", ":", " ", "\t", "\n", "\r") class VertexAIAudioTranscriptionConfig(BaseAudioTranscriptionConfig, VertexBase): @@ -85,14 +86,27 @@ def get_complete_url( litellm_params: dict, stream: bool | None = None, ) -> str: - location = self.safe_get_vertex_ai_location(litellm_params) or DEFAULT_SPEECH_TO_TEXT_LOCATION - project_id = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_project_id_from_credentials( - litellm_params + 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), diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py index 36522dfe396a..7dcb4dcf2e81 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/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 index 32680b876227..3e3f81f0879d 100644 --- 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 @@ -2,6 +2,7 @@ import json import os import sys +from urllib.parse import urlparse import httpx import pytest @@ -12,6 +13,7 @@ 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 @@ -62,6 +64,75 @@ def test_api_base_override(self, config): ) 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): 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 bebf856ee6e8..b83d4742b642 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 @@ pop_vertex_request_labels, set_schema_property_ordering, supports_response_json_schema, + validate_vertex_location, vertex_request_labels_from_litellm_params, ) +@pytest.mark.parametrize("location", ["us", "eu", "us-central1", "europe-west1", "global"]) +def test_validate_vertex_location_accepts_valid(location): + assert validate_vertex_location(location) == location + + +@pytest.mark.parametrize( + "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""" From 2b8706776f4b25f5745e819232166b8baf04a3cf Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Mon, 6 Jul 2026 16:03:43 -0700 Subject: [PATCH 6/6] fix(vertex_ai): reject unsupported transcription response_format values instead of silently ignoring --- .../audio_transcription/transformation.py | 18 ++++++++++- ...x_ai_audio_transcription_transformation.py | 30 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/litellm/llms/vertex_ai/audio_transcription/transformation.py b/litellm/llms/vertex_ai/audio_transcription/transformation.py index f348307ebb98..03769bf2601e 100644 --- a/litellm/llms/vertex_ai/audio_transcription/transformation.py +++ b/litellm/llms/vertex_ai/audio_transcription/transformation.py @@ -2,6 +2,8 @@ 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, @@ -28,6 +30,7 @@ DEFAULT_SPEECH_TO_TEXT_LOCATION = "us" AUTO_LANGUAGE_CODE = "auto" +SUPPORTED_RESPONSE_FORMATS = ("json", "text") _URL_UNSAFE_PROJECT_CHARS = ("/", "?", "#", "\\", ":", " ", "\t", "\n", "\r") @@ -47,10 +50,23 @@ def map_openai_params( drop_params: bool, ) -> dict: supported_params = self.get_supported_openai_params(model) - return { + 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) 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 index 3e3f81f0879d..3fa28699f73f 100644 --- 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 @@ -286,6 +286,36 @@ def test_get_optional_params_transcription_rejects_unsupported_param(self): 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__), "../../../../.."))