The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
remove model before casting it in the transformation (#18810)
Shivam Rawat43dd0e6ef51c
diff --git a/litellm/llms/watsonx/audio_transcription/transformation.py b/litellm/llms/watsonx/audio_transcription/transformation.pyindex 186d858321a..c7e6a77b96f 100644--- a/litellm/llms/watsonx/audio_transcription/transformation.py+++ b/litellm/llms/watsonx/audio_transcription/transformation.py@@ -7,13 +7,14 @@ WatsonX follows the OpenAI spec for audio transcription.from typing import Any, Dict, List, Optionalimport litellm+from httpx import Responsefrom litellm.litellm_core_utils.audio_utils.utils import process_audio_filefrom litellm.types.llms.openai import (AllMessageValues,OpenAIAudioTranscriptionOptionalParams,)from litellm.types.llms.watsonx import WatsonXAudioTranscriptionRequestBody-from litellm.types.utils import FileTypes+from litellm.types.utils import FileTypes, TranscriptionResponsefrom ...base_llm.audio_transcription.transformation import (AudioTranscriptionRequestData,@@ -156,3 +157,48 @@ class IBMWatsonXAudioTranscriptionConfig(url = f"{url}?version={api_version}"return url++ def transform_audio_transcription_response(+ self,+ raw_response: Response,+ ) -> TranscriptionResponse:+ """+ Transform the audio transcription response from WatsonX.++ WatsonX may include a 'model' field in the response, which needs to be+ removed before creating the TranscriptionResponse object.+ """+ try:+ raw_response_json = raw_response.json()+ except Exception as e:+ raise ValueError(+ f"Error transforming response to json: {str(e)}\nResponse: {raw_response.text}"+ )++ # Extract only valid fields for TranscriptionResponse.__init__()+ # TranscriptionResponse only accepts 'text' and 'usage' in __init__()+ text = raw_response_json.get("text")+ usage = raw_response_json.get("usage")++ # Create response with only valid fields+ response_kwargs = {}+ if text is not None:+ response_kwargs["text"] = text+ if usage is not None:+ response_kwargs["usage"] = usage++ if not response_kwargs:+ raise ValueError(+ "Invalid response format. Received response does not match the expected format. Got: ",+ raw_response_json,+ )++ response = TranscriptionResponse(**response_kwargs)++ # Add other fields using dictionary-style assignment (like duration, task, etc.)+ # Skip fields that TranscriptionResponse doesn't accept in __init__()+ for key, value in raw_response_json.items():+ if key not in ["text", "usage", "model"]: # text/usage already set, model should be excluded+ response[key] = value++ return responsediff --git a/tests/test_litellm/llms/watsonx/audio_transcription/test_watsonx_audio_transcription_transformation.py b/tests/test_litellm/llms/watsonx/audio_transcription/test_watsonx_audio_transcription_transformation.pyindex e36a494998b..fd5f8f3eff8 100644--- a/tests/test_litellm/llms/watsonx/audio_transcription/test_watsonx_audio_transcription_transformation.py+++ b/tests/test_litellm/llms/watsonx/audio_transcription/test_watsonx_audio_transcription_transformation.py@@ -14,6 +14,10 @@ import pytestsys.path.insert(0, os.path.abspath("../../../../.."))import litellm+from litellm.llms.watsonx.audio_transcription.transformation import (+ IBMWatsonXAudioTranscriptionConfig,+)+from litellm.types.utils import TranscriptionResponseclass TestWatsonXAudioTranscription:@@ -189,3 +193,72 @@ class TestWatsonXAudioTranscription:# Verify file is sent separatelyfiles = captured_request.get("files", {})assert "file" in files++ def test_transform_audio_transcription_response_removes_model_field(self):+ """+ Test that transform_audio_transcription_response removes the 'model' field+ from WatsonX response before creating TranscriptionResponse.++ This test ensures that when WatsonX returns a response with a 'model' field,+ it is removed before creating the TranscriptionResponse object, since+ TranscriptionResponse doesn't accept a 'model' parameter.+ """+ handler = IBMWatsonXAudioTranscriptionConfig()++ # Mock response with 'model' field (as WatsonX may return)+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "text": "Hello, this is a test transcription.",+ "model": "whisper-large-v3-turbo", # This field should be removed+ "duration": 5.5,+ }+ mock_response.text = '{"text": "Hello, this is a test transcription.", "model": "whisper-large-v3-turbo", "duration": 5.5}'++ # This should not raise a TypeError - model field should be removed+ result = handler.transform_audio_transcription_response(mock_response)++ # Verify the result is a TranscriptionResponse+ assert isinstance(result, TranscriptionResponse)++ # Verify the text is correct+ assert result.text == "Hello, this is a test transcription."++ # Verify duration is set via dictionary assignment+ assert result["duration"] == 5.5++ # Verify the model field is NOT in the serialized result+ # Check via model_dump() or dict() to ensure it's not in the output+ try:+ result_dict = result.model_dump()+ except AttributeError:+ # Fallback for pydantic v1+ result_dict = result.dict()++ # The 'model' field should not be in the result+ assert "model" not in result_dict, "Model field should be removed from response"++ def test_transform_audio_transcription_response_without_model_field(self):+ """+ Test that transform_audio_transcription_response works correctly+ when WatsonX response doesn't include a 'model' field.+ """+ handler = IBMWatsonXAudioTranscriptionConfig()++ # Mock response without 'model' field+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "text": "Hello, this is a test transcription.",+ "duration": 5.5,+ }+ mock_response.text = '{"text": "Hello, this is a test transcription.", "duration": 5.5}'++ result = handler.transform_audio_transcription_response(mock_response)++ # Verify the result is a TranscriptionResponse+ assert isinstance(result, TranscriptionResponse)++ # Verify the text is correct+ assert result.text == "Hello, this is a test transcription."++ # Verify duration is set via dictionary assignment+ assert result["duration"] == 5.5