Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test(gemini): Add unit tests for Google GenAI adapter

Henry Wang99a884019bf0
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 20f0d5b2e50..ae4625451a8 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -172,22 +172,22 @@ prometheus_initialize_budget_metrics: Optional[bool] = False
require_auth_for_metrics_endpoint: Optional[bool] = False
argilla_batch_size: Optional[int] = None
datadog_use_v1: Optional[bool] = False # if you want to use v1 datadog logged payload.
-gcs_pub_sub_use_v1: Optional[bool] = (
- False # if you want to use v1 gcs pubsub logged payload
-)
-generic_api_use_v1: Optional[bool] = (
- False # if you want to use v1 generic api logged payload
-)
+gcs_pub_sub_use_v1: Optional[
+ bool
+] = False # if you want to use v1 gcs pubsub logged payload
+generic_api_use_v1: Optional[
+ bool
+] = False # if you want to use v1 generic api logged payload
argilla_transformation_object: Optional[Dict[str, Any]] = None
-_async_input_callback: List[Union[str, Callable, CustomLogger]] = (
- []
-) # internal variable - async custom callbacks are routed here.
-_async_success_callback: List[Union[str, Callable, CustomLogger]] = (
- []
-) # internal variable - async custom callbacks are routed here.
-_async_failure_callback: List[Union[str, Callable, CustomLogger]] = (
- []
-) # internal variable - async custom callbacks are routed here.
+_async_input_callback: List[
+ Union[str, Callable, CustomLogger]
+] = [] # internal variable - async custom callbacks are routed here.
+_async_success_callback: List[
+ Union[str, Callable, CustomLogger]
+] = [] # internal variable - async custom callbacks are routed here.
+_async_failure_callback: List[
+ Union[str, Callable, CustomLogger]
+] = [] # internal variable - async custom callbacks are routed here.
pre_call_rules: List[Callable] = []
post_call_rules: List[Callable] = []
turn_off_message_logging: Optional[bool] = False
@@ -195,18 +195,18 @@ log_raw_request_response: bool = False
redact_messages_in_exceptions: Optional[bool] = False
redact_user_api_key_info: Optional[bool] = False
filter_invalid_headers: Optional[bool] = False
-add_user_information_to_llm_headers: Optional[bool] = (
- None # adds user_id, team_id, token hash (params from StandardLoggingMetadata) to request headers
-)
+add_user_information_to_llm_headers: Optional[
+ bool
+] = None # adds user_id, team_id, token hash (params from StandardLoggingMetadata) to request headers
store_audit_logs = False # Enterprise feature, allow users to see audit logs
### end of callbacks #############
-email: Optional[str] = (
- None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
-token: Optional[str] = (
- None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
+email: Optional[
+ str
+] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
+token: Optional[
+ str
+] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
telemetry = True
max_tokens: int = DEFAULT_MAX_TOKENS # OpenAI Defaults
drop_params = bool(os.getenv("LITELLM_DROP_PARAMS", False))
@@ -306,24 +306,20 @@ enable_loadbalancing_on_batch_endpoints: Optional[bool] = None
enable_caching_on_provider_specific_optional_params: bool = (
False # feature-flag for caching on optional params - e.g. 'top_k'
)
-caching: bool = (
- False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
-caching_with_models: bool = (
- False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
-cache: Optional[Cache] = (
- None # cache object <- use this - https://docs.litellm.ai/docs/caching
-)
+caching: bool = False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
+caching_with_models: bool = False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
+cache: Optional[
+ Cache
+] = None # cache object <- use this - https://docs.litellm.ai/docs/caching
default_in_memory_ttl: Optional[float] = None
default_redis_ttl: Optional[float] = None
default_redis_batch_cache_expiry: Optional[float] = None
model_alias_map: Dict[str, str] = {}
model_group_settings: Optional["ModelGroupSettings"] = None
max_budget: float = 0.0 # set the max budget across all providers
-budget_duration: Optional[str] = (
- None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
-)
+budget_duration: Optional[
+ str
+] = None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
default_soft_budget: float = (
DEFAULT_SOFT_BUDGET # by default all litellm proxy keys have a soft budget of 50.0
)
@@ -332,15 +328,11 @@ forward_traceparent_to_llm_provider: bool = False
_current_cost = 0.0 # private variable, used if max budget is set
error_logs: Dict = {}
-add_function_to_prompt: bool = (
- False # if function calling not supported by api, append function call details to system prompt
-)
+add_function_to_prompt: bool = False # if function calling not supported by api, append function call details to system prompt
client_session: Optional[httpx.Client] = None
aclient_session: Optional[httpx.AsyncClient] = None
model_fallbacks: Optional[List] = None # Deprecated for 'litellm.fallbacks'
-model_cost_map_url: str = (
- "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
-)
+model_cost_map_url: str = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
suppress_debug_info = False
dynamodb_table_name: Optional[str] = None
s3_callback_params: Optional[Dict] = None
@@ -370,9 +362,7 @@ prometheus_metrics_config: Optional[List] = None
disable_add_prefix_to_prompt: bool = (
False # used by anthropic, to disable adding prefix to prompt
)
-disable_copilot_system_to_assistant: bool = (
- False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior.
-)
+disable_copilot_system_to_assistant: bool = False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior.
public_model_groups: Optional[List[str]] = None
public_model_groups_links: Dict[str, str] = {}
#### REQUEST PRIORITIZATION ######
@@ -383,17 +373,13 @@ priority_reservation_settings: "PriorityReservationSettings" = (
######## Networking Settings ########
-use_aiohttp_transport: bool = (
- True # Older variable, aiohttp is now the default. use disable_aiohttp_transport instead.
-)
+use_aiohttp_transport: bool = True # Older variable, aiohttp is now the default. use disable_aiohttp_transport instead.
aiohttp_trust_env: bool = False # set to true to use HTTP_ Proxy settings
disable_aiohttp_transport: bool = False # Set this to true to use httpx instead
disable_aiohttp_trust_env: bool = (
False # When False, aiohttp will respect HTTP(S)_PROXY env vars
)
-force_ipv4: bool = (
- False # when True, litellm will force ipv4 for all LLM requests. Some users have seen httpx ConnectionError when using ipv6.
-)
+force_ipv4: bool = False # when True, litellm will force ipv4 for all LLM requests. Some users have seen httpx ConnectionError when using ipv6.
module_level_aclient = AsyncHTTPHandler(
timeout=request_timeout, client_alias="module level aclient"
)
@@ -407,13 +393,13 @@ fallbacks: Optional[List] = None
context_window_fallbacks: Optional[List] = None
content_policy_fallbacks: Optional[List] = None
allowed_fails: int = 3
-num_retries_per_request: Optional[int] = (
- None # for the request overall (incl. fallbacks + model retries)
-)
+num_retries_per_request: Optional[
+ int
+] = None # for the request overall (incl. fallbacks + model retries)
####### SECRET MANAGERS #####################
-secret_manager_client: Optional[Any] = (
- None # list of instantiated key management clients - e.g. azure kv, infisical, etc.
-)
+secret_manager_client: Optional[
+ Any
+] = None # list of instantiated key management clients - e.g. azure kv, infisical, etc.
_google_kms_resource_name: Optional[str] = None
_key_management_system: Optional[KeyManagementSystem] = None
_key_management_settings: KeyManagementSettings = KeyManagementSettings()
@@ -1342,12 +1328,12 @@ from .types.llms.custom_llm import CustomLLMItem
from .types.utils import GenericStreamingChunk
custom_provider_map: List[CustomLLMItem] = []
-_custom_providers: List[str] = (
- []
-) # internal helper util, used to track names of custom providers
-disable_hf_tokenizer_download: Optional[bool] = (
- None # disable huggingface tokenizer download. Defaults to openai clk100
-)
+_custom_providers: List[
+ str
+] = [] # internal helper util, used to track names of custom providers
+disable_hf_tokenizer_download: Optional[
+ bool
+] = None # disable huggingface tokenizer download. Defaults to openai clk100
global_disable_no_log_param: bool = False
### CLI UTILITIES ###
diff --git a/litellm/google_genai/adapters/handler.py b/litellm/google_genai/adapters/handler.py
index 2e3d7a836d2..575c36b946a 100644
--- a/litellm/google_genai/adapters/handler.py
+++ b/litellm/google_genai/adapters/handler.py
@@ -74,7 +74,7 @@ class GenerateContentToCompletionHandler:
if stream:
# Check if completion_response is actually a stream or a ModelResponse
# This can happen in error cases or when stream is not properly supported
- if not hasattr(completion_response, '__aiter__'):
+ if not hasattr(completion_response, "__aiter__"):
# If it's not a stream, treat it as a regular response
generate_content_response = (
GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content(
@@ -84,10 +84,8 @@ class GenerateContentToCompletionHandler:
return generate_content_response
else:
# Transform streaming completion response to generate_content format
- transformed_stream = (
- GOOGLE_GENAI_ADAPTER.translate_completion_output_params_streaming(
- completion_response
- )
+ transformed_stream = GOOGLE_GENAI_ADAPTER.translate_completion_output_params_streaming(
+ completion_response
)
if transformed_stream is not None:
return transformed_stream
@@ -149,7 +147,7 @@ class GenerateContentToCompletionHandler:
if stream:
# Check if completion_response is actually a stream or a ModelResponse
# This can happen in error cases or when stream is not properly supported
- if not hasattr(completion_response, '__iter__'):
+ if not hasattr(completion_response, "__iter__"):
# If it's not a stream, treat it as a regular response
generate_content_response = (
GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content(
@@ -159,10 +157,8 @@ class GenerateContentToCompletionHandler:
return generate_content_response
else:
# Transform streaming completion response to generate_content format
- transformed_stream = (
- GOOGLE_GENAI_ADAPTER.translate_completion_output_params_streaming(
- completion_response
- )
+ transformed_stream = GOOGLE_GENAI_ADAPTER.translate_completion_output_params_streaming(
+ completion_response
)
if transformed_stream is not None:
return transformed_stream
diff --git a/litellm/google_genai/adapters/transformation.py b/litellm/google_genai/adapters/transformation.py
index 56cc59b72b1..2b3cce5084a 100644
--- a/litellm/google_genai/adapters/transformation.py
+++ b/litellm/google_genai/adapters/transformation.py
@@ -43,7 +43,7 @@ class GoogleGenAIStreamWrapper(AdapterCompletionStreamWrapper):
def __next__(self):
try:
- if not hasattr(self.completion_stream, '__iter__'):
+ if not hasattr(self.completion_stream, "__iter__"):
if self._returned_response:
raise StopIteration
self._returned_response = True
@@ -69,7 +69,7 @@ class GoogleGenAIStreamWrapper(AdapterCompletionStreamWrapper):
async def __anext__(self):
try:
- if not hasattr(self.completion_stream, '__aiter__'):
+ if not hasattr(self.completion_stream, "__aiter__"):
if self._returned_response:
raise StopAsyncIteration
self._returned_response = True
@@ -98,7 +98,9 @@ class GoogleGenAIStreamWrapper(AdapterCompletionStreamWrapper):
try:
# For tool calls with no arguments, accumulated_args will be "", which is not valid JSON.
# We default to an empty JSON object in this case.
- parsed_args = json.loads(tool_call_data["arguments"] or "{}")
+ parsed_args = json.loads(
+ tool_call_data["arguments"] or "{}"
+ )
function_call_part = {
"functionCall": {
"name": tool_call_data["name"]
@@ -171,7 +173,7 @@ class GoogleGenAIStreamWrapper(AdapterCompletionStreamWrapper):
continue
else:
# For other chunk types, yield them directly
- if hasattr(chunk, 'encode'):
+ if hasattr(chunk, "encode"):
yield chunk.encode()
else:
yield str(chunk).encode()
@@ -191,7 +193,6 @@ class GoogleGenAIAdapter:
litellm_params: Optional[GenericLiteLLMParams] = None,
**kwargs,
) -> Dict[str, Any]:
-
"""
Transform generate_content request to litellm completion format
@@ -212,7 +213,6 @@ class GoogleGenAIAdapter:
tools = kwargs.get("tools")
tool_config = kwargs.get("toolConfig") or kwargs.get("tool_config")
-
# Normalize contents to list format
if isinstance(contents, dict):
contents_list = [contents]
@@ -224,7 +224,6 @@ class GoogleGenAIAdapter:
contents_list, system_instruction=system_instruction
)
-
# Create base request as dict (which is compatible with ChatCompletionRequest)
completion_request: ChatCompletionRequest = {
"model": model,
@@ -338,9 +337,7 @@ class GoogleGenAIAdapter:
if "description" in func_decl:
function_chunk["description"] = func_decl["description"]
if "parametersJsonSchema" in func_decl:
- function_chunk["parameters"] = func_decl[
- "parametersJsonSchema"
- ]
+ function_chunk["parameters"] = func_decl["parametersJsonSchema"]
openai_tool = {"type": "function", "function": function_chunk}
openai_tools.append(openai_tool)
@@ -377,7 +374,7 @@ class GoogleGenAIAdapter:
if system_parts and "text" in system_parts[0]:
messages.append(
ChatCompletionUserMessage(
- role="system", content=system_parts[0]["text"]
+ role="system", content=system_parts[0]["text"]
)
)
@@ -470,7 +467,9 @@ class GoogleGenAIAdapter:
Dict in Google GenAI generate_content response format
"""
if isinstance(response, AdapterCompletionStreamWrapper):
- return self.translate_streaming_completion_to_generate_content(response, wrapper=response)
+ return self.translate_streaming_completion_to_generate_content(
+ response, wrapper=response
+ )
# Extract the main response content
choice = response.choices[0] if response.choices else None
@@ -529,7 +528,6 @@ class GoogleGenAIAdapter:
response: Union[ModelResponse, ModelResponseStream],
wrapper: GoogleGenAIStreamWrapper,
) -> Optional[Dict[str, Any]]:
-
"""
Transform streaming litellm completion chunk to Google GenAI generate_content format
@@ -639,7 +637,6 @@ class GoogleGenAIAdapter:
return parts if parts else [{"text": ""}]
-
def _transform_openai_delta_to_google_genai_parts_with_accumulation(
self, delta: Any, wrapper: GoogleGenAIStreamWrapper
) -> List[Dict[str, Any]]:
@@ -688,7 +685,9 @@ class GoogleGenAIAdapter:
wrapper.accumulated_tool_calls[tool_call_index]["name"] = function_name
if args_chunk:
- wrapper.accumulated_tool_calls[tool_call_index]["arguments"] += args_chunk
+ wrapper.accumulated_tool_calls[tool_call_index][
+ "arguments"
+ ] += args_chunk
# Attempt to parse and emit a complete tool call
accumulated_data = wrapper.accumulated_tool_calls[tool_call_index]
diff --git a/litellm/proxy/_experimental/out/model_hub_table.html b/litellm/proxy/_experimental/out/model_hub_table.html
deleted file mode 100644
index 4f669ec00ac..00000000000
--- a/litellm/proxy/_experimental/out/model_hub_table.html
+++ /dev/null
@@ -1 +0,0 @@
-<!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/litellm-asset-prefix/_next/static/chunks/webpack-a426aae3231a8df1.js"/><script src="/litellm-asset-prefix/_next/static/chunks/fd9d1056-205af899b895cbac.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/117-6a9f6a591033d4a0.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/main-app-bb35cb240fbb9dca.js" async=""></script><title>LiteLLM Dashboard</title><meta name="description" content="LiteLLM Proxy Admin UI"/><link rel="icon" href="/favicon.ico" type="image/x-icon" sizes="16x16"/><link rel="icon" href="./favicon.ico"/><meta name="next-size-adjust"/><script src="/litellm-asset-prefix/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><script src="/litellm-asset-prefix/_next/static/chunks/webpack-a426aae3231a8df1.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:HL[\"/litellm-asset-prefix/_next/static/media/e4af272ccee01ff0-s.p.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n2:HL[\"/litellm-asset-prefix/_next/static/css/349654da14372cd9.css\",\"style\"]\n3:HL[\"/litellm-asset-prefix/_next/static/css/4103fa525703177b.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"4:I[12846,[],\"\"]\n6:I[19107,[],\"ClientPageRoot\"]\n7:I[22775,[\"50\",\"static/chunks/50-d0da2dd7acce2eb9.js\",\"521\",\"static/chunks/521-d97d355792d44830.js\",\"866\",\"static/chunks/866-9e1803a09e9ae8da.js\",\"154\",\"static/chunks/154-b1f2a106d0e0d77b.js\",\"162\",\"static/chunks/162-dd6427ff1a4ad9f4.js\",\"851\",\"static/chunks/851-bbe6d02cf41bb87a.js\",\"25\",\"static/chunks/app/model_hub_table/page-0b693f691bf0309f.js\"],\"default\",1]\n8:I[4707,[],\"\"]\n9:I[36423,[],\"\"]\nb:I[61060,[],\"\"]\nc:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L4\",null,{\"buildId\":\"Ap4Kq4vtq74RgOyxD-zii\",\"assetPrefix\":\"/litellm-asset-prefix\",\"urlParts\":[\"\",\"model_hub_table\"],\"initialTree\":[\"\",{\"children\":[\"model_hub_table\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"model_hub_table\",{\"children\":[\"__PAGE__\",{},[[\"$L5\",[\"$\",\"$L6\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$7\"}],null],null],null]},[null,[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"model_hub_table\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/349654da14372cd9.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"1\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/4103fa525703177b.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__className_1c856b\",\"children\":[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$La\"],\"globalErrorComponent\":\"$b\",\"missingSlots\":\"$Wc\"}]\n"])</script><script>self.__next_f.push([1,"a:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"LiteLLM Dashboard\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"LiteLLM Proxy Admin UI\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/favicon.ico\",\"type\":\"image/x-icon\",\"sizes\":\"16x16\"}],[\"$\",\"link\",\"5\",{\"rel\":\"icon\",\"href\":\"./favicon.ico\"}],[\"$\",\"meta\",\"6\",{\"name\":\"next-size-adjust\"}]]\n5:null\n"])</script></body></html>
\ No newline at end of file
diff --git a/litellm/proxy/_experimental/out/onboarding.html b/litellm/proxy/_experimental/out/onboarding.html
deleted file mode 100644
index 0df6a53a7c2..00000000000
--- a/litellm/proxy/_experimental/out/onboarding.html
+++ /dev/null
@@ -1 +0,0 @@
-<!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/litellm-asset-prefix/_next/static/chunks/webpack-a426aae3231a8df1.js"/><script src="/litellm-asset-prefix/_next/static/chunks/fd9d1056-205af899b895cbac.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/117-6a9f6a591033d4a0.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/main-app-bb35cb240fbb9dca.js" async=""></script><title>LiteLLM Dashboard</title><meta name="description" content="LiteLLM Proxy Admin UI"/><link rel="icon" href="/favicon.ico" type="image/x-icon" sizes="16x16"/><link rel="icon" href="./favicon.ico"/><meta name="next-size-adjust"/><script src="/litellm-asset-prefix/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><script src="/litellm-asset-prefix/_next/static/chunks/webpack-a426aae3231a8df1.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:HL[\"/litellm-asset-prefix/_next/static/media/e4af272ccee01ff0-s.p.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n2:HL[\"/litellm-asset-prefix/_next/static/css/349654da14372cd9.css\",\"style\"]\n3:HL[\"/litellm-asset-prefix/_next/static/css/4103fa525703177b.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"4:I[12846,[],\"\"]\n6:I[19107,[],\"ClientPageRoot\"]\n7:I[12011,[\"665\",\"static/chunks/3014691f-b7b79b78e27792f3.js\",\"50\",\"static/chunks/50-d0da2dd7acce2eb9.js\",\"154\",\"static/chunks/154-b1f2a106d0e0d77b.js\",\"461\",\"static/chunks/app/onboarding/page-d0d85032bb87ba51.js\"],\"default\",1]\n8:I[4707,[],\"\"]\n9:I[36423,[],\"\"]\nb:I[61060,[],\"\"]\nc:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L4\",null,{\"buildId\":\"Ap4Kq4vtq74RgOyxD-zii\",\"assetPrefix\":\"/litellm-asset-prefix\",\"urlParts\":[\"\",\"onboarding\"],\"initialTree\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"onboarding\",{\"children\":[\"__PAGE__\",{},[[\"$L5\",[\"$\",\"$L6\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$7\"}],null],null],null]},[null,[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"onboarding\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/349654da14372cd9.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"1\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/4103fa525703177b.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__className_1c856b\",\"children\":[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$La\"],\"globalErrorComponent\":\"$b\",\"missingSlots\":\"$Wc\"}]\n"])</script><script>self.__next_f.push([1,"a:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"LiteLLM Dashboard\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"LiteLLM Proxy Admin UI\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/favicon.ico\",\"type\":\"image/x-icon\",\"sizes\":\"16x16\"}],[\"$\",\"link\",\"5\",{\"rel\":\"icon\",\"href\":\"./favicon.ico\"}],[\"$\",\"meta\",\"6\",{\"name\":\"next-size-adjust\"}]]\n5:null\n"])</script></body></html>
\ No newline at end of file
diff --git a/litellm/proxy/google_endpoints/endpoints.py b/litellm/proxy/google_endpoints/endpoints.py
index 1b3fdfdb688..35c83f9ddb9 100644
--- a/litellm/proxy/google_endpoints/endpoints.py
+++ b/litellm/proxy/google_endpoints/endpoints.py
@@ -3,10 +3,7 @@ from fastapi.responses import StreamingResponse
from litellm.proxy._types import *
from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth
-from litellm.proxy.common_request_processing import (
- ProxyBaseLLMRequestProcessing,
- create_streaming_response,
-)
+
from litellm.proxy.common_utils.http_parsing_utils import _read_request_body
from litellm.types.llms.vertex_ai import TokenCountDetailsResponse
@@ -15,8 +12,13 @@ router = APIRouter(
)
[email protected]("/v1beta/models/{model_name}:generateContent", dependencies=[Depends(user_api_key_auth)])
[email protected]("/models/{model_name}:generateContent", dependencies=[Depends(user_api_key_auth)])
+ "/v1beta/models/{model_name}:generateContent",
+ dependencies=[Depends(user_api_key_auth)],
+)
+ "/models/{model_name}:generateContent", dependencies=[Depends(user_api_key_auth)]
+)
async def google_generate_content(
request: Request,
model_name: str,
@@ -35,8 +37,14 @@ async def google_generate_content(
return response
[email protected]("/v1beta/models/{model_name}:streamGenerateContent", dependencies=[Depends(user_api_key_auth)])
[email protected]("/models/{model_name}:streamGenerateContent", dependencies=[Depends(user_api_key_auth)])
+ "/v1beta/models/{model_name}:streamGenerateContent",
+ dependencies=[Depends(user_api_key_auth)],
+)
+ "/models/{model_name}:streamGenerateContent",
+ dependencies=[Depends(user_api_key_auth)],
+)
async def google_stream_generate_content(
request: Request,
model_name: str,
diff --git a/litellm/router.py b/litellm/router.py
index d9a4a58edfe..2091ebd66e5 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -337,8 +337,6 @@ class Router:
```
"""
- from litellm._service_logger import ServiceLogging
-
self.set_verbose = set_verbose
self.ignore_invalid_deployments = ignore_invalid_deployments
self.debug_level = debug_level
@@ -360,9 +358,9 @@ class Router:
) # names of models under litellm_params. ex. azure/chatgpt-v-2
self.deployment_latency_map = {}
### CACHING ###
- cache_type: Literal["local", "redis", "redis-semantic", "s3", "disk"] = (
- "local" # default to an in-memory cache
- )
+ cache_type: Literal[
+ "local", "redis", "redis-semantic", "s3", "disk"
+ ] = "local" # default to an in-memory cache
redis_cache = None
cache_config: Dict[str, Any] = {}
@@ -404,14 +402,14 @@ class Router:
self.default_max_parallel_requests = default_max_parallel_requests
self.provider_default_deployment_ids: List[str] = []
self.pattern_router = PatternMatchRouter()
- self.team_pattern_routers: Dict[str, PatternMatchRouter] = (
- {}
- ) # {"TEAM_ID": PatternMatchRouter}
+ self.team_pattern_routers: Dict[
+ str, PatternMatchRouter
+ ] = {} # {"TEAM_ID": PatternMatchRouter}
self.auto_routers: Dict[str, "AutoRouter"] = {}
# Initialize model ID to deployment index mapping for O(1) lookups
self.model_id_to_deployment_index_map: Dict[str, int] = {}
-
+
if model_list is not None:
# Build model index immediately to enable O(1) lookups from the start
self._build_model_id_to_deployment_index_map(model_list)
@@ -584,9 +582,9 @@ class Router:
)
)
- self.model_group_retry_policy: Optional[Dict[str, RetryPolicy]] = (
- model_group_retry_policy
- )
+ self.model_group_retry_policy: Optional[
+ Dict[str, RetryPolicy]
+ ] = model_group_retry_policy
self.allowed_fails_policy: Optional[AllowedFailsPolicy] = None
if allowed_fails_policy is not None:
@@ -1216,10 +1214,7 @@ class Router:
async def _acompletion(
self, model: str, messages: List[Dict[str, str]], **kwargs
- ) -> Union[
- ModelResponse,
- CustomStreamWrapper,
- ]:
+ ) -> Union[ModelResponse, CustomStreamWrapper,]:
"""
- Get an available deployment
- call it with a semaphore over the call
@@ -3176,9 +3171,9 @@ class Router:
healthy_deployments=healthy_deployments, responses=responses
)
returned_response = cast(OpenAIFileObject, responses[0])
- returned_response._hidden_params["model_file_id_mapping"] = (
- model_file_id_mapping
- )
+ returned_response._hidden_params[
+ "model_file_id_mapping"
+ ] = model_file_id_mapping
return returned_response
except Exception as e:
verbose_router_logger.exception(
@@ -3741,11 +3736,11 @@ class Router:
if isinstance(e, litellm.ContextWindowExceededError):
if context_window_fallbacks is not None:
- context_window_fallback_model_group: Optional[List[str]] = (
- self._get_fallback_model_group_from_fallbacks(
- fallbacks=context_window_fallbacks,
- model_group=model_group,
- )
+ context_window_fallback_model_group: Optional[
+ List[str]
+ ] = self._get_fallback_model_group_from_fallbacks(
+ fallbacks=context_window_fallbacks,
+ model_group=model_group,
)
if context_window_fallback_model_group is None:
raise original_exception
@@ -3777,11 +3772,11 @@ class Router:
e.message += "\n{}".format(error_message)
elif isinstance(e, litellm.ContentPolicyViolationError):
if content_policy_fallbacks is not None:
- content_policy_fallback_model_group: Optional[List[str]] = (
- self._get_fallback_model_group_from_fallbacks(
- fallbacks=content_policy_fallbacks,
- model_group=model_group,
- )
+ content_policy_fallback_model_group: Optional[
+ List[str]
+ ] = self._get_fallback_model_group_from_fallbacks(
+ fallbacks=content_policy_fallbacks,
+ model_group=model_group,
)
if content_policy_fallback_model_group is None:
raise original_exception
@@ -4988,7 +4983,9 @@ class Router:
model = deployment.to_json(exclude_none=True)
- self._add_model_to_list_and_index_map(model=model, model_id=deployment.model_info.id)
+ self._add_model_to_list_and_index_map(
+ model=model, model_id=deployment.model_info.id
+ )
return deployment
except Exception as e:
if self.ignore_invalid_deployments:
@@ -5017,26 +5014,26 @@ class Router:
"""
from litellm.router_strategy.auto_router.auto_router import AutoRouter
- auto_router_config_path: Optional[str] = (
- deployment.litellm_params.auto_router_config_path
- )
+ auto_router_config_path: Optional[
+ str
+ ] = deployment.litellm_params.auto_router_config_path
auto_router_config: Optional[str] = deployment.litellm_params.auto_router_config
if auto_router_config_path is None and auto_router_config is None:
raise ValueError(
"auto_router_config_path or auto_router_config is required for auto-router deployments. Please set it in the litellm_params"
)
- default_model: Optional[str] = (
- deployment.litellm_params.auto_router_default_model
- )
+ default_model: Optional[
+ str
+ ] = deployment.litellm_params.auto_router_default_model
if default_model is None:
raise ValueError(
"auto_router_default_model is required for auto-router deployments. Please set it in the litellm_params"
)
- embedding_model: Optional[str] = (
- deployment.litellm_params.auto_router_embedding_model
- )
+ embedding_model: Optional[
+ str
+ ] = deployment.litellm_params.auto_router_embedding_model
if embedding_model is None:
raise ValueError(
"auto_router_embedding_model is required for auto-router deployments. Please set it in the litellm_params"
@@ -5339,14 +5336,18 @@ class Router:
self._add_deployment(deployment=deployment)
# add to model names
- self._add_model_to_list_and_index_map(model=_deployment, model_id=deployment.model_info.id)
+ self._add_model_to_list_and_index_map(
+ model=_deployment, model_id=deployment.model_info.id
+ )
self.model_names.append(deployment.model_name)
return deployment
- def _update_deployment_indices_after_removal(self, model_id: str, removal_idx: int) -> None:
+ def _update_deployment_indices_after_removal(
+ self, model_id: str, removal_idx: int
+ ) -> None:
"""
Helper method to update deployment indices after a deployment has been removed from model_list.
-
+
Parameters:
- model_id: str - the id of the deployment that was removed
- removal_idx: int - the index where the deployment was removed from model_list
@@ -5359,11 +5360,12 @@ class Router:
if model_id in self.model_id_to_deployment_index_map:
del self.model_id_to_deployment_index_map[model_id]
-
- def _add_model_to_list_and_index_map(self, model: dict, model_id: Optional[str] = None) -> None:
+ def _add_model_to_list_and_index_map(
+ self, model: dict, model_id: Optional[str] = None
+ ) -> None:
"""
Helper method to add a model to the model_list and update the model_id_to_deployment_index_map.
-
+
Parameters:
- model: dict - the model to add to the list
- model_id: Optional[str] - the model ID to use for indexing. If None, will try to get from model["model_info"]["id"]
@@ -5373,7 +5375,9 @@ class Router:
if model_id is not None:
self.model_id_to_deployment_index_map[model_id] = len(self.model_list) - 1
elif model.get("model_info", {}).get("id") is not None:
- self.model_id_to_deployment_index_map[model["model_info"]["id"]] = len(self.model_list) - 1
+ self.model_id_to_deployment_index_map[model["model_info"]["id"]] = (
+ len(self.model_list) - 1
+ )
def upsert_deployment(self, deployment: Deployment) -> Optional[Deployment]:
"""
@@ -5402,13 +5406,15 @@ class Router:
removal_idx: Optional[int] = None
deployment_id = deployment.model_info.id
deployment_fast_mapping = self.model_id_to_deployment_index_map
-
+
if deployment_id in deployment_fast_mapping:
removal_idx = deployment_fast_mapping[deployment_id]
if removal_idx is not None:
self.model_list.pop(removal_idx)
- self._update_deployment_indices_after_removal(model_id=deployment_id, removal_idx=removal_idx)
+ self._update_deployment_indices_after_removal(
+ model_id=deployment_id, removal_idx=removal_idx
+ )
# if the model_id is not in router
self.add_deployment(deployment=deployment)
@@ -5439,7 +5445,9 @@ class Router:
if deployment_idx is not None:
# Pop the item from the list first
item = self.model_list.pop(deployment_idx)
- self._update_deployment_indices_after_removal(model_id=id, removal_idx=deployment_idx)
+ self._update_deployment_indices_after_removal(
+ model_id=id, removal_idx=deployment_idx
+ )
return item
else:
return None
@@ -5462,7 +5470,7 @@ class Router:
return model
else:
raise Exception("Model invalid format - {}".format(type(model)))
-
+
return None
def get_deployment_credentials(self, model_id: str) -> Optional[dict]:
@@ -6092,7 +6100,7 @@ class Router:
# Extract model_info from the model dict
model_info = model.get("model_info", {})
model_id = model_info.get("id")
-
+
# If no ID exists, generate one using the same logic as set_model_list
if model_id is None:
model_name = model.get("model_name", "")
@@ -6102,7 +6110,7 @@ class Router:
if "model_info" not in model:
model["model_info"] = {}
model["model_info"]["id"] = model_id
-
+
self._add_model_to_list_and_index_map(model=model, model_id=model_id)
def get_model_ids(
diff --git a/tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py b/tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py
new file mode 100644
index 00000000000..d4d0ba9d44c
--- /dev/null
+++ b/tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py
@@ -0,0 +1,290 @@
+#!/usr/bin/env python3
+"""
+Test to verify the Google GenAI adapter fixes
+"""
+import json
+import os
+import sys
+import unittest
+from unittest.mock import patch
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+
+import litellm
+from litellm.google_genai.adapters.handler import GenerateContentToCompletionHandler
+from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import ModelResponse
+
+
+def test_system_instruction_handling():
+ """Test that systemInstruction is correctly handled in translation"""
+ adapter = GoogleGenAIAdapter()
+
+ model = "gpt-3.5-turbo"
+ contents = [{"role": "user", "parts": [{"text": "Hello"}]}]
+ system_instruction = {
+ "parts": [{"text": "You are a helpful assistant"}]
+ }
+
+ # Transform to completion format with system instruction
+ completion_request = adapter.translate_generate_content_to_completion(
+ model=model,
+ contents=contents,
+ system_instruction=system_instruction
+ )
+
+ # Verify system instruction is correctly transformed
+ assert len(completion_request["messages"]) == 2
+ assert completion_request["messages"][0]["role"] == "system"
+ assert completion_request["messages"][0]["content"] == "You are a helpful assistant"
+ assert completion_request["messages"][1]["role"] == "user"
+ assert completion_request["messages"][1]["content"] == "Hello"
+
+
+def test_parameters_json_schema_transformation():
+ """Test that parametersJsonSchema is correctly transformed to parameters"""
+ adapter = GoogleGenAIAdapter()
+
+ # Google GenAI tools with parametersJsonSchema
+ tools = [
+ {
+ "functionDeclarations": [
+ {
+ "name": "get_weather",
+ "description": "Get current weather information",
+ "parametersJsonSchema": {
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": "The city name"
+ }
+ },
+ "required": ["location"]
+ }
+ }
+ ]
+ }
+ ]
+
+ # Transform tools
+ openai_tools = adapter._transform_google_genai_tools_to_openai(tools)
+
+ # Verify parametersJsonSchema is correctly transformed to parameters
+ assert len(openai_tools) == 1
+ tool = openai_tools[0]
+ assert tool["type"] == "function"
+ assert tool["function"]["name"] == "get_weather"
+ assert "parameters" in tool["function"]
+ assert tool["function"]["parameters"]["type"] == "object"
+ assert "properties" in tool["function"]["parameters"]
+ assert "location" in tool["function"]["parameters"]["properties"]
+
+
+def test_streaming_tool_call_with_empty_args():
+ """Test that streaming tool calls with empty arguments are handled correctly"""
+ from litellm.google_genai.adapters.transformation import (
+ GoogleGenAIStreamWrapper,
+ )
+ from litellm.types.utils import (
+ ChatCompletionDeltaToolCall,
+ Delta,
+ Function,
+ StreamingChoices,
+ )
+
+ adapter = GoogleGenAIAdapter()
+
+ # Create a tool call with empty arguments
+ mock_function = Function(
+ name="test_function",
+ arguments="" # Empty arguments
+ )
+
+ mock_tool_call_delta = ChatCompletionDeltaToolCall(
+ id="call_123",
+ type="function",
+ function=mock_function,
+ index=0
+ )
+
+ 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 a proper wrapper
+ mock_wrapper = GoogleGenAIStreamWrapper(completion_stream=iter([]))
+
+ # Manually set up the accumulated tool call to simulate what would happen during streaming
+ mock_wrapper.accumulated_tool_calls = {0: {"name": "test_function", "arguments": ""}}
+
+ # Create a mock response that has a finish_reason to trigger the final processing
+ mock_response_with_finish = ModelResponse(
+ id="test-streaming",
+ choices=[
+ StreamingChoices(
+ finish_reason="stop",
+ index=0,
+ delta=Delta(content=None, tool_calls=[])
+ )
+ ],
+ created=1234567890,
+ model="gpt-3.5-turbo",
+ object="chat.completion.chunk"
+ )
+
+ # Transform streaming chunk - this should process the accumulated tool call
+ streaming_chunk = adapter.translate_streaming_completion_to_generate_content(
+ mock_response_with_finish, mock_wrapper
+ )
+
+ # For empty content and tool calls with empty args, we might get None or a minimal response
+ # Let's check if we get a valid response with empty content
+ if streaming_chunk is not None:
+ assert "candidates" in streaming_chunk
+ candidate = streaming_chunk["candidates"][0]
+ assert "content" in candidate
+ parts = candidate["content"]["parts"]
+ # If there are parts, check if functionCall with empty args is properly handled
+ for part in parts:
+ if "functionCall" in part:
+ function_call = part["functionCall"]
+ assert function_call["name"] == "test_function"
+ assert function_call["args"] == {} # Empty args should become empty object
+ else:
+ # If streaming_chunk is None, it's acceptable as it might indicate no meaningful content
+ # This is a valid case in streaming where we might skip empty chunks
+ # The important thing is that no exception was raised
+ pass
+
+
+def test_tool_config_transformation():
+ """Test that toolConfig is correctly transformed to tool_choice"""
+ adapter = GoogleGenAIAdapter()
+
+ # Test different toolConfig modes
+ test_cases = [
+ # AUTO mode
+ {
+ "tool_config": {"functionCallingConfig": {"mode": "AUTO"}},
+ "expected_tool_choice": "auto"
+ },
+ # ANY mode - maps to "required" in OpenAI
+ {
+ "tool_config": {
+ "functionCallingConfig": {
+ "mode": "ANY"
+ }
+ },
+ "expected_tool_choice": "required"
+ },
+ # NONE mode
+ {
+ "tool_config": {"functionCallingConfig": {"mode": "NONE"}},
+ "expected_tool_choice": "none"
+ }
+ ]
+
+ for case in test_cases:
+ tool_config = case["tool_config"]
+ expected_tool_choice = case["expected_tool_choice"]
+
+ # Transform tool config
+ openai_tool_choice = adapter._transform_google_genai_tool_config_to_openai(tool_config)
+
+ # Verify transformation
+ assert openai_tool_choice == expected_tool_choice
+
+
+def test_stream_transformation_error_handling():
+ """Test that stream transformation errors are properly handled"""
+ from litellm.google_genai.adapters.transformation import (
+ GoogleGenAIStreamWrapper,
+ )
+
+ adapter = GoogleGenAIAdapter()
+
+ # Create a mock response that would cause transformation to fail
+ mock_response = ModelResponse(
+ id="test-streaming-error",
+ choices=[], # Empty choices which might cause issues
+ created=1234567890,
+ model="gpt-3.5-turbo",
+ object="chat.completion.chunk"
+ )
+
+ # Create a wrapper
+ mock_wrapper = GoogleGenAIStreamWrapper(completion_stream=iter([]))
+
+ # Try to transform - this should handle errors gracefully
+ try:
+ streaming_chunk = adapter.translate_streaming_completion_to_generate_content(
+ mock_response, mock_wrapper
+ )
+ # If no exception is raised, that's fine - we just want to ensure no crash
+ assert True
+ except Exception as e:
+ # If an exception is raised, it should be a ValueError with appropriate message
+ assert isinstance(e, ValueError)
+ # We won't check the exact message as it might vary
+
+
+def test_non_stream_response_when_stream_requested():
+ """Test handling of non-stream responses when streaming was requested"""
+ from litellm.types.utils import Choices
+
+ # Mock a non-stream response (ModelResponse with valid choices)
+ mock_response = ModelResponse(
+ id="test-123",
+ choices=[
+ Choices(
+ index=0,
+ message={
+ "role": "assistant",
+ "content": "Hello, world!"
+ },
+ finish_reason="stop"
+ )
+ ],
+ created=1234567890,
+ model="gpt-3.5-turbo",
+ object="chat.completion"
+ )
+
+ # Create an instance of the adapter
+ adapter = GoogleGenAIAdapter()
+
+ # Test the adapter's translate_completion_to_generate_content method directly
+ result = adapter.translate_completion_to_generate_content(mock_response)
+
+ # Verify the result is a valid Google GenAI format response
+ assert "candidates" in result
+ assert isinstance(result["candidates"], list)
+ assert len(result["candidates"]) > 0
+ candidate = result["candidates"][0]
+ assert "content" in candidate
+ assert "parts" in candidate["content"]
+ assert isinstance(candidate["content"]["parts"], list)
+ assert len(candidate["content"]["parts"]) > 0
+ assert "text" in candidate["content"]["parts"][0]
+ assert candidate["content"]["parts"][0]["text"] == "Hello, world!"
\ No newline at end of file
diff --git a/tests/test_litellm/google_genai/test_google_genai_handler.py b/tests/test_litellm/google_genai/test_google_genai_handler.py
new file mode 100644
index 00000000000..a199f086fe6
--- /dev/null
+++ b/tests/test_litellm/google_genai/test_google_genai_handler.py
@@ -0,0 +1,220 @@
+#!/usr/bin/env python3
+"""
+Test to verify the Google GenAI generate_content handler functionality
+"""
+import json
+import os
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../../..")
+) # Adds the parent directory to the system path
+
+import litellm
+from litellm.google_genai.adapters.handler import GenerateContentToCompletionHandler
+from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter
+from litellm.types.utils import ModelResponse
+
+
+def test_non_stream_response_when_stream_requested_sync():
+ """
+ Test that when a non-stream response is returned but streaming was requested,
+ the sync handler correctly transforms it to generate_content format.
+ """
+ from litellm.types.utils import Choices
+
+ # Mock a non-stream response (ModelResponse with valid choices)
+ mock_response = ModelResponse(
+ id="test-123",
+ choices=[
+ Choices(
+ index=0,
+ message={
+ "role": "assistant",
+ "content": "Hello, world!"
+ },
+ finish_reason="stop"
+ )
+ ],
+ created=1234567890,
+ model="gpt-3.5-turbo",
+ object="chat.completion"
+ )
+
+ # Create an instance of the adapter
+ adapter = GoogleGenAIAdapter()
+
+ # Test the adapter's translate_completion_to_generate_content method directly
+ result = adapter.translate_completion_to_generate_content(mock_response)
+
+ # Verify the result is a valid Google GenAI format response
+ assert "candidates" in result
+ assert isinstance(result["candidates"], list)
+ assert len(result["candidates"]) > 0
+ candidate = result["candidates"][0]
+ assert "content" in candidate
+ assert "parts" in candidate["content"]
+ assert isinstance(candidate["content"]["parts"], list)
+ assert len(candidate["content"]["parts"]) > 0
+ assert "text" in candidate["content"]["parts"][0]
+ assert candidate["content"]["parts"][0]["text"] == "Hello, world!"
+
+
+async def test_non_stream_response_when_stream_requested_async():
+ """
+ Test that when a non-stream response is returned but streaming was requested,
+ the async handler correctly transforms it to generate_content format.
+ """
+ from litellm.types.utils import Choices
+
+ # Mock a non-stream response (ModelResponse with valid choices)
+ mock_response = ModelResponse(
+ id="test-123",
+ choices=[
+ Choices(
+ index=0,
+ message={
+ "role": "assistant",
+ "content": "Hello, world!"
+ },
+ finish_reason="stop"
+ )
+ ],
+ created=1234567890,
+ model="gpt-3.5-turbo",
+ object="chat.completion"
+ )
+
+ # Create an instance of the adapter
+ adapter = GoogleGenAIAdapter()
+
+ # Test the adapter's translate_completion_to_generate_content method directly
+ result = adapter.translate_completion_to_generate_content(mock_response)
+
+ # Verify the result is a valid Google GenAI format response
+ assert "candidates" in result
+ assert isinstance(result["candidates"], list)
+ assert len(result["candidates"]) > 0
+ candidate = result["candidates"][0]
+ assert "content" in candidate
+ assert "parts" in candidate["content"]
+ assert isinstance(candidate["content"]["parts"], list)
+ assert len(candidate["content"]["parts"]) > 0
+ assert "text" in candidate["content"]["parts"][0]
+ assert candidate["content"]["parts"][0]["text"] == "Hello, world!"
+
+
+def test_stream_response_when_stream_requested_sync():
+ """
+ Test that when a stream response is returned and streaming was requested,
+ the sync handler correctly transforms it to generate_content streaming format.
+ """
+ # Mock a stream response
+ mock_stream = MagicMock()
+ mock_stream.__iter__ = MagicMock(return_value=iter([]))
+
+ # Mock the GoogleGenAIAdapter's translate_completion_output_params_streaming method
+ with patch.object(
+ GoogleGenAIAdapter,
+ "translate_completion_output_params_streaming",
+ return_value=mock_stream
+ ) as mock_translate:
+ with patch("litellm.completion", return_value=mock_stream):
+ # Call the handler with stream=True
+ result = GenerateContentToCompletionHandler.generate_content_handler(
+ model="gemini-pro",
+ contents=[{"role": "user", "parts": [{"text": "Hello"}]}],
+ litellm_params={}, # Empty dict for params
+ stream=True
+ )
+
+ # Verify that translate_completion_output_params_streaming was called
+ mock_translate.assert_called_once_with(mock_stream)
+ # Verify the result is the transformed stream
+ assert result == mock_stream
+
+
+async def test_stream_response_when_stream_requested_async():
+ """
+ Test that when a stream response is returned and streaming was requested,
+ the async handler correctly transforms it to generate_content streaming format.
+ """
+ # Mock a stream response
+ mock_stream = MagicMock()
+ mock_stream.__aiter__ = AsyncMock(return_value=iter([])) # Return an empty async iterator
+
+ # Mock the GoogleGenAIAdapter's translate_completion_output_params_streaming method
+ with patch.object(
+ GoogleGenAIAdapter,
+ "translate_completion_output_params_streaming",
+ return_value=mock_stream
+ ) as mock_translate:
+ with patch("litellm.acompletion", return_value=mock_stream):
+ # Call the handler with stream=True
+ result = await GenerateContentToCompletionHandler.async_generate_content_handler(
+ model="gemini-pro",
+ contents=[{"role": "user", "parts": [{"text": "Hello"}]}],
+ litellm_params={}, # Empty dict for params
+ stream=True
+ )
+
+ # Verify that translate_completion_output_params_streaming was called
+ mock_translate.assert_called_once_with(mock_stream)
+ # Verify the result is the transformed stream
+ assert result == mock_stream
+
+
+def test_stream_transformation_error_sync():
+ """
+ Test that when a stream transformation fails, the sync handler raises a ValueError.
+ """
+ # Mock a stream response
+ mock_stream = MagicMock()
+ mock_stream.__iter__ = MagicMock(return_value=iter([]))
+
+ # Mock the GoogleGenAIAdapter's translate_completion_output_params_streaming method to return None
+ with patch.object(
+ GoogleGenAIAdapter,
+ "translate_completion_output_params_streaming",
+ return_value=None
+ ):
+ with patch("litellm.completion", return_value=mock_stream):
+ # Call the handler with stream=True and expect a ValueError
+ with pytest.raises(ValueError, match="Failed to transform streaming response"):
+ GenerateContentToCompletionHandler.generate_content_handler(
+ model="gemini-pro",
+ contents=[{"role": "user", "parts": [{"text": "Hello"}]}],
+ litellm_params={}, # Empty dict for params
+ stream=True
+ )
+
+
+async def test_stream_transformation_error_async():
+ """
+ Test that when a stream transformation fails, the async handler raises a ValueError.
+ """
+ # Mock a stream response
+ mock_stream = MagicMock()
+ mock_stream.__aiter__ = AsyncMock(return_value=mock_stream)
+
+ # Mock the GoogleGenAIAdapter's translate_completion_output_params_streaming method to return None
+ with patch.object(
+ GoogleGenAIAdapter,
+ "translate_completion_output_params_streaming",
+ return_value=None
+ ):
+ with patch("litellm.acompletion", return_value=mock_stream):
+ # Call the handler with stream=True and expect a ValueError
+ with pytest.raises(ValueError, match="Failed to transform streaming response"):
+ await GenerateContentToCompletionHandler.async_generate_content_handler(
+ model="gemini-pro",
+ contents=[{"role": "user", "parts": [{"text": "Hello"}]}],
+ litellm_params={}, # Empty dict for params
+ stream=True
+ )
\ No newline at end of file
diff --git a/tests/test_litellm/proxy/google_endpoints/test_google_api_endpoints.py b/tests/test_litellm/proxy/google_endpoints/test_google_api_endpoints.py
new file mode 100644
index 00000000000..62e8aaf2794
--- /dev/null
+++ b/tests/test_litellm/proxy/google_endpoints/test_google_api_endpoints.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python3
+"""
+Test to verify the Google GenAI proxy API endpoints
+"""
+import asyncio
+import os
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+
+import litellm
+
+
+def test_google_generate_content_endpoint():
+ """Test that the google_generate_content endpoint correctly routes requests"""
+ # Skip this test if we can't import the required modules due to missing dependencies
+ try:
+ from fastapi.testclient import TestClient
+ from litellm.proxy.google_endpoints.endpoints import router as google_router
+ except ImportError as e:
+ pytest.skip(f"Skipping test due to missing dependency: {e}")
+
+ # Create a test client
+ client = TestClient(google_router)
+
+ # Mock the router's agenerate_content method
+ with patch("litellm.proxy.proxy_server.llm_router") as mock_router:
+ mock_router.agenerate_content = AsyncMock(return_value={"test": "response"})
+
+ # Send a request to the endpoint
+ response = client.post(
+ "/v1beta/models/test-model:generateContent",
+ json={
+ "contents": [{"role": "user", "parts": [{"text": "Hello"}]}]
+ }
+ )
+
+ # Verify the response
+ assert response.status_code == 200
+ assert response.json() == {"test": "response"}
+
+ # Verify that agenerate_content was called
+ mock_router.agenerate_content.assert_called_once()
+
+
+def test_google_stream_generate_content_endpoint():
+ """Test that the google_stream_generate_content endpoint correctly routes streaming requests"""
+ # Skip this test if we can't import the required modules due to missing dependencies
+ try:
+ from fastapi.testclient import TestClient
+ from litellm.proxy.google_endpoints.endpoints import router as google_router
+ except ImportError as e:
+ pytest.skip(f"Skipping test due to missing dependency: {e}")
+
+ # Create a test client
+ client = TestClient(google_router)
+
+ # Mock the router's agenerate_content method to return a stream
+ mock_stream = AsyncMock()
+ mock_stream.__aiter__ = lambda self: mock_stream
+ mock_stream.__anext__.side_effect = StopAsyncIteration
+
+ with patch("litellm.proxy.proxy_server.llm_router") as mock_router:
+ mock_router.agenerate_content = AsyncMock(return_value=mock_stream)
+
+ # Send a request to the endpoint
+ response = client.post(
+ "/v1beta/models/test-model:streamGenerateContent",
+ json={
+ "contents": [{"role": "user", "parts": [{"text": "Hello"}]}]
+ }
+ )
+
+ # Verify the response
+ assert response.status_code == 200
+
+ # Verify that agenerate_content was called with correct parameters
+ mock_router.agenerate_content.assert_called_once()
+ call_args = mock_router.agenerate_content.call_args
+ assert call_args[1]["stream"] is True
+ assert call_args[1]["model"] == "test-model"
+ assert call_args[1]["contents"] == [{"role": "user", "parts": [{"text": "Hello"}]}]
\ No newline at end of file
diff --git a/tests/test_litellm/test_router_google_genai.py b/tests/test_litellm/test_router_google_genai.py
new file mode 100644
index 00000000000..8b8d8a8379d
--- /dev/null
+++ b/tests/test_litellm/test_router_google_genai.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python3
+"""
+Test to verify the new Google GenAI router methods
+"""
+import asyncio
+import os
+import sys
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+
+import litellm
+from litellm.types.utils import ModelResponse
+
+
+async def test_router_agenerate_content_method():
+ """Test that the new agenerate_content method in Router works correctly"""
+ # Create a router instance
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "test-model",
+ "litellm_params": {
+ "model": "gpt-3.5-turbo",
+ }
+ }
+ ]
+ )
+
+ # Create a mock response in Google GenAI format
+ mock_response = {
+ "candidates": [
+ {
+ "content": {
+ "parts": [
+ {
+ "text": "Hello, world!"
+ }
+ ]
+ }
+ }
+ ]
+ }
+
+ # Mock the router's underlying agenerate_content method to return a mock response
+ with patch.object(router, 'agenerate_content', new=AsyncMock(return_value=mock_response)) as mock_agenerate_content:
+ # Call the agenerate_content method
+ response = await router.agenerate_content(
+ model="test-model",
+ contents=[{"role": "user", "parts": [{"text": "Hello"}]}]
+ )
+
+ # Verify that router.agenerate_content was called with correct parameters
+ mock_agenerate_content.assert_called_once()
+ call_args = mock_agenerate_content.call_args
+ assert call_args[1]["model"] == "test-model"
+ assert call_args[1]["contents"] == [{"role": "user", "parts": [{"text": "Hello"}]}]
+
+ # Verify that the response is the mock response we created
+ assert response == mock_response
+
+
+async def test_router_aadapter_generate_content_method():
+ """Test that the new aadapter_generate_content method in Router works correctly"""
+ # Create a router instance
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "test-model",
+ "litellm_params": {
+ "model": "gpt-3.5-turbo",
+ }
+ }
+ ]
+ )
+
+ # Create a mock response in Google GenAI format
+ mock_response = {
+ "candidates": [
+ {
+ "content": {
+ "parts": [
+ {
+ "text": "Hello, world!"
+ }
+ ]
+ }
+ }
+ ]
+ }
+
+ # Mock the router's underlying aadapter_generate_content method to return a mock response
+ with patch.object(router, 'aadapter_generate_content', new=AsyncMock(return_value=mock_response)) as mock_aadapter_generate_content:
+ # Call the aadapter_generate_content method
+ response = await router.aadapter_generate_content(
+ model="test-model",
+ contents=[{"role": "user", "parts": [{"text": "Hello"}]}]
+ )
+
+ # Verify that router.aadapter_generate_content was called with correct parameters
+ mock_aadapter_generate_content.assert_called_once()
+ call_args = mock_aadapter_generate_content.call_args
+ assert call_args[1]["model"] == "test-model"
+ assert call_args[1]["contents"] == [{"role": "user", "parts": [{"text": "Hello"}]}]
+
+ # Verify that the response is the mock response we created
+ assert response == mock_response
\ No newline at end of file