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
VertexAI - camelcase optional params for image generation + Anthropic - streaming, always ensure assistant role set on only first chunk (#12889)
Krish Dholakia1737cf4257a8
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 98fdd133eb6..2e3fe091eed 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -745,6 +745,24 @@ class CustomStreamWrapper:else:return False+ def strip_role_from_delta(+ self, model_response: ModelResponseStream+ ) -> ModelResponseStream:+ """+ Strip the role from the delta.+ """+ if self.sent_first_chunk is False:+ model_response.choices[0].delta["role"] = "assistant"+ self.sent_first_chunk = True+ elif self.sent_first_chunk is True and hasattr(+ model_response.choices[0].delta, "role"+ ):+ _initial_delta = model_response.choices[0].delta.model_dump()++ _initial_delta.pop("role", None)+ model_response.choices[0].delta = Delta(**_initial_delta)+ return model_response+def return_processed_chunk_logic( # noqaself,completion_obj: Dict[str, Any],@@ -770,11 +788,12 @@ class CustomStreamWrapper:chunk=completion_obj["content"],finish_reason=model_response.choices[0].finish_reason,) # filter out bos/eos tokens from openai-compatible hf endpoints- print_verbose(f"hold - {hold}, model_response_str - {model_response_str}")+if hold is False:## check if openai/azure chunkoriginal_chunk = response_obj.get("original_chunk", None)if original_chunk:+if len(original_chunk.choices) > 0:choices = []for choice in original_chunk.choices:@@ -791,6 +810,7 @@ class CustomStreamWrapper:print_verbose(f"choices in streaming: {choices}")setattr(model_response, "choices", choices)else:+returnmodel_response.system_fingerprint = (original_chunk.system_fingerprint@@ -804,19 +824,10 @@ class CustomStreamWrapper:model_response=model_response,original_chunk=original_chunk,)- print_verbose(f"self.sent_first_chunk: {self.sent_first_chunk}")- if self.sent_first_chunk is False:- model_response.choices[0].delta["role"] = "assistant"- self.sent_first_chunk = True- elif self.sent_first_chunk is True and hasattr(- model_response.choices[0].delta, "role"- ):- _initial_delta = model_response.choices[0].delta.model_dump()- _initial_delta.pop("role", None)- model_response.choices[0].delta = Delta(**_initial_delta)+ model_response = self.strip_role_from_delta(model_response)verbose_logger.debug(- f"model_response.choices[0].delta: {model_response.choices[0].delta}"+ f"model_response.choices[0].delta inside is_chunk_non_empty: {model_response.choices[0].delta}")else:## else@@ -836,7 +847,7 @@ class CustomStreamWrapper:self._optional_combine_thinking_block_in_choices(model_response=model_response)- print_verbose(f"returning model_response: {model_response}")+return model_responseelse:return@@ -878,15 +889,15 @@ class CustomStreamWrapper:model_response.choices[0].delta.tool_calls is not Noneor model_response.choices[0].delta.function_call is not None):- if self.sent_first_chunk is False:- model_response.choices[0].delta["role"] = "assistant"- self.sent_first_chunk = True+ model_response = self.strip_role_from_delta(model_response)+return model_responseelif (len(model_response.choices) > 0and hasattr(model_response.choices[0].delta, "audio")and model_response.choices[0].delta.audio is not None):+ model_response = self.strip_role_from_delta(model_response)return model_responseelse:if hasattr(model_response, "usage"):diff --git a/litellm/llms/vertex_ai/image_generation/image_generation_handler.py b/litellm/llms/vertex_ai/image_generation/image_generation_handler.pyindex e83f4b6f038..4ffe557f1b6 100644--- a/litellm/llms/vertex_ai/image_generation/image_generation_handler.py+++ b/litellm/llms/vertex_ai/image_generation/image_generation_handler.py@@ -40,6 +40,31 @@ class VertexImageGeneration(VertexLLM):model_response.data = response_datareturn model_response+ def transform_optional_params(self, optional_params: Optional[dict]) -> dict:+ """+ Transform the optional params to the format expected by the Vertex AI API.+ For example, "aspect_ratio" is transformed to "aspectRatio".+ """+ if optional_params is None:+ return {+ "sampleCount": 1,+ }++ def snake_to_camel(snake_str: str) -> str:+ """Convert snake_case to camelCase"""+ components = snake_str.split("_")+ return components[0] + "".join(word.capitalize() for word in components[1:])++ transformed_params = {}+ for key, value in optional_params.items():+ if "_" in key:+ camel_case_key = snake_to_camel(key)+ transformed_params[camel_case_key] = value+ else:+ transformed_params[key] = value++ return transformed_params+def image_generation(self,prompt: str,@@ -109,6 +134,9 @@ class VertexImageGeneration(VertexLLM):"sampleCount": 1} # default optional params+ # Transform optional params to camelCase format+ optional_params = self.transform_optional_params(optional_params)+request_data = {"instances": [{"prompt": prompt}],"parameters": optional_params,@@ -211,9 +239,9 @@ class VertexImageGeneration(VertexLLM):should_use_v1beta1_features=False,mode="image_generation",)- optional_params = optional_params or {- "sampleCount": 1- } # default optional params++ # Transform optional params to camelCase format+ optional_params = self.transform_optional_params(optional_params)request_data = {"instances": [{"prompt": prompt}],diff --git a/tests/llm_translation/test_anthropic_completion.py b/tests/llm_translation/test_anthropic_completion.pyindex e3334658281..45702a261e2 100644--- a/tests/llm_translation/test_anthropic_completion.py+++ b/tests/llm_translation/test_anthropic_completion.py@@ -1438,3 +1438,59 @@ def test_anthropic_tool_cache_control():assert "cache_control" in json.dumps(result["raw_request_body"]["messages"][2]["content"])+++def test_anthropic_streaming():+ from litellm import completion++ request_data = {+ "messages": [+ {+ "role": "system",+ "content": "Call the tool, please, but tell me what you are doing before you do it.", # (so we get some pre-tool streaming output)+ },+ {+ "role": "user",+ "content": "Do what you are told to do in the system prompt",+ },+ ],+ "model": "anthropic/claude-3-5-sonnet-latest",+ "max_tokens": 7000,+ "parallel_tool_calls": False,+ "stream": True,+ "temperature": 0,+ "tool_choice": "auto",+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "call_me_please",+ "strict": True,+ "parameters": {+ "properties": {+ "a_number": {+ "description": "String that is text version of a number, e.g. sixty-five. At least a 5 digit number.",+ "type": "string",+ "title": "A Number Function",+ }+ },+ "title": "call_me_please",+ "type": "object",+ "additionalProperties": False,+ "required": ["a_number"],+ },+ "description": "Call this tool with a number to get a random number back",+ },+ }+ ],+ }++ response = completion(**request_data)++ role_set_count = 0+ for chunk in response:+ if chunk.choices[0].delta.role is not None:+ print(f"role: {chunk.choices[0].delta.role}")+ role_set_count += 1++ assert role_set_count == 1diff --git a/tests/llm_translation/test_optional_params.py b/tests/llm_translation/test_optional_params.pyindex 3ccdfe485b8..52f6d99fdf5 100644--- a/tests/llm_translation/test_optional_params.py+++ b/tests/llm_translation/test_optional_params.py@@ -67,19 +67,35 @@ def test_anthropic_optional_params(stop_sequence, expected_count):assert len(optional_params) == expected_count--def test_get_optional_params_with_allowed_openai_params():"""Test if use can dynamically pass in allowed_openai_params to override default behavior"""litellm.drop_params = True- tools = [{'type': 'function', 'function': {'name': 'get_current_time', 'description': 'Get the current time in a given location.', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city name, e.g. San Francisco'}}, 'required': ['location']}}}]+ tools = [+ {+ "type": "function",+ "function": {+ "name": "get_current_time",+ "description": "Get the current time in a given location.",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {+ "type": "string",+ "description": "The city name, e.g. San Francisco",+ }+ },+ "required": ["location"],+ },+ },+ }+ ]response_format = {"type": "json"}reasoning_effort = "low"optional_params = get_optional_params(- model="cf/llama-3.1-70b-instruct",- custom_llm_provider="cloudflare",+ model="cf/llama-3.1-70b-instruct",+ custom_llm_provider="cloudflare",allowed_openai_params=["tools", "reasoning_effort", "response_format"],tools=tools,response_format=response_format,@@ -88,7 +104,7 @@ def test_get_optional_params_with_allowed_openai_params():print(f"optional_params: {optional_params}")assert optional_params["tools"] == toolsassert optional_params["response_format"] == response_format- assert optional_params["reasoning_effort"] == reasoning_effort+ assert optional_params["reasoning_effort"] == reasoning_effortdef test_bedrock_optional_params_embeddings():@@ -460,6 +476,7 @@ def test_dynamic_drop_params_e2e():print(mock_response.call_args.kwargs["data"])assert "response_format" not in mock_response.call_args.kwargs["data"]+def test_dynamic_pass_additional_params():with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post", new=MagicMock()@@ -618,7 +635,10 @@ def test_get_optional_params_num_retries():"""Relevant issue - https://github.com/BerriAI/litellm/issues/5124"""- with patch("litellm.main.get_optional_params", new=MagicMock(return_value={"max_retries": 0})) as mock_client:+ with patch(+ "litellm.main.get_optional_params",+ new=MagicMock(return_value={"max_retries": 0}),+ ) as mock_client:_ = litellm.completion(model="gpt-3.5-turbo",messages=[{"role": "user", "content": "Hello world"}],@@ -1425,13 +1445,18 @@ def test_azure_modalities_param():assert optional_params["modalities"] == ["text", "audio"]assert optional_params["audio"] == {"type": "audio_input", "input": "test.wav"}+def test_litellm_proxy_thinking_param():optional_params = get_optional_params(model="gpt-4o",custom_llm_provider="litellm_proxy",thinking={"type": "enabled", "budget_tokens": 1024},)- assert optional_params["extra_body"]["thinking"] == {"type": "enabled", "budget_tokens": 1024}+ assert optional_params["extra_body"]["thinking"] == {+ "type": "enabled",+ "budget_tokens": 1024,+ }+def test_gemini_modalities_param():optional_params = get_optional_params(@@ -1441,18 +1466,34 @@ def test_gemini_modalities_param():)assert optional_params["responseModalities"] == ["TEXT", "IMAGE"]--def test_azure_response_format_param():optional_params = litellm.get_optional_params(model="azure/o_series/test-o3-mini",custom_llm_provider="azure/o_series",- tools= [{'type': 'function', 'function': {'name': 'get_current_time', 'description': 'Get the current time in a given location.', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city name, e.g. San Francisco'}}, 'required': ['location']}}}]+ tools=[+ {+ "type": "function",+ "function": {+ "name": "get_current_time",+ "description": "Get the current time in a given location.",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {+ "type": "string",+ "description": "The city name, e.g. San Francisco",+ }+ },+ "required": ["location"],+ },+ },+ }+ ],)-+@pytest.mark.parametrize("model, provider",[@@ -1471,7 +1512,6 @@ def test_anthropic_unified_reasoning_content(model, provider):assert optional_params["thinking"] == {"type": "enabled", "budget_tokens": 4096}-def test_azure_response_format(monkeypatch):monkeypatch.setenv("AZURE_API_VERSION", "2025-02-01")optional_params = get_optional_params(@@ -1481,6 +1521,7 @@ def test_azure_response_format(monkeypatch):)assert optional_params["response_format"] == {"type": "json_object"}+def test_cohere_embed_dimensions_param():optional_params = get_optional_params_embeddings(model="embed-multilingual-v3.0",@@ -1489,24 +1530,35 @@ def test_cohere_embed_dimensions_param():)assert optional_params["embedding_types"] == ["float"]+def test_optional_params_with_additional_drop_params():optional_params = get_optional_params(model="gpt-4o",custom_llm_provider="openai",additional_drop_params=["red"],drop_params=True,- red="blue"+ red="blue",)print(f"optional_params: {optional_params}")assert "red" not in optional_paramsassert "red" not in optional_params["extra_body"]+def test_azure_ai_cohere_embed_input_type_param():optional_params = get_optional_params_embeddings(model="embed-v-4-0",custom_llm_provider="azure_ai",input_type="text",- dimensions=1536+ dimensions=1536,)assert optional_params["dimensions"] == 1536- assert optional_params["extra_body"]["input_type"] == "text"\ No newline at end of file+ assert optional_params["extra_body"]["input_type"] == "text"+++def test_optional_params_image_gen_with_aspect_ratio():+ optional_params = get_optional_params_image_gen(+ model="imagen-4.0-ultra-generate-preview-06-06",+ custom_llm_provider="vertex_ai",+ aspect_ratio="16:9",+ )+ assert optional_params["aspect_ratio"] == "16:9"diff --git a/tests/local_testing/test_streaming.py b/tests/local_testing/test_streaming.pyindex 5db40946772..841e5b87234 100644--- a/tests/local_testing/test_streaming.py+++ b/tests/local_testing/test_streaming.py@@ -80,7 +80,9 @@ def validate_first_format(chunk):for choice in chunk["choices"]:assert isinstance(choice["index"], int), "'index' should be an integer."- assert isinstance(choice["delta"]["role"], str), "'role' should be a string."+ assert isinstance(+ choice["delta"]["role"], str+ ), f"'role' should be a string. Got {choice['delta']['role']}"assert "messages" not in choice# openai v1.0.0 returns content as Noneassert (choice["finish_reason"] is None) or isinstance(@@ -672,7 +674,6 @@ def test_completion_model_stream(model):pytest.fail(f"Error occurred: {e}")-@pytest.mark.parametrize("sync_mode",[True, False],@@ -889,6 +890,7 @@ async def test_completion_gemini_stream_accumulated_json(sync_mode):# returnpytest.fail(f"Error occurred: {e}")+@pytest.mark.flaky(retries=3, delay=1)def test_completion_mistral_api_mistral_large_function_call_with_streaming():litellm.set_verbose = Truediff --git a/tests/test_litellm/llms/vertex_ai/test_vertex_image_generation.py b/tests/test_litellm/llms/vertex_ai/test_vertex_image_generation.pynew file mode 100644index 00000000000..1f680f22dde--- /dev/null+++ b/tests/test_litellm/llms/vertex_ai/test_vertex_image_generation.py@@ -0,0 +1,158 @@+import os+import sys+from unittest.mock import MagicMock++import pytest++sys.path.insert(+ 0, os.path.abspath("../..")+) # Adds the parent directory to the system path++import litellm+from litellm.llms.vertex_ai.image_generation.image_generation_handler import (+ VertexImageGeneration,+)+++class TestVertexImageGeneration:+ def setup_method(self):+ """Set up test fixtures"""+ self.vertex_image_gen = VertexImageGeneration()++ def test_transform_optional_params_none(self):+ """Test transform_optional_params with None input"""+ result = self.vertex_image_gen.transform_optional_params(None)+ expected = {"sampleCount": 1}+ assert result == expected++ def test_transform_optional_params_empty_dict(self):+ """Test transform_optional_params with empty dict"""+ result = self.vertex_image_gen.transform_optional_params({})+ expected = {}+ assert result == expected++ def test_transform_optional_params_no_underscores(self):+ """Test transform_optional_params with params that don't have underscores"""+ input_params = {+ "sampleCount": 2,+ "guidanceScale": 7.5,+ "model": "imagegeneration",+ }+ result = self.vertex_image_gen.transform_optional_params(input_params)+ expected = {"sampleCount": 2, "guidanceScale": 7.5, "model": "imagegeneration"}+ assert result == expected++ def test_transform_optional_params_with_underscores(self):+ """Test transform_optional_params with snake_case params that need transformation"""+ input_params = {+ "aspect_ratio": "16:9",+ "sample_count": 3,+ "guidance_scale": 8.0,+ "max_output_tokens": 1024,+ "negative_prompt": "bad quality",+ }+ result = self.vertex_image_gen.transform_optional_params(input_params)+ expected = {+ "aspectRatio": "16:9",+ "sampleCount": 3,+ "guidanceScale": 8.0,+ "maxOutputTokens": 1024,+ "negativePrompt": "bad quality",+ }+ assert result == expected++ def test_transform_optional_params_mixed_params(self):+ """Test transform_optional_params with mixed snake_case and camelCase params"""+ input_params = {+ "aspect_ratio": "1:1",+ "sampleCount": 2,+ "guidance_scale": 7.0,+ "model": "imagegeneration",+ "output_format": "png",+ "temperature": 0.8,+ }+ result = self.vertex_image_gen.transform_optional_params(input_params)+ expected = {+ "aspectRatio": "1:1",+ "sampleCount": 2,+ "guidanceScale": 7.0,+ "model": "imagegeneration",+ "outputFormat": "png",+ "temperature": 0.8,+ }+ assert result == expected++ def test_transform_optional_params_complex_snake_case(self):+ """Test transform_optional_params with complex snake_case params"""+ input_params = {+ "very_long_parameter_name": "test",+ "multi_word_config_setting": 42,+ "another_test_param": True,+ }+ result = self.vertex_image_gen.transform_optional_params(input_params)+ expected = {+ "veryLongParameterName": "test",+ "multiWordConfigSetting": 42,+ "anotherTestParam": True,+ }+ assert result == expected++ def test_transform_optional_params_single_underscore(self):+ """Test transform_optional_params with single underscore params"""+ input_params = {"test_param": "value", "a_b": "short"}+ result = self.vertex_image_gen.transform_optional_params(input_params)+ expected = {"testParam": "value", "aB": "short"}+ assert result == expected++ def test_transform_optional_params_preserves_values(self):+ """Test that transform_optional_params preserves all value types correctly"""+ input_params = {+ "string_param": "test_string",+ "int_param": 123,+ "float_param": 45.67,+ "bool_param": True,+ "list_param": [1, 2, 3],+ "dict_param": {"nested": "value"},+ "none_param": None,+ }+ result = self.vertex_image_gen.transform_optional_params(input_params)+ expected = {+ "stringParam": "test_string",+ "intParam": 123,+ "floatParam": 45.67,+ "boolParam": True,+ "listParam": [1, 2, 3],+ "dictParam": {"nested": "value"},+ "noneParam": None,+ }+ assert result == expected++ def test_snake_to_camel_conversion(self):+ """Test the internal snake_to_camel conversion logic"""+ # Test the method directly by accessing the internal function+ test_cases = [+ ("aspect_ratio", "aspectRatio"),+ ("sample_count", "sampleCount"),+ ("guidance_scale", "guidanceScale"),+ ("max_output_tokens", "maxOutputTokens"),+ ("very_long_parameter_name", "veryLongParameterName"),+ ("a_b_c_d", "aBCD"),+ ("single", "single"), # No underscore+ ("", ""), # Empty string+ ]++ for snake_case, expected_camel_case in test_cases:+ # We need to test this through the transform_optional_params method+ # since the snake_to_camel function is defined inside it+ if "_" in snake_case:+ result = self.vertex_image_gen.transform_optional_params(+ {snake_case: "test"}+ )+ assert expected_camel_case in result+ assert result[expected_camel_case] == "test"+ elif snake_case: # Handle empty string case+ result = self.vertex_image_gen.transform_optional_params(+ {snake_case: "test"}+ )+ assert snake_case in result+ assert result[snake_case] == "test"