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
[Feat] Add Bridge from generateContent <> /chat/completions (#12081)
Ishaan Jafff1c7024e706e
diff --git a/docs/my-website/docs/proxy/prod.md b/docs/my-website/docs/proxy/prod.mdindex a618e530796..e16c4ed25a6 100644--- a/docs/my-website/docs/proxy/prod.md+++ b/docs/my-website/docs/proxy/prod.md@@ -22,7 +22,6 @@ general_settings:database_connection_pool_limit: 10 # limit the number of database connections to = MAX Number of DB Connections/Number of instances of litellm proxy (Around 10-20 is good number)# OPTIONAL Best Practices- disable_spend_logs: True # turn off writing each transaction to the db. We recommend doing this is you don't need to see Usage on the LiteLLM UI and are tracking metrics via Prometheusdisable_error_logs: True # turn off writing LLM Exceptions to DBallow_requests_on_db_unavailable: True # Only USE when running LiteLLM on your VPC. Allow requests to still be processed even if the DB is unavailable. We recommend doing this if you're running LiteLLM on VPC that cannot be accessed from the public internet.@@ -139,23 +138,9 @@ When `allow_requests_on_db_unavailable` is set to `true`, LiteLLM will handle er| LiteLLM Budget Errors or Model Errors | ❌ Request will be blocked | Triggered when the DB is reachable but the authentication token is invalid, lacks access, or exceeds budget limits. |-## 7. Disable spend_logs & error_logs if not using the LiteLLM UI--By default, LiteLLM writes several types of logs to the database:-- Every LLM API request to the `LiteLLM_SpendLogs` table-- LLM Exceptions to the `LiteLLM_SpendLogs` table--If you're not viewing these logs on the LiteLLM UI, you can disable them by setting the following flags to `True`:--```yaml-general_settings:- disable_spend_logs: True # Disable writing spend logs to DB- disable_error_logs: True # Disable writing error logs to DB-```-[More information about what the Database is used for here](db_info)-## 8. Use Helm PreSync Hook for Database Migrations [BETA]+## 7. Use Helm PreSync Hook for Database Migrations [BETA]To ensure only one service manages database migrations, use our [Helm PreSync hook for Database Migrations](https://github.com/BerriAI/litellm/blob/main/deploy/charts/litellm-helm/templates/migrations-job.yaml). This ensures migrations are handled during `helm upgrade` or `helm install`, while LiteLLM pods explicitly disable migrations.@@ -183,7 +168,7 @@ To ensure only one service manages database migrations, use our [Helm PreSync ho```-## 9. Set LiteLLM Salt Key+## 8. Set LiteLLM Salt KeyIf you plan on using the DB, set a salt key for encrypting/decrypting variables in the DB.@@ -198,7 +183,7 @@ export LITELLM_SALT_KEY="sk-1234"[**See Code**](https://github.com/BerriAI/litellm/blob/036a6821d588bd36d170713dcf5a72791a694178/litellm/proxy/common_utils/encrypt_decrypt_utils.py#L15)-## 10. Use `prisma migrate deploy`+## 9. Use `prisma migrate deploy`Use this to handle db migrations across LiteLLM versions in productiondiff --git a/litellm/google_genai/adapters/__init__.py b/litellm/google_genai/adapters/__init__.pynew file mode 100644index 00000000000..96ff777ebe8--- /dev/null+++ b/litellm/google_genai/adapters/__init__.py@@ -0,0 +1,19 @@+"""+Google GenAI Adapters for LiteLLM++This module provides adapters for transforming Google GenAI generate_content requests+to/from LiteLLM completion format with full support for:+- Text content transformation+- Tool calling (function declarations, function calls, function responses)+- Streaming (both regular and tool calling)+- Mixed content (text + tool calls)+"""++from .handler import GenerateContentToCompletionHandler+from .transformation import GoogleGenAIAdapter, GoogleGenAIStreamWrapper++__all__ = [+ "GoogleGenAIAdapter",+ "GoogleGenAIStreamWrapper",+ "GenerateContentToCompletionHandler"+]\ No newline at end of filediff --git a/litellm/google_genai/adapters/handler.py b/litellm/google_genai/adapters/handler.pynew file mode 100644index 00000000000..651a6413cad--- /dev/null+++ b/litellm/google_genai/adapters/handler.py@@ -0,0 +1,130 @@+from typing import Any, AsyncIterator, Coroutine, Dict, List, Optional, Union, cast++import litellm+from litellm.types.utils import ModelResponse++from .transformation import GoogleGenAIAdapter++# Initialize adapter+GOOGLE_GENAI_ADAPTER = GoogleGenAIAdapter()+++class GenerateContentToCompletionHandler:+ """Handler for transforming generate_content calls to completion format when provider config is None"""++ @staticmethod+ def _prepare_completion_kwargs(+ model: str,+ contents: Union[List[Dict[str, Any]], Dict[str, Any]],+ config: Optional[Dict[str, Any]] = None,+ stream: bool = False,+ extra_kwargs: Optional[Dict[str, Any]] = None,+ ) -> Dict[str, Any]:+ """Prepare kwargs for litellm.completion/acompletion"""++ # Transform generate_content request to completion format+ completion_request = GOOGLE_GENAI_ADAPTER.translate_generate_content_to_completion(+ model=model,+ contents=contents,+ config=config,+ **(extra_kwargs or {})+ )++ completion_kwargs: Dict[str, Any] = dict(completion_request)++ if stream:+ completion_kwargs["stream"] = stream++ return completion_kwargs++ @staticmethod+ async def async_generate_content_handler(+ model: str,+ contents: Union[List[Dict[str, Any]], Dict[str, Any]],+ config: Optional[Dict[str, Any]] = None,+ stream: bool = False,+ **kwargs,+ ) -> Union[Dict[str, Any], AsyncIterator[bytes]]:+ """Handle generate_content call asynchronously using completion adapter"""++ completion_kwargs = GenerateContentToCompletionHandler._prepare_completion_kwargs(+ model=model,+ contents=contents,+ config=config,+ stream=stream,+ extra_kwargs=kwargs,+ )++ try:+ completion_response = await litellm.acompletion(**completion_kwargs)++ if stream:+ # Transform streaming completion response to generate_content format+ transformed_stream = GOOGLE_GENAI_ADAPTER.translate_completion_output_params_streaming(+ completion_response+ )+ if transformed_stream is not None:+ return transformed_stream+ raise ValueError("Failed to transform streaming response")+ else:+ # Transform completion response back to generate_content format+ generate_content_response = GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content(+ cast(ModelResponse, completion_response)+ )+ return generate_content_response++ except Exception as e:+ raise ValueError(+ f"Error calling litellm.acompletion for generate_content: {str(e)}"+ )++ @staticmethod+ def generate_content_handler(+ model: str,+ contents: Union[List[Dict[str, Any]], Dict[str, Any]],+ config: Optional[Dict[str, Any]] = None,+ stream: bool = False,+ _is_async: bool = False,+ **kwargs,+ ) -> Union[Dict[str, Any], AsyncIterator[bytes], Coroutine[Any, Any, Union[Dict[str, Any], AsyncIterator[bytes]]]]:+ """Handle generate_content call using completion adapter"""++ if _is_async:+ return GenerateContentToCompletionHandler.async_generate_content_handler(+ model=model,+ contents=contents,+ config=config,+ stream=stream,+ **kwargs,+ )++ completion_kwargs = GenerateContentToCompletionHandler._prepare_completion_kwargs(+ model=model,+ contents=contents,+ config=config,+ stream=stream,+ extra_kwargs=kwargs,+ )++ try:+ completion_response = litellm.completion(**completion_kwargs)++ if stream:+ # Transform streaming completion response to generate_content format+ transformed_stream = GOOGLE_GENAI_ADAPTER.translate_completion_output_params_streaming(+ completion_response+ )+ if transformed_stream is not None:+ return transformed_stream+ raise ValueError("Failed to transform streaming response")+ else:+ # Transform completion response back to generate_content format+ generate_content_response = GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content(+ cast(ModelResponse, completion_response)+ )+ return generate_content_response++ except Exception as e:+ raise ValueError(+ f"Error calling litellm.completion for generate_content: {str(e)}"+ )\ No newline at end of filediff --git a/litellm/google_genai/adapters/transformation.py b/litellm/google_genai/adapters/transformation.pynew file mode 100644index 00000000000..915e436b216--- /dev/null+++ b/litellm/google_genai/adapters/transformation.py@@ -0,0 +1,589 @@+import json+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union, cast++from litellm.litellm_core_utils.json_validation_rule import normalize_tool_schema+from litellm.types.llms.openai import (+ AllMessageValues,+ ChatCompletionAssistantMessage,+ ChatCompletionAssistantToolCall,+ ChatCompletionRequest,+ ChatCompletionToolCallFunctionChunk,+ ChatCompletionToolChoiceValues,+ ChatCompletionToolMessage,+ ChatCompletionToolParam,+ ChatCompletionUserMessage,+)+from litellm.types.utils import (+ AdapterCompletionStreamWrapper,+ Choices,+ ModelResponse,+ StreamingChoices,+)+++class GoogleGenAIStreamWrapper(AdapterCompletionStreamWrapper):+ """+ Wrapper for streaming Google GenAI generate_content responses.+ Transforms OpenAI streaming chunks to Google GenAI format.+ """++ sent_first_chunk: bool = False+ # State tracking for accumulating partial tool calls+ accumulated_tool_calls: Dict[str, Dict[str, Any]]++ def __init__(self, completion_stream: Any):+ super().__init__(completion_stream)+ self.sent_first_chunk = False+ self.accumulated_tool_calls = {}++ def __next__(self):+ try:+ for chunk in self.completion_stream:+ if chunk == "None" or chunk is None:+ continue++ # Transform OpenAI streaming chunk to Google GenAI format+ transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content(chunk, self)+ if transformed_chunk: # Only return non-empty chunks+ return transformed_chunk++ raise StopIteration+ except StopIteration:+ raise StopIteration+ except Exception:+ raise StopIteration++ async def __anext__(self):+ try:+ async for chunk in self.completion_stream:+ if chunk == "None" or chunk is None:+ continue++ # Transform OpenAI streaming chunk to Google GenAI format+ transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content(chunk, self)+ if transformed_chunk: # Only return non-empty chunks+ return transformed_chunk++ raise StopAsyncIteration+ except StopAsyncIteration:+ raise StopAsyncIteration+ except Exception:+ raise StopAsyncIteration++ def google_genai_sse_wrapper(self) -> Iterator[bytes]:+ """+ Convert Google GenAI streaming chunks to Server-Sent Events format.+ """+ for chunk in self:+ if isinstance(chunk, dict):+ payload = f"data: {json.dumps(chunk)}\n\n"+ yield payload.encode()+ else:+ yield chunk++ async def async_google_genai_sse_wrapper(self) -> AsyncIterator[bytes]:+ """+ Async version of google_genai_sse_wrapper.+ """+ async for chunk in self:+ if isinstance(chunk, dict):+ payload = f"data: {json.dumps(chunk)}\n\n"+ yield payload.encode()+ else:+ yield chunk+++class GoogleGenAIAdapter:+ """Adapter for transforming Google GenAI generate_content requests to/from litellm.completion format"""++ def __init__(self) -> None:+ pass+++ def translate_generate_content_to_completion(+ self,+ model: str,+ contents: Union[List[Dict[str, Any]], Dict[str, Any]],+ config: Optional[Dict[str, Any]] = None,+ **kwargs+ ) -> ChatCompletionRequest:+ """+ Transform generate_content request to litellm completion format++ Args:+ model: The model name+ contents: Generate content contents (can be list or single dict)+ config: Optional config parameters+ **kwargs: Additional parameters++ Returns:+ ChatCompletionRequest in OpenAI format+ """++ # Normalize contents to list format+ if isinstance(contents, dict):+ contents_list = [contents]+ else:+ contents_list = contents++ # Transform contents to OpenAI messages format+ messages = self._transform_contents_to_messages(contents_list)++ # Create base request+ completion_request: ChatCompletionRequest = ChatCompletionRequest(+ model=model,+ messages=messages,+ )++ #########################################################+ # Supported OpenAI chat completion params+ # - temperature+ # - max_tokens+ # - top_p+ # - frequency_penalty+ # - presence_penalty+ # - stop+ # - tools+ # - tool_choice+ #########################################################++ # Add config parameters if provided+ if config:+ # Map common Google GenAI config parameters to OpenAI equivalents+ if "temperature" in config:+ completion_request["temperature"] = config["temperature"]+ if "maxOutputTokens" in config:+ completion_request["max_tokens"] = config["maxOutputTokens"]+ if "topP" in config:+ completion_request["top_p"] = config["topP"]+ if "topK" in config:+ # OpenAI doesn't have direct topK, but we can pass it as extra+ pass+ if "stopSequences" in config:+ completion_request["stop"] = config["stopSequences"]++ # Handle tools transformation+ if "tools" in kwargs:+ tools = kwargs["tools"]++ # Check if tools are already in OpenAI format or Google GenAI format+ if isinstance(tools, list) and len(tools) > 0:+ # Tools are in Google GenAI format, transform them+ openai_tools = self._transform_google_genai_tools_to_openai(tools)+ if openai_tools:+ completion_request["tools"] = openai_tools++ # Handle tool_config (tool choice)+ if "tool_config" in kwargs:+ tool_choice = self._transform_google_genai_tool_config_to_openai(kwargs["tool_config"])+ if tool_choice:+ completion_request["tool_choice"] = tool_choice++ return completion_request++ def translate_completion_output_params_streaming(+ self, completion_stream: Any+ ) -> Union[AsyncIterator[bytes], None]:+ """Transform streaming completion output to Google GenAI format"""+ google_genai_wrapper = GoogleGenAIStreamWrapper(completion_stream=completion_stream)+ # Return the SSE-wrapped version for proper event formatting+ return google_genai_wrapper.async_google_genai_sse_wrapper()++ def _transform_google_genai_tools_to_openai(self, tools: List[Dict[str, Any]]) -> List[ChatCompletionToolParam]:+ """Transform Google GenAI tools to OpenAI tools format"""+ openai_tools: List[Dict[str, Any]] = []++ for tool in tools:+ if "functionDeclarations" in tool:+ for func_decl in tool["functionDeclarations"]:+ function_chunk: Dict[str, Any] = {+ "name": func_decl.get("name", ""),+ }++ if "description" in func_decl:+ function_chunk["description"] = func_decl["description"]+ if "parameters" in func_decl:+ function_chunk["parameters"] = func_decl["parameters"]++ openai_tool = {+ "type": "function",+ "function": function_chunk+ }+ openai_tools.append(openai_tool)+++ # normalize the tool schemas+ normalized_tools = [normalize_tool_schema(tool) for tool in openai_tools]++ return cast(List[ChatCompletionToolParam], normalized_tools)++ def _transform_google_genai_tool_config_to_openai(self, tool_config: Dict[str, Any]) -> Optional[ChatCompletionToolChoiceValues]:+ """Transform Google GenAI tool_config to OpenAI tool_choice"""+ function_calling_config = tool_config.get("functionCallingConfig", {})+ mode = function_calling_config.get("mode", "AUTO")++ mode_mapping = {+ "AUTO": "auto",+ "ANY": "required",+ "NONE": "none"+ }++ tool_choice = mode_mapping.get(mode, "auto")+ return cast(ChatCompletionToolChoiceValues, tool_choice)++ def _transform_contents_to_messages(self, contents: List[Dict[str, Any]]) -> List[AllMessageValues]:+ """Transform Google GenAI contents to OpenAI messages format"""+ messages: List[AllMessageValues] = []++ for content in contents:+ role = content.get("role", "user")+ parts = content.get("parts", [])++ if role == "user":+ # Handle user messages with potential function responses+ combined_text = ""+ tool_messages: List[ChatCompletionToolMessage] = []++ for part in parts:+ if isinstance(part, dict):+ if "text" in part:+ combined_text += part["text"]+ elif "functionResponse" in part:+ # Transform function response to tool message+ func_response = part["functionResponse"]+ tool_message = ChatCompletionToolMessage(+ role="tool",+ tool_call_id=f"call_{func_response.get('name', 'unknown')}",+ content=json.dumps(func_response.get("response", {}))+ )+ tool_messages.append(tool_message)+ elif isinstance(part, str):+ combined_text += part++ # Add user message if there's text content+ if combined_text:+ messages.append(ChatCompletionUserMessage(+ role="user",+ content=combined_text+ ))++ # Add tool messages+ messages.extend(tool_messages)++ elif role == "model":+ # Handle assistant messages with potential function calls+ combined_text = ""+ tool_calls: List[ChatCompletionAssistantToolCall] = []++ for part in parts:+ if isinstance(part, dict):+ if "text" in part:+ combined_text += part["text"]+ elif "functionCall" in part:+ # Transform function call to tool call+ func_call = part["functionCall"]+ tool_call = ChatCompletionAssistantToolCall(+ id=f"call_{func_call.get('name', 'unknown')}",+ type="function",+ function=ChatCompletionToolCallFunctionChunk(+ name=func_call.get("name", ""),+ arguments=json.dumps(func_call.get("args", {}))+ )+ )+ tool_calls.append(tool_call)+ elif isinstance(part, str):+ combined_text += part++ # Create assistant message+ if tool_calls:+ assistant_message = ChatCompletionAssistantMessage(+ role="assistant",+ content=combined_text if combined_text else None,+ tool_calls=tool_calls+ )+ else:+ assistant_message = ChatCompletionAssistantMessage(+ role="assistant",+ content=combined_text if combined_text else None+ )++ messages.append(assistant_message)++ return messages++ def translate_completion_to_generate_content(+ self, response: ModelResponse+ ) -> Dict[str, Any]:+ """+ Transform litellm completion response to Google GenAI generate_content format++ Args:+ response: ModelResponse from litellm.completion++ Returns:+ Dict in Google GenAI generate_content response format+ """++ # Extract the main response content+ choice = response.choices[0] if response.choices else None+ if not choice:+ raise ValueError("Invalid completion response: no choices found")++ # Handle different choice types (Choices vs StreamingChoices)+ if isinstance(choice, Choices):+ if not choice.message:+ raise ValueError("Invalid completion response: no message found in choice")+ parts = self._transform_openai_message_to_google_genai_parts(choice.message)+ elif isinstance(choice, StreamingChoices):+ if not choice.delta:+ raise ValueError("Invalid completion response: no delta found in streaming choice")+ parts = self._transform_openai_delta_to_google_genai_parts(choice.delta)+ else:+ # Fallback for generic choice objects+ message_content = getattr(choice, 'message', {}).get('content', '') or getattr(choice, 'delta', {}).get('content', '')+ parts = [{"text": message_content}] if message_content else []++ # Create Google GenAI format response+ generate_content_response: Dict[str, Any] = {+ "candidates": [+ {+ "content": {+ "parts": parts,+ "role": "model"+ },+ "finishReason": self._map_finish_reason(getattr(choice, 'finish_reason', None)),+ "index": 0,+ "safetyRatings": []+ }+ ],+ "usageMetadata": (+ self._map_usage(getattr(response, 'usage', None))+ if hasattr(response, 'usage') and getattr(response, 'usage', None)+ else {+ "promptTokenCount": 0,+ "candidatesTokenCount": 0,+ "totalTokenCount": 0+ }+ )+ }++ # Add text field for convenience (common in Google GenAI responses)+ text_content = ""+ for part in parts:+ if isinstance(part, dict) and "text" in part:+ text_content += part["text"]+ if text_content:+ generate_content_response["text"] = text_content++ return generate_content_response++ def translate_streaming_completion_to_generate_content(+ self, response: ModelResponse, wrapper: GoogleGenAIStreamWrapper+ ) -> Dict[str, Any]:+ """+ Transform streaming litellm completion chunk to Google GenAI generate_content format++ Args:+ response: Streaming ModelResponse chunk from litellm.completion+ wrapper: GoogleGenAIStreamWrapper instance++ Returns:+ Dict in Google GenAI streaming generate_content response format+ """++ # Extract the main response content from streaming chunk+ choice = response.choices[0] if response.choices else None+ if not choice:+ # Return empty chunk if no choices+ return {}++ # Handle streaming choice+ if isinstance(choice, StreamingChoices):+ if choice.delta:+ parts = self._transform_openai_delta_to_google_genai_parts_with_accumulation(choice.delta, wrapper)+ else:+ parts = []+ finish_reason = getattr(choice, 'finish_reason', None)+ else:+ # Fallback for generic choice objects+ message_content = getattr(choice, 'delta', {}).get('content', '')+ parts = [{"text": message_content}] if message_content else []+ finish_reason = getattr(choice, 'finish_reason', None)++ # Only create response chunk if we have parts or it's the final chunk+ if not parts and not finish_reason:+ return {}++ # Create Google GenAI streaming format response+ streaming_chunk: Dict[str, Any] = {+ "candidates": [+ {+ "content": {+ "parts": parts,+ "role": "model"+ },+ "finishReason": self._map_finish_reason(finish_reason) if finish_reason else None,+ "index": 0,+ "safetyRatings": []+ }+ ]+ }++ # Add usage metadata only in the final chunk (when finish_reason is present)+ if finish_reason:+ usage_metadata = self._map_usage(getattr(response, 'usage', None)) if hasattr(response, 'usage') and getattr(response, 'usage', None) else {+ "promptTokenCount": 0,+ "candidatesTokenCount": 0,+ "totalTokenCount": 0+ }+ streaming_chunk["usageMetadata"] = usage_metadata++ # Add text field for convenience (common in Google GenAI responses)+ text_content = ""+ for part in parts:+ if isinstance(part, dict) and "text" in part:+ text_content += part["text"]+ if text_content:+ streaming_chunk["text"] = text_content++ return streaming_chunk++ def _transform_openai_message_to_google_genai_parts(self, message: Any) -> List[Dict[str, Any]]:+ """Transform OpenAI message to Google GenAI parts format"""+ parts: List[Dict[str, Any]] = []++ # Add text content if present+ if hasattr(message, 'content') and message.content:+ parts.append({"text": message.content})++ # Add tool calls if present+ if hasattr(message, 'tool_calls') and message.tool_calls:+ for tool_call in message.tool_calls:+ if hasattr(tool_call, 'function') and tool_call.function:+ try:+ args = json.loads(tool_call.function.arguments) if tool_call.function.arguments else {}+ except json.JSONDecodeError:+ args = {}++ function_call_part = {+ "functionCall": {+ "name": tool_call.function.name,+ "args": args+ }+ }+ parts.append(function_call_part)++ return parts if parts else [{"text": ""}]++ def _transform_openai_delta_to_google_genai_parts(self, delta: Any) -> List[Dict[str, Any]]:+ """Transform OpenAI delta to Google GenAI parts format for streaming"""+ parts: List[Dict[str, Any]] = []++ # Add text content if present+ if hasattr(delta, 'content') and delta.content:+ parts.append({"text": delta.content})++ # Add tool calls if present (for streaming tool calls)+ if hasattr(delta, 'tool_calls') and delta.tool_calls:+ for tool_call in delta.tool_calls:+ if hasattr(tool_call, 'function') and tool_call.function:+ # For streaming, we might get partial function arguments+ args_str = getattr(tool_call.function, 'arguments', '') or ''+ try:+ args = json.loads(args_str) if args_str else {}+ except json.JSONDecodeError:+ # For partial JSON in streaming, return as text for now+ args = {"partial": args_str}++ function_call_part = {+ "functionCall": {+ "name": getattr(tool_call.function, 'name', '') or '',+ "args": args+ }+ }+ parts.append(function_call_part)++ return parts++ def _transform_openai_delta_to_google_genai_parts_with_accumulation(+ self, delta: Any, wrapper: GoogleGenAIStreamWrapper+ ) -> List[Dict[str, Any]]:+ """Transform OpenAI delta to Google GenAI parts format with tool call accumulation"""+ parts: List[Dict[str, Any]] = []++ # Add text content if present+ if hasattr(delta, 'content') and delta.content:+ parts.append({"text": delta.content})++ # Handle tool calls with accumulation for streaming+ if hasattr(delta, 'tool_calls') and delta.tool_calls:+ for tool_call in delta.tool_calls:+ if hasattr(tool_call, 'function') and tool_call.function:+ tool_call_id = getattr(tool_call, 'id', '') or 'call_unknown'+ function_name = getattr(tool_call.function, 'name', '') or ''+ args_str = getattr(tool_call.function, 'arguments', '') or ''++ # Initialize accumulation for this tool call if not exists+ if tool_call_id not in wrapper.accumulated_tool_calls:+ wrapper.accumulated_tool_calls[tool_call_id] = {+ 'name': '',+ 'arguments': '',+ 'complete': False+ }++ # Accumulate function name if provided+ if function_name:+ wrapper.accumulated_tool_calls[tool_call_id]['name'] = function_name++ # Accumulate arguments if provided+ if args_str:+ wrapper.accumulated_tool_calls[tool_call_id]['arguments'] += args_str++ # Try to parse the accumulated arguments as JSON+ accumulated_args = wrapper.accumulated_tool_calls[tool_call_id]['arguments']+ try:+ if accumulated_args:+ parsed_args = json.loads(accumulated_args)+ # JSON is valid, mark as complete and create function call part+ wrapper.accumulated_tool_calls[tool_call_id]['complete'] = True++ function_call_part = {+ "functionCall": {+ "name": wrapper.accumulated_tool_calls[tool_call_id]['name'],+ "args": parsed_args+ }+ }+ parts.append(function_call_part)++ # Clean up completed tool call+ del wrapper.accumulated_tool_calls[tool_call_id]++ except json.JSONDecodeError:+ # JSON is still incomplete, continue accumulating+ # Don't add to parts yet+ pass++ return parts++ def _map_finish_reason(self, finish_reason: Optional[str]) -> str:+ """Map OpenAI finish reasons to Google GenAI finish reasons"""+ if not finish_reason:+ return "STOP"++ mapping = {+ "stop": "STOP",+ "length": "MAX_TOKENS",+ "content_filter": "SAFETY",+ "tool_calls": "STOP",+ "function_call": "STOP",+ }++ return mapping.get(finish_reason, "STOP")++ def _map_usage(self, usage: Any) -> Dict[str, int]:+ """Map OpenAI usage to Google GenAI usage format"""+ return {+ "promptTokenCount": getattr(usage, "prompt_tokens", 0) or 0,+ "candidatesTokenCount": getattr(usage, "completion_tokens", 0) or 0,+ "totalTokenCount": getattr(usage, "total_tokens", 0) or 0,+ }\ No newline at end of filediff --git a/litellm/google_genai/main.py b/litellm/google_genai/main.pyindex 237e195c9a8..f1847057db9 100644--- a/litellm/google_genai/main.py+++ b/litellm/google_genai/main.py@@ -8,6 +8,9 @@ from pydantic import BaseModelimport litellmfrom litellm.constants import request_timeout++# Import the adapter for fallback to completion format+from litellm.google_genai.adapters.handler import GenerateContentToCompletionHandlerfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.llms.base_llm.google_genai.transformation import (BaseGoogleGenAIGenerateContentConfig,@@ -38,7 +41,7 @@ class GenerateContentSetupResult(BaseModel):model: strrequest_body: Dict[str, Any]custom_llm_provider: str- generate_content_provider_config: BaseGoogleGenAIGenerateContentConfig+ generate_content_provider_config: Optional[BaseGoogleGenAIGenerateContentConfig]generate_content_config_dict: Dict[str, Any]litellm_params: GenericLiteLLMParamslitellm_logging_obj: LiteLLMLoggingObj@@ -131,9 +134,19 @@ class GenerateContentHelper:)if generate_content_provider_config is None:- operation = "streaming" if stream else ""- raise ValueError(- f"Generate content {operation} is not supported for {custom_llm_provider}".strip()+ # Use adapter to transform to completion format when provider config is None+ # Signal that we should use the adapter by returning special result+ if litellm_logging_obj is None:+ raise ValueError("litellm_logging_obj is required, but got None")+ return GenerateContentSetupResult(+ model=model,+ custom_llm_provider=custom_llm_provider,+ request_body={}, # Will be handled by adapter+ generate_content_provider_config=None, # type: ignore+ generate_content_config_dict=dict(config or {}),+ litellm_params=litellm_params,+ litellm_logging_obj=litellm_logging_obj,+ litellm_call_id=litellm_call_id)@@ -278,7 +291,19 @@ def generate_content(**kwargs)- # Call the handler+ # Check if we should use the adapter (when provider config is None)+ if setup_result.generate_content_provider_config is None:+ # Use the adapter to convert to completion format+ return GenerateContentToCompletionHandler.generate_content_handler(+ model=setup_result.model,+ contents=contents, # type: ignore+ config=setup_result.generate_content_config_dict,+ stream=False,+ _is_async=_is_async,+ **kwargs+ )++ # Call the standard handlerresponse = base_llm_http_handler.generate_content_handler(model=setup_result.model,contents=contents,@@ -345,6 +370,17 @@ async def agenerate_content_stream(**kwargs)+ # Check if we should use the adapter (when provider config is None)+ if setup_result.generate_content_provider_config is None:+ # Use the adapter to convert to completion format+ return await GenerateContentToCompletionHandler.async_generate_content_handler(+ model=setup_result.model,+ contents=contents, # type: ignore+ config=setup_result.generate_content_config_dict,+ stream=True,+ **kwargs+ )+# Call the handler with async enabled and streaming# Return the coroutine directly for the router to handlereturn await base_llm_http_handler.generate_content_handler(@@ -395,7 +431,7 @@ def generate_content_stream(local_vars = locals()try:# Remove any async-related flags since this is the sync function- kwargs.pop("agenerate_content_stream", None)+ _is_async = kwargs.pop("agenerate_content_stream", False)# Setup the callsetup_result = GenerateContentHelper.setup_generate_content_call(@@ -407,6 +443,18 @@ def generate_content_stream(**kwargs)+ # Check if we should use the adapter (when provider config is None)+ if setup_result.generate_content_provider_config is None:+ # Use the adapter to convert to completion format+ return GenerateContentToCompletionHandler.generate_content_handler(+ model=setup_result.model,+ contents=contents, # type: ignore+ config=setup_result.generate_content_config_dict,+ stream=True,+ _is_async=_is_async,+ **kwargs+ )+# Call the handler with streaming enabled (sync version)return base_llm_http_handler.generate_content_handler(model=setup_result.model,@@ -419,7 +467,7 @@ def generate_content_stream(extra_headers=extra_headers,extra_body=extra_body,timeout=timeout or request_timeout,- _is_async=False,+ _is_async=_is_async,client=kwargs.get("client"),stream=True,litellm_metadata=kwargs.get("litellm_metadata", {}),diff --git a/litellm/litellm_core_utils/json_validation_rule.py b/litellm/litellm_core_utils/json_validation_rule.pyindex 53e1479783b..315a90fe300 100644--- a/litellm/litellm_core_utils/json_validation_rule.py+++ b/litellm/litellm_core_utils/json_validation_rule.py@@ -1,4 +1,97 @@import json+from typing import Any, Dict, List, Union++from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH+++def normalize_json_schema_types(schema: Union[Dict[str, Any], List[Any], Any], depth: int = 0, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> Union[Dict[str, Any], List[Any], Any]:+ """+ Normalize JSON schema types from uppercase to lowercase format.++ Some providers (like certain Google services) use uppercase types like 'BOOLEAN', 'STRING', 'ARRAY', 'OBJECT'+ but standard JSON Schema requires lowercase: 'boolean', 'string', 'array', 'object'++ This function recursively normalizes all type fields in a schema to lowercase.++ Args:+ schema: The schema to normalize (dict, list, or other)+ depth: Current recursion depth+ max_depth: Maximum recursion depth to prevent infinite loops++ Returns:+ The normalized schema with lowercase types+ """+ # Prevent infinite recursion+ if depth >= max_depth:+ return schema++ if not isinstance(schema, (dict, list)):+ return schema++ # Type mapping from uppercase to lowercase+ type_mapping = {+ 'BOOLEAN': 'boolean',+ 'STRING': 'string',+ 'ARRAY': 'array',+ 'OBJECT': 'object',+ 'NUMBER': 'number',+ 'INTEGER': 'integer',+ 'NULL': 'null'+ }++ if isinstance(schema, list):+ return [normalize_json_schema_types(item, depth + 1, max_depth) for item in schema]++ if isinstance(schema, dict):+ normalized_schema: Dict[str, Any] = {}++ for key, value in schema.items():+ if key == 'type' and isinstance(value, str) and value in type_mapping:+ normalized_schema[key] = type_mapping[value]+ elif key == 'properties' and isinstance(value, dict):+ # Recursively normalize properties+ normalized_schema[key] = {+ prop_key: normalize_json_schema_types(prop_value, depth + 1, max_depth)+ for prop_key, prop_value in value.items()+ }+ elif key == 'items' and isinstance(value, (dict, list)):+ # Recursively normalize array items+ normalized_schema[key] = normalize_json_schema_types(value, depth + 1, max_depth)+ elif isinstance(value, (dict, list)):+ # Recursively normalize any nested dict or list+ normalized_schema[key] = normalize_json_schema_types(value, depth + 1, max_depth)+ else:+ normalized_schema[key] = value++ return normalized_schema++ return schema+++def normalize_tool_schema(tool: Dict[str, Any]) -> Dict[str, Any]:+ """+ Normalize a tool's parameter schema to use standard JSON Schema lowercase types.++ Args:+ tool: The tool definition containing function parameters++ Returns:+ The tool with normalized schema types+ """+ if not isinstance(tool, dict):+ return tool++ normalized_tool = tool.copy()++ # Normalize function parameters if present+ if 'function' in tool and isinstance(tool['function'], dict):+ normalized_tool['function'] = tool['function'].copy()+ if 'parameters' in tool['function']:+ normalized_tool['function']['parameters'] = normalize_json_schema_types(+ tool['function']['parameters']+ )++ return normalized_tooldef validate_schema(schema: dict, response: str):diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex b31ab0b2724..498cf4dcf70 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -1,8 +1,17 @@model_list:- - model_name: azure_ai/*+ - model_name: anthropic/*litellm_params:- model: azure_ai/*+ model: anthropic/*+ - model_name: openai/*+ litellm_params:+ model: openai/*+router_settings:+ model_group_alias: {+ "gemini-2.5-pro": "anthropic/claude-sonnet-4-20250514",+ "gemini-2.5-flash": "anthropic/claude-sonnet-4-20250514",+ # "gemini-2.5-pro": "openai/gpt-4o-mini"+ }mcp_servers:deepwiki_mcp:diff --git a/tests/code_coverage_tests/recursive_detector.py b/tests/code_coverage_tests/recursive_detector.pyindex 2bfde87fbd2..b2fe50bae14 100644--- a/tests/code_coverage_tests/recursive_detector.py+++ b/tests/code_coverage_tests/recursive_detector.py@@ -23,6 +23,7 @@ IGNORE_FUNCTIONS = ["_can_object_call_model", # max depth set."encode_unserializable_types", # max depth set."filter_value_from_dict", # max depth set.+ "normalize_json_schema_types", # max depth set.]diff --git a/tests/test_litellm/google_genai/test_google_genai_adapter.py b/tests/test_litellm/google_genai/test_google_genai_adapter.pynew file mode 100644index 00000000000..45fa9375234--- /dev/null+++ b/tests/test_litellm/google_genai/test_google_genai_adapter.py@@ -0,0 +1,950 @@+#!/usr/bin/env python3+"""+Test to verify the Google GenAI generate_content adapter functionality+"""+import json+import os+import sys++import pytest++sys.path.insert(+ 0, os.path.abspath("../../..")+) # Adds the parent directory to the system path++import json+import os+import sys++import pytest+++def test_adapter_import():+ """Test that the adapter can be imported successfully"""+ from litellm.google_genai.adapters.handler import GenerateContentToCompletionHandler+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ # Should not raise any exceptions+ assert GoogleGenAIAdapter is not None+ assert GenerateContentToCompletionHandler is not None++def test_single_content_transformation():+ """Test the transformation from generate_content to completion format with single content"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ # Test input+ model = "gpt-3.5-turbo"+ contents = {+ "role": "user",+ "parts": [{"text": "Hello, how are you?"}]+ }+ config = {+ "temperature": 0.7,+ "maxOutputTokens": 100+ }++ # Transform to completion format+ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents,+ config=config+ )++ # Verify the transformation+ assert completion_request["model"] == "gpt-3.5-turbo"+ assert len(completion_request["messages"]) == 1+ assert completion_request["messages"][0]["role"] == "user"+ assert completion_request["messages"][0]["content"] == "Hello, how are you?"+ assert completion_request["temperature"] == 0.7+ assert completion_request["max_tokens"] == 100++def test_list_contents_transformation():+ """Test transformation with list of contents (conversation history)"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ # Test input with conversation history+ model = "gpt-3.5-turbo"+ contents = [+ {+ "role": "user",+ "parts": [{"text": "Hello, how are you?"}]+ },+ {+ "role": "model",+ "parts": [{"text": "I'm doing well, thank you!"}]+ },+ {+ "role": "user",+ "parts": [{"text": "What's the weather like?"}]+ }+ ]++ # Transform to completion format+ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Verify the transformation+ assert completion_request["model"] == "gpt-3.5-turbo"+ assert len(completion_request["messages"]) == 3++ # Check first message+ assert completion_request["messages"][0]["role"] == "user"+ assert completion_request["messages"][0]["content"] == "Hello, how are you?"++ # Check second message+ assert completion_request["messages"][1]["role"] == "assistant"+ assert completion_request["messages"][1]["content"] == "I'm doing well, thank you!"++ # Check third message+ assert completion_request["messages"][2]["role"] == "user"+ assert completion_request["messages"][2]["content"] == "What's the weather like?"++def test_config_parameter_mapping():+ """Test that config parameters are correctly mapped"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ model = "gpt-3.5-turbo"+ contents = {"role": "user", "parts": [{"text": "Test"}]}+ config = {+ "temperature": 0.8,+ "maxOutputTokens": 150,+ "topP": 0.9,+ "stopSequences": ["END", "STOP"]+ }++ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents,+ config=config+ )++ # Verify parameter mapping+ assert completion_request["temperature"] == 0.8+ assert completion_request["max_tokens"] == 150+ assert completion_request["top_p"] == 0.9+ assert completion_request["stop"] == ["END", "STOP"]++def test_tools_transformation():+ """Test transformation of Google GenAI tools to OpenAI tools format"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ model = "gpt-3.5-turbo"+ contents = {"role": "user", "parts": [{"text": "What's the weather?"}]}++ # Google GenAI tools format+ tools = [+ {+ "functionDeclarations": [+ {+ "name": "get_weather",+ "description": "Get current weather information",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {+ "type": "string",+ "description": "The city name"+ }+ },+ "required": ["location"]+ }+ },+ {+ "name": "get_forecast",+ "description": "Get weather forecast",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {"type": "string"},+ "days": {"type": "integer"}+ }+ }+ }+ ]+ }+ ]++ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents,+ tools=tools+ )++ # Verify tools transformation+ assert "tools" in completion_request+ openai_tools = completion_request["tools"]+ assert len(openai_tools) == 2++ # Check first tool+ tool1 = openai_tools[0]+ assert tool1["type"] == "function"+ assert tool1["function"]["name"] == "get_weather"+ assert tool1["function"]["description"] == "Get current weather information"+ assert "parameters" in tool1["function"]+ assert tool1["function"]["parameters"]["properties"]["location"]["type"] == "string"++ # Check second tool+ tool2 = openai_tools[1]+ assert tool2["type"] == "function"+ assert tool2["function"]["name"] == "get_forecast"+ assert tool2["function"]["description"] == "Get weather forecast"++def test_tool_config_transformation():+ """Test transformation of Google GenAI tool_config to OpenAI tool_choice"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ model = "gpt-3.5-turbo"+ contents = {"role": "user", "parts": [{"text": "Test"}]}++ # Test different tool config modes+ test_cases = [+ ({"functionCallingConfig": {"mode": "AUTO"}}, "auto"),+ ({"functionCallingConfig": {"mode": "ANY"}}, "required"),+ ({"functionCallingConfig": {"mode": "NONE"}}, "none"),+ ({"functionCallingConfig": {"mode": "UNKNOWN"}}, "auto"), # Default case+ ]++ for tool_config, expected_choice in test_cases:+ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents,+ tool_config=tool_config+ )++ assert "tool_choice" in completion_request+ assert completion_request["tool_choice"] == expected_choice++def test_function_call_message_transformation():+ """Test transformation of messages with function calls"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ model = "gpt-3.5-turbo"+ contents = [+ {+ "role": "user",+ "parts": [{"text": "What's the weather in San Francisco?"}]+ },+ {+ "role": "model",+ "parts": [+ {"text": "I'll check the weather for you."},+ {+ "functionCall": {+ "name": "get_weather",+ "args": {"location": "San Francisco"}+ }+ }+ ]+ }+ ]++ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Verify the transformation+ messages = completion_request["messages"]+ assert len(messages) == 2++ # Check user message+ assert messages[0]["role"] == "user"+ assert messages[0]["content"] == "What's the weather in San Francisco?"++ # Check assistant message with tool call+ assistant_msg = messages[1]+ assert assistant_msg["role"] == "assistant"+ assert assistant_msg["content"] == "I'll check the weather for you."+ assert "tool_calls" in assistant_msg+ assert len(assistant_msg["tool_calls"]) == 1++ tool_call = assistant_msg["tool_calls"][0]+ assert tool_call["type"] == "function"+ assert tool_call["function"]["name"] == "get_weather"++ # Verify arguments are properly JSON encoded+ args = json.loads(tool_call["function"]["arguments"])+ assert args["location"] == "San Francisco"++def test_function_response_message_transformation():+ """Test transformation of messages with function responses"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ model = "gpt-3.5-turbo"+ contents = [+ {+ "role": "user",+ "parts": [+ {"text": "Here's the weather data:"},+ {+ "functionResponse": {+ "name": "get_weather",+ "response": {+ "temperature": "72F",+ "condition": "sunny",+ "humidity": "45%"+ }+ }+ }+ ]+ }+ ]++ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Verify the transformation+ messages = completion_request["messages"]+ assert len(messages) == 2 # User message + tool message++ # Check user message+ user_msg = messages[0]+ assert user_msg["role"] == "user"+ assert user_msg["content"] == "Here's the weather data:"++ # Check tool message+ tool_msg = messages[1]+ assert tool_msg["role"] == "tool"+ assert "call_get_weather" in tool_msg["tool_call_id"]++ # Verify function response content+ response_content = json.loads(tool_msg["content"])+ assert response_content["temperature"] == "72F"+ assert response_content["condition"] == "sunny"+ assert response_content["humidity"] == "45%"++def test_completion_to_generate_content_with_tool_calls():+ """Test transforming completion response with tool calls back to generate_content format"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter+ from litellm.types.llms.openai import (+ ChatCompletionAssistantMessage,+ ChatCompletionAssistantToolCall,+ ChatCompletionToolCallFunctionChunk,+ )+ from litellm.types.utils import Choices, ModelResponse, Usage++ adapter = GoogleGenAIAdapter()++ # Create mock tool call+ mock_tool_call = ChatCompletionAssistantToolCall(+ id="call_123",+ type="function",+ function=ChatCompletionToolCallFunctionChunk(+ name="get_weather",+ arguments='{"location": "San Francisco"}'+ )+ )++ # Create mock assistant message with tool call+ mock_message = ChatCompletionAssistantMessage(+ role="assistant",+ content="I'll check the weather for you.",+ tool_calls=[mock_tool_call]+ )++ mock_choice = Choices(+ finish_reason="tool_calls",+ index=0,+ message=mock_message+ )++ mock_usage = Usage(+ prompt_tokens=15,+ completion_tokens=25,+ total_tokens=40+ )++ mock_response = ModelResponse(+ id="test-123",+ choices=[mock_choice],+ created=1234567890,+ model="gpt-3.5-turbo",+ object="chat.completion",+ usage=mock_usage+ )++ # Transform back to generate_content format+ generate_content_response = adapter.translate_completion_to_generate_content(mock_response)++ # Verify the transformation+ assert "candidates" in generate_content_response+ candidate = generate_content_response["candidates"][0]+ assert candidate["finishReason"] == "STOP" # tool_calls maps to STOP++ # Check content parts+ parts = candidate["content"]["parts"]+ assert len(parts) == 2++ # Check text part+ text_part = parts[0]+ assert text_part["text"] == "I'll check the weather for you."++ # Check function call part+ function_part = parts[1]+ assert "functionCall" in function_part+ function_call = function_part["functionCall"]+ assert function_call["name"] == "get_weather"+ assert function_call["args"]["location"] == "San Francisco"++ # Check text field+ assert generate_content_response["text"] == "I'll check the weather for you."++def test_streaming_tool_calls_transformation():+ """Test streaming transformation with tool calls"""+ from litellm.google_genai.adapters.transformation import (+ GoogleGenAIAdapter,+ GoogleGenAIStreamWrapper,+ )+ from litellm.types.utils import (+ ChatCompletionDeltaToolCall,+ Delta,+ Function,+ ModelResponse,+ StreamingChoices,+ )++ adapter = GoogleGenAIAdapter()++ # Create mock function for tool call+ mock_function = Function(+ name="get_weather",+ arguments='{"location": "SF"}'+ )++ # Create mock streaming tool call delta+ mock_tool_call_delta = ChatCompletionDeltaToolCall(+ id="call_123",+ type="function",+ function=mock_function,+ index=0+ )++ # Create mock delta with tool call+ mock_delta = Delta(+ content=None,+ tool_calls=[mock_tool_call_delta]+ )++ mock_choice = StreamingChoices(+ finish_reason=None,+ index=0,+ delta=mock_delta+ )++ mock_response = ModelResponse(+ id="test-streaming",+ choices=[mock_choice],+ created=1234567890,+ model="gpt-3.5-turbo",+ object="chat.completion.chunk"+ )++ # Create mock wrapper for accumulation state+ mock_wrapper = GoogleGenAIStreamWrapper(completion_stream=None)++ # Transform streaming chunk+ streaming_chunk = adapter.translate_streaming_completion_to_generate_content(mock_response, mock_wrapper)++ # Verify the transformation+ assert "candidates" in streaming_chunk+ candidate = streaming_chunk["candidates"][0]++ # Check parts+ parts = candidate["content"]["parts"]+ assert len(parts) == 1++ # Check function call part+ function_part = parts[0]+ assert "functionCall" in function_part+ function_call = function_part["functionCall"]+ assert function_call["name"] == "get_weather"+ assert function_call["args"]["location"] == "SF"++def test_streaming_partial_tool_calls_accumulation():+ """Test accumulation of partial tool call arguments across streaming chunks"""+ from litellm.google_genai.adapters.transformation import (+ GoogleGenAIAdapter,+ GoogleGenAIStreamWrapper,+ )+ from litellm.types.utils import (+ ChatCompletionDeltaToolCall,+ Delta,+ Function,+ ModelResponse,+ StreamingChoices,+ )++ adapter = GoogleGenAIAdapter()+ mock_wrapper = GoogleGenAIStreamWrapper(completion_stream=None)++ # Simulate partial chunks that create valid JSON when accumulated+ partial_chunks = [+ ('read_file', '{"path"'), # First chunk: {"path"+ (None, ': "/Users'), # Second chunk: : "/Users+ (None, '/is'), # Third chunk: /is+ (None, 'haanjaffe'), # Fourth chunk: haanjaffe+ (None, 'r/Github/li'), # Fifth chunk: r/Github/li+ (None, 'tellm'), # Sixth chunk: tellm+ (None, '/README.md'), # Seventh chunk: /README.md+ (None, '"}') # Final chunk: "}+ ]++ # Process each partial chunk+ accumulated_results = []+ tool_call_id = "call_read_file_123" # Same ID for all chunks++ for function_name, chunk_args in partial_chunks:+ # Create mock function for tool call with partial arguments+ mock_function = Function(+ name=function_name, # Only set in first chunk+ arguments=chunk_args+ )++ # Create mock streaming tool call delta+ mock_tool_call_delta = ChatCompletionDeltaToolCall(+ id=tool_call_id, # Same ID across all chunks+ type="function",+ function=mock_function,+ index=0+ )++ # Create mock delta with tool call+ mock_delta = Delta(+ content=None,+ tool_calls=[mock_tool_call_delta]+ )++ mock_choice = StreamingChoices(+ finish_reason=None,+ index=0,+ delta=mock_delta+ )++ mock_response = ModelResponse(+ id="test-streaming",+ choices=[mock_choice],+ created=1234567890,+ model="gpt-3.5-turbo",+ object="chat.completion.chunk"+ )++ # Transform streaming chunk with accumulation+ streaming_chunk = adapter.translate_streaming_completion_to_generate_content(mock_response, mock_wrapper)+ accumulated_results.append(streaming_chunk)++ # Verify accumulation behavior+ # Most chunks should be empty (because JSON is incomplete)+ empty_chunks = [chunk for chunk in accumulated_results if not chunk]+ non_empty_chunks = [chunk for chunk in accumulated_results if chunk]++ # Should have several empty chunks while accumulating+ assert len(empty_chunks) > 0, "Should have empty chunks while accumulating partial JSON"++ # Should have exactly one non-empty chunk when JSON becomes complete+ assert len(non_empty_chunks) == 1, f"Should have exactly one complete chunk, got {len(non_empty_chunks)}"++ # Verify the final complete chunk+ final_chunk = non_empty_chunks[0]+ assert "candidates" in final_chunk+ candidate = final_chunk["candidates"][0]++ # Check parts+ parts = candidate["content"]["parts"]+ assert len(parts) == 1, f"Expected 1 part, got {len(parts)}"++ # Check function call part+ function_part = parts[0]+ assert "functionCall" in function_part, "Should have functionCall in the final chunk"+ function_call = function_part["functionCall"]+ assert function_call["name"] == "read_file", f"Expected function name 'read_file', got {function_call['name']}"+ assert function_call["args"]["path"] == "/Users/ishaanjaffer/Github/litellm/README.md", f"Expected complete path, got {function_call['args']}"++ # Verify that accumulated_tool_calls is cleaned up after completion+ assert len(mock_wrapper.accumulated_tool_calls) == 0, "Should clean up completed tool calls from accumulator"++def test_streaming_multiple_partial_tool_calls():+ """Test accumulation of multiple partial tool calls simultaneously"""+ from litellm.google_genai.adapters.transformation import (+ GoogleGenAIAdapter,+ GoogleGenAIStreamWrapper,+ )+ from litellm.types.utils import (+ ChatCompletionDeltaToolCall,+ Delta,+ Function,+ ModelResponse,+ StreamingChoices,+ )++ adapter = GoogleGenAIAdapter()+ mock_wrapper = GoogleGenAIStreamWrapper(completion_stream=None)++ # Test data for two tool calls being accumulated simultaneously+ # Format: (tool_call_id, function_name, args_chunk)+ test_chunks = [+ ("call_1", "read_file", '{"file1"'), # {"file1"+ ("call_2", "write_file", '{"file2"'), # {"file2"+ ("call_1", None, ': "test1.txt"'), # : "test1.txt"+ ("call_2", None, ': "test2.txt"'), # : "test2.txt"+ ("call_1", None, '}'), # }+ ("call_2", None, '}'), # }+ ]++ completed_chunks = []++ for call_id, function_name, args_chunk in test_chunks:+ # Create mock function for tool call+ mock_function = Function(+ name=function_name,+ arguments=args_chunk+ )++ # Create mock streaming tool call delta+ mock_tool_call_delta = ChatCompletionDeltaToolCall(+ id=call_id,+ type="function",+ function=mock_function,+ index=0+ )++ # Create mock delta with tool call+ mock_delta = Delta(+ content=None,+ tool_calls=[mock_tool_call_delta]+ )++ mock_choice = StreamingChoices(+ finish_reason=None,+ index=0,+ delta=mock_delta+ )++ mock_response = ModelResponse(+ id="test-streaming",+ choices=[mock_choice],+ created=1234567890,+ model="gpt-3.5-turbo",+ object="chat.completion.chunk"+ )++ # Transform streaming chunk with accumulation+ streaming_chunk = adapter.translate_streaming_completion_to_generate_content(mock_response, mock_wrapper)+ if streaming_chunk: # Only collect non-empty chunks+ completed_chunks.append(streaming_chunk)++ # Should have exactly 2 completed chunks (one for each tool call)+ assert len(completed_chunks) == 2, f"Expected 2 completed chunks, got {len(completed_chunks)}"++ # Extract function calls from completed chunks+ function_calls = []+ for chunk in completed_chunks:+ parts = chunk["candidates"][0]["content"]["parts"]+ for part in parts:+ if "functionCall" in part:+ function_calls.append(part["functionCall"])++ # Should have 2 function calls+ assert len(function_calls) == 2, f"Expected 2 function calls, got {len(function_calls)}"++ # Verify both function calls are complete and correct+ function_names = [fc["name"] for fc in function_calls]+ assert "read_file" in function_names, "Should have read_file function call"+ assert "write_file" in function_names, "Should have write_file function call"++ # Verify arguments are correctly assembled+ for fc in function_calls:+ if fc["name"] == "read_file":+ assert fc["args"]["file1"] == "test1.txt", f"Expected file1: test1.txt, got {fc['args']}"+ elif fc["name"] == "write_file":+ assert fc["args"]["file2"] == "test2.txt", f"Expected file2: test2.txt, got {fc['args']}"++ # Verify cleanup+ assert len(mock_wrapper.accumulated_tool_calls) == 0, "Should clean up all completed tool calls"++def test_mixed_content_transformation():+ """Test transformation of mixed content (text + function calls)"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ model = "gpt-3.5-turbo"+ contents = [+ {+ "role": "model",+ "parts": [+ {"text": "I'll help you with that. Let me check the weather and also get the forecast."},+ {+ "functionCall": {+ "name": "get_weather",+ "args": {"location": "San Francisco"}+ }+ },+ {+ "functionCall": {+ "name": "get_forecast",+ "args": {"location": "San Francisco", "days": 3}+ }+ }+ ]+ }+ ]++ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Verify the transformation+ messages = completion_request["messages"]+ assert len(messages) == 1++ assistant_msg = messages[0]+ assert assistant_msg["role"] == "assistant"+ assert assistant_msg["content"] == "I'll help you with that. Let me check the weather and also get the forecast."+ assert "tool_calls" in assistant_msg+ assert len(assistant_msg["tool_calls"]) == 2++ # Check first tool call+ tool_call1 = assistant_msg["tool_calls"][0]+ assert tool_call1["function"]["name"] == "get_weather"+ args1 = json.loads(tool_call1["function"]["arguments"])+ assert args1["location"] == "San Francisco"++ # Check second tool call+ tool_call2 = assistant_msg["tool_calls"][1]+ assert tool_call2["function"]["name"] == "get_forecast"+ args2 = json.loads(tool_call2["function"]["arguments"])+ assert args2["location"] == "San Francisco"+ assert args2["days"] == 3++def test_completion_to_generate_content_transformation():+ """Test transforming a completion response back to generate_content format"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter+ from litellm.types.llms.openai import ChatCompletionAssistantMessage+ from litellm.types.utils import Choices, ModelResponse, Usage++ adapter = GoogleGenAIAdapter()++ # Create proper mock response using actual types+ mock_message = ChatCompletionAssistantMessage(+ role="assistant",+ content="Hello! I'm doing well, thank you for asking."+ )++ mock_choice = Choices(+ finish_reason="stop",+ index=0,+ message=mock_message+ )++ mock_usage = Usage(+ prompt_tokens=10,+ completion_tokens=20,+ total_tokens=30+ )++ # Create mock completion response+ mock_response = ModelResponse(+ id="test-123",+ choices=[mock_choice],+ created=1234567890,+ model="gpt-3.5-turbo",+ object="chat.completion",+ usage=mock_usage+ )++ # Transform back to generate_content format+ generate_content_response = adapter.translate_completion_to_generate_content(mock_response)++ # Verify the transformation+ assert "text" in generate_content_response+ assert generate_content_response["text"] == "Hello! I'm doing well, thank you for asking."++ assert "candidates" in generate_content_response+ assert len(generate_content_response["candidates"]) == 1++ candidate = generate_content_response["candidates"][0]+ assert candidate["finishReason"] == "STOP"+ assert candidate["index"] == 0+ assert candidate["content"]["role"] == "model"+ assert len(candidate["content"]["parts"]) == 1+ assert candidate["content"]["parts"][0]["text"] == "Hello! I'm doing well, thank you for asking."++ assert "usageMetadata" in generate_content_response+ usage = generate_content_response["usageMetadata"]+ assert usage["promptTokenCount"] == 10+ assert usage["candidatesTokenCount"] == 20+ assert usage["totalTokenCount"] == 30++def test_finish_reason_mapping():+ """Test that finish reasons are correctly mapped"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ # Test different finish reason mappings+ test_cases = [+ ("stop", "STOP"),+ ("length", "MAX_TOKENS"),+ ("content_filter", "SAFETY"),+ ("tool_calls", "STOP"),+ ("unknown_reason", "STOP"), # Default case+ (None, "STOP") # None case+ ]++ for openai_reason, expected_google_reason in test_cases:+ result = adapter._map_finish_reason(openai_reason)+ assert result == expected_google_reason++def test_empty_content_handling():+ """Test handling of empty or missing content"""+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter++ adapter = GoogleGenAIAdapter()++ # Test with empty parts+ model = "gpt-3.5-turbo"+ contents = {+ "role": "user",+ "parts": []+ }++ completion_request = adapter.translate_generate_content_to_completion(+ model=model,+ contents=contents+ )++ # Should still create a valid request but with empty messages+ assert completion_request["model"] == "gpt-3.5-turbo"+ assert "messages" in completion_request+ assert len(completion_request["messages"]) == 0++def test_handler_parameter_exclusion():+ """Test that the handler properly excludes Google GenAI-specific parameters"""+ from litellm.google_genai.adapters.handler import GenerateContentToCompletionHandler++ # Test parameters that should be excluded+ model = "gpt-3.5-turbo"+ contents = {"role": "user", "parts": [{"text": "Test"}]}+ config = {"temperature": 0.7}++ extra_kwargs = {+ "agenerate_content_stream": True, # Should be excluded+ "generate_content_stream": True, # Should be excluded+ }++ completion_kwargs = GenerateContentToCompletionHandler._prepare_completion_kwargs(+ model=model,+ contents=contents,+ config=config,+ stream=False,+ extra_kwargs=extra_kwargs+ )++ # Verify Google GenAI-specific parameters are excluded+ assert "agenerate_content_stream" not in completion_kwargs+ assert "generate_content_stream" not in completion_kwargs++ # Verify valid OpenAI parameters are present+ assert "model" in completion_kwargs+ assert completion_kwargs["model"] == "gpt-3.5-turbo"+ assert "temperature" in completion_kwargs+ assert completion_kwargs["temperature"] == 0.7++def test_shared_schema_normalization_utilities():+ """Test the shared schema normalization utility functions work correctly"""+ from litellm.litellm_core_utils.json_validation_rule import (+ normalize_json_schema_types,+ normalize_tool_schema,+ )++ # Test normalize_json_schema_types with nested structures+ schema_with_uppercase_types = {+ "type": "OBJECT",+ "properties": {+ "name": {"type": "STRING"},+ "age": {"type": "INTEGER"},+ "active": {"type": "BOOLEAN"},+ "scores": {+ "type": "ARRAY",+ "items": {"type": "NUMBER"}+ },+ "metadata": {+ "type": "OBJECT",+ "properties": {+ "nested_field": {"type": "STRING"}+ }+ }+ },+ "required": ["name", "age"]+ }++ normalized_schema = normalize_json_schema_types(schema_with_uppercase_types)++ # Check top-level type normalization+ assert normalized_schema["type"] == "object"++ # Check properties normalization+ props = normalized_schema["properties"]+ assert props["name"]["type"] == "string"+ assert props["age"]["type"] == "integer"+ assert props["active"]["type"] == "boolean"+ assert props["scores"]["type"] == "array"+ assert props["scores"]["items"]["type"] == "number"+ assert props["metadata"]["type"] == "object"+ assert props["metadata"]["properties"]["nested_field"]["type"] == "string"++ # Check non-type fields are preserved+ assert normalized_schema["required"] == ["name", "age"]++ # Test normalize_tool_schema+ tool_with_uppercase_types = {+ "type": "function",+ "function": {+ "name": "test_function",+ "description": "A test function",+ "parameters": {+ "type": "OBJECT",+ "properties": {+ "param1": {"type": "STRING"},+ "param2": {"type": "BOOLEAN"}+ }+ }+ }+ }++ normalized_tool = normalize_tool_schema(tool_with_uppercase_types)++ # Check that function info is preserved+ assert normalized_tool["type"] == "function"+ assert normalized_tool["function"]["name"] == "test_function"+ assert normalized_tool["function"]["description"] == "A test function"++ # Check that parameters are normalized+ params = normalized_tool["function"]["parameters"]+ assert params["type"] == "object"+ assert params["properties"]["param1"]["type"] == "string"+ assert params["properties"]["param2"]["type"] == "boolean"++ # Test edge cases+ assert normalize_json_schema_types("not_a_dict") == "not_a_dict"+ assert normalize_json_schema_types([{"type": "STRING"}]) == [{"type": "string"}]+ assert normalize_tool_schema("not_a_dict") == "not_a_dict"