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]

fix(vertex_ai)!: send integer enums to Gemini instead of dropping them (#44908)

Max Azatian208cac49f051
diff --git a/litellm/llms/gemini/common_utils.py b/litellm/llms/gemini/common_utils.py
index b1a726be876..8ee7a463828 100644
--- a/litellm/llms/gemini/common_utils.py
+++ b/litellm/llms/gemini/common_utils.py
@@ -524,7 +524,7 @@ class GoogleAIStudioTokenCounter(BaseTokenCounter):
)
if isinstance(request_view, VertexGeminiCountContextError):
return count_context_error_response(request_view, request_model, model_to_use)
- count_context: Final = vertex_gemini_count_context(system=request_view.system, tools=tools)
+ count_context: Final = vertex_gemini_count_context(system=request_view.system, tools=tools, model=model_to_use)
if isinstance(count_context, VertexGeminiCountContextError):
return count_context_error_response(count_context, request_model, model_to_use)
blocks_error: Final = unconvertible_messages_error(
diff --git a/litellm/llms/gemini/google_genai/transformation.py b/litellm/llms/gemini/google_genai/transformation.py
index 196a19a141f..bc3180a2129 100644
--- a/litellm/llms/gemini/google_genai/transformation.py
+++ b/litellm/llms/gemini/google_genai/transformation.py
@@ -15,8 +15,9 @@ from litellm.llms.base_llm.google_genai.transformation import (
from litellm.llms.vertex_ai.common_utils import (
build_vertex_schema,
supports_response_json_schema,
+ with_integer_enums_that_fit,
)
-from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexLLM
+from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig, VertexLLM
from litellm.types.router import GenericLiteLLMParams
if TYPE_CHECKING:
@@ -327,8 +328,11 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM):
else:
if json_schema_key is not None:
generate_content_config_dict.pop(json_schema_key)
- generate_content_config_dict[schema_key] = build_vertex_schema(
- parameters=deepcopy(value), add_property_ordering=True
+ generate_content_config_dict[schema_key] = with_integer_enums_that_fit(
+ lambda send_integer_enums: build_vertex_schema(
+ parameters=deepcopy(value), add_property_ordering=True, send_integer_enums=send_integer_enums
+ ),
+ VertexGeminiConfig.is_gemini_3_or_newer(model),
)
def transform_generate_content_request(
diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py
index f85a5a8cda9..27f2aedb300 100644
--- a/litellm/llms/vertex_ai/common_utils.py
+++ b/litellm/llms/vertex_ai/common_utils.py
@@ -1,11 +1,12 @@
import re
-from collections.abc import Mapping, Sequence
+from collections.abc import Callable, Iterable, Mapping, Sequence
from copy import deepcopy
from datetime import datetime, timezone
from enum import Enum
from functools import lru_cache
+from itertools import accumulate, chain, repeat, takewhile
from types import MappingProxyType
-from typing import Any, Final, Literal, cast, get_type_hints
+from typing import Any, Final, Literal, TypeVar, cast, get_type_hints
import httpx
from pydantic import JsonValue, TypeAdapter, ValidationError
@@ -666,12 +667,89 @@ def _fix_enum_empty_strings(schema, depth=0):
_fix_enum_empty_strings(items, depth=depth + 1)
-def _fix_enum_types(schema, depth=0):
- """Remove `enum` fields when the schema type is not string.
+GEMINI_MAX_ENUM_CHARACTERS: Final = 2000
+_GEMINI_EXACT_INT_MAX: Final = 2**53 - 1
- Gemini / Vertex APIs only allow enums for string-typed fields. When an enum
- is present on a non-string typed property (or when `anyOf` types do not
- include a string type), remove the enum to avoid provider validation errors.
+
+def _gemini_integer_enum_value(value: object) -> str | None:
+ match value:
+ case bool():
+ return None
+ case int() if -_GEMINI_EXACT_INT_MAX <= value <= _GEMINI_EXACT_INT_MAX:
+ return str(int(value))
+ case str() if (
+ re.fullmatch(r"-?[0-9]{1,16}", value) and -_GEMINI_EXACT_INT_MAX <= int(value) <= _GEMINI_EXACT_INT_MAX
+ ):
+ return str(int(value))
+ case _:
+ return None
+
+
+def _gemini_integer_enum(values: Sequence[object]) -> tuple[str, ...] | None:
+ if not values:
+ return None
+ converted: Final = tuple(text for value in values if (text := _gemini_integer_enum_value(value)) is not None)
+ return converted if len(converted) == len(values) else None
+
+
+def _json_children(node: JsonValue) -> Iterable[JsonValue]:
+ match node:
+ case dict():
+ return node.values()
+ case list():
+ return node
+ case _:
+ return ()
+
+
+def _next_json_level(level: tuple[JsonValue, ...], _: None) -> tuple[JsonValue, ...]:
+ return tuple(chain.from_iterable(_json_children(node) for node in level))
+
+
+def _enum_size(node: JsonValue) -> tuple[bool, int] | None:
+ match node:
+ case {"enum": list() as values}:
+ return (str(node.get("type")).lower() == "integer", sum(len(str(value)) for value in values))
+ case _:
+ return None
+
+
+def _integer_enums_fit(schema: JsonValue) -> bool:
+ levels: Final = takewhile(bool, accumulate(repeat(None), _next_json_level, initial=(schema,)))
+ enum_sizes: Final = tuple(size for node in chain.from_iterable(levels) if (size := _enum_size(node)) is not None)
+ return (
+ not any(is_integer for is_integer, _ in enum_sizes)
+ or sum(characters for _, characters in enum_sizes) <= GEMINI_MAX_ENUM_CHARACTERS
+ )
+
+
+_GeminiRequestPart: Final = TypeVar("_GeminiRequestPart")
+
+
+def with_integer_enums_that_fit(
+ build: Callable[[bool], _GeminiRequestPart], send_integer_enums: bool
+) -> _GeminiRequestPart:
+ if not send_integer_enums:
+ return build(False)
+ with_integer_enums: Final = build(True)
+ if _integer_enums_fit(
+ cast(JsonValue, with_integer_enums) # cast-ok: built tools and schemas are JSON request data
+ ):
+ return with_integer_enums
+ verbose_logger.debug(
+ "Gemini integer enums dropped: the request's enum values exceed %s characters", GEMINI_MAX_ENUM_CHARACTERS
+ )
+ return build(False)
+
+
+def _fix_enum_types(schema, depth=0, send_integer_enums: bool = False):
+ """Make `enum` fields acceptable to Gemini / Vertex.
+
+ Gemini / Vertex APIs only accept string enum values. With `send_integer_enums`,
+ an integer enum of values a double holds exactly is sent as type INTEGER with the
+ values as strings; the model still returns an integer.
+ On any other non-string typed property (or when `anyOf` types do not include a
+ string type), the enum is removed to avoid provider validation errors.
"""
if depth > DEFAULT_MAX_RECURSE_DEPTH:
raise ValueError(f"Max depth of {DEFAULT_MAX_RECURSE_DEPTH} exceeded while processing schema.")
@@ -696,26 +774,37 @@ def _fix_enum_types(schema, depth=0):
break
if not keep_enum:
- schema.pop("enum", None)
+ is_integer_type: Final = isinstance(schema_type, str) and schema_type.lower() == "integer"
+ integer_enum: Final = (
+ _gemini_integer_enum(cast(Sequence[object], schema["enum"])) # cast-ok: an untyped JSON list
+ if send_integer_enums and is_integer_type
+ else None
+ )
+ if integer_enum is not None:
+ schema["enum"] = list(integer_enum) # rebind-ok: this function edits the schema in place by design
+ else:
+ schema.pop("enum", None)
# Recurse into nested structures
properties: Final = schema.get("properties", None)
if properties is not None:
for _, value in properties.items():
- _fix_enum_types(value, depth=depth + 1)
+ _fix_enum_types(value, depth=depth + 1, send_integer_enums=send_integer_enums)
items: Final = schema.get("items", None)
if items is not None:
- _fix_enum_types(items, depth=depth + 1)
+ _fix_enum_types(items, depth=depth + 1, send_integer_enums=send_integer_enums)
anyof = schema.get("anyOf", None)
if anyof is not None and isinstance(anyof, list):
for item in anyof:
if isinstance(item, dict):
- _fix_enum_types(item, depth=depth + 1)
+ _fix_enum_types(item, depth=depth + 1, send_integer_enums=send_integer_enums)
-def build_vertex_schema(parameters: dict, add_property_ordering: bool = False):
+def build_vertex_schema(
+ parameters: dict, add_property_ordering: bool = False, send_integer_enums: bool = False
+) -> dict[str, object]:
"""
This is a modified version of https://github.com/google-gemini/generative-ai-python/blob/8f77cc6ac99937cd3a81299ecf79608b91b06bbb/google/generativeai/types/content_types.py#L419
@@ -725,6 +814,7 @@ def build_vertex_schema(parameters: dict, add_property_ordering: bool = False):
parameters: dict - the json schema to build from
add_property_ordering: bool - whether to add propertyOrdering to the schema. This is only applicable to schemas for structured outputs. See
set_schema_property_ordering for more details.
+ send_integer_enums: bool - whether to send integer enums with string values instead of removing them
Returns:
parameters: dict - the input parameters, modified in place
"""
@@ -750,7 +840,7 @@ def build_vertex_schema(parameters: dict, add_property_ordering: bool = False):
_fix_enum_empty_strings(parameters)
# Remove enums for non-string typed fields (Gemini requires enum only on strings)
- _fix_enum_types(parameters)
+ _fix_enum_types(parameters, send_integer_enums=send_integer_enums)
# Handle empty items objects
process_items(parameters)
@@ -1068,6 +1158,17 @@ def _convert_schema_types(schema, depth=0):
if field in schema:
item_schema[field] = deepcopy(schema[field])
any_of.append(item_schema)
+ elif t == "integer" and "enum" in schema and isinstance(schema["enum"], list):
+ any_of.append(
+ {
+ "type": t,
+ "enum": [
+ value
+ for value in cast(list[object], schema["enum"]) # cast-ok: an untyped JSON list
+ if value is not None
+ ],
+ }
+ )
else:
# For primitive types, only include the type
any_of.append({"type": t})
@@ -1454,7 +1555,9 @@ class VertexAITokenCounter(BaseTokenCounter):
)
if isinstance(request_view, VertexGeminiCountContextError):
return count_context_error_response(request_view, request_model, model_to_use)
- count_context: Final = vertex_gemini_count_context(system=request_view.system, tools=tools)
+ count_context: Final = vertex_gemini_count_context(
+ system=request_view.system, tools=tools, model=model_to_use
+ )
if isinstance(count_context, VertexGeminiCountContextError):
return count_context_error_response(count_context, request_model, model_to_use)
blocks_error: Final = unconvertible_messages_error(
diff --git a/litellm/llms/vertex_ai/count_tokens/context.py b/litellm/llms/vertex_ai/count_tokens/context.py
index b13f72e96fe..2579e857bd9 100644
--- a/litellm/llms/vertex_ai/count_tokens/context.py
+++ b/litellm/llms/vertex_ai/count_tokens/context.py
@@ -78,6 +78,7 @@ def _is_function_tool(tool: Mapping[str, JsonValue]) -> bool:
def _map_function_tools(
tools: object | None,
+ model: str,
) -> tuple[Mapping[str, object], ...] | None | VertexGeminiCountContextError:
try:
tool_values: Final = _TOOLS.validate_python(tools or ())
@@ -89,15 +90,21 @@ def _map_function_tools(
if not all(_has_object_schema(tool) for tool in function_tools):
return _INVALID_TOOLS
+ from litellm.llms.vertex_ai.common_utils import with_integer_enums_that_fit
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig
chat_tools: Final = tuple(
chat_tool for tool in function_tools for chat_tool in chat_completion_tools_for(tool)
) # comprehension-ok: flattens each tool's translation
+ config: Final = VertexGeminiConfig()
try:
- mapped_tools: Final = VertexGeminiConfig().map_function(
- value=[dict(tool) for tool in chat_tools],
- optional_params={},
+ mapped_tools: Final = with_integer_enums_that_fit(
+ lambda send_integer_enums: config.map_function(
+ value=[dict(tool) for tool in chat_tools],
+ optional_params={},
+ send_integer_enums=send_integer_enums,
+ ),
+ VertexGeminiConfig.is_gemini_3_or_newer(model),
)
except (AttributeError, TypeError, ValueError):
return _INVALID_TOOLS
@@ -110,11 +117,12 @@ def _map_function_tools(
def vertex_gemini_count_context(
system: object | None,
tools: object | None,
+ model: str,
) -> VertexGeminiCountContext | VertexGeminiCountContextError:
system_parts: Final = _system_parts(system)
if isinstance(system_parts, VertexGeminiCountContextError):
return system_parts
- function_tools: Final = _map_function_tools(tools)
+ function_tools: Final = _map_function_tools(tools, model)
if isinstance(function_tools, VertexGeminiCountContextError):
return function_tools
return VertexGeminiCountContext(
diff --git a/litellm/llms/vertex_ai/files/transformation.py b/litellm/llms/vertex_ai/files/transformation.py
index 396acd270fa..ea71e5fef50 100644
--- a/litellm/llms/vertex_ai/files/transformation.py
+++ b/litellm/llms/vertex_ai/files/transformation.py
@@ -1118,6 +1118,7 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig):
non_default_params=openai_request_body,
optional_params={},
drop_params=False,
+ allow_integer_enums=False,
)
return vertex_params
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index 114b9cd80ae..ec40cdfd11f 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -95,6 +95,7 @@ from ..common_utils import (
build_json_schema,
build_vertex_schema,
supports_response_json_schema,
+ with_integer_enums_that_fit,
)
from ..context_caching.known_cached_contents import known_cached_contents
from ..context_caching.rejected_cache_retry import (
@@ -692,13 +693,14 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
return googleSearch, googleSearchRetrieval, enterpriseWebSearch, urlContext
- def _map_function(self, value: list[dict], optional_params: dict) -> list[Tools]:
+ def _map_function(self, value: list[dict], optional_params: dict, send_integer_enums: bool = False) -> list[Tools]:
"""
Map OpenAI-style tools/functions to Vertex AI format.
Args:
value: List of tool definitions
optional_params: Request-scoped parameters to store retrieval config
+ send_integer_enums: Whether to send integer enums with string values
Returns:
List of mapped tools in Vertex AI format
@@ -711,18 +713,18 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
googleSearch: dict | None = None
googleSearchRetrieval: dict | None = None
enterpriseWebSearch: dict | None = None
- urlContext: dict | None = None
+ urlContext: dict[str, object] | None = None
code_execution: dict | None = None
googleMaps: dict | None = None
google_maps_retrieval_config: dict | None = None
computerUse: dict | None = None
# remove 'additionalProperties' from tools
- schema_value: Final[JsonValue] = cast(JsonValue, value) # cast-ok: tool schemas come from JSON request data
+ schema_value: Final[JsonValue] = deepcopy(cast(JsonValue, value)) # cast-ok: tools are JSON request data
remove_additional_properties(schema_value)
# remove 'strict' from tools
remove_strict_from_schema(schema_value)
- for tool in value:
+ for tool in cast(list[dict], schema_value): # cast-ok: a deep copy keeps the caller's tool shape
openai_function_object: ChatCompletionToolParamFunctionChunk | None = None
if "function" in tool: # tools list
_openai_function_object = ChatCompletionToolParamFunctionChunk(**tool["function"])
@@ -732,7 +734,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
and _openai_function_object["parameters"] is not None
and isinstance(_openai_function_object["parameters"], dict)
): # OPENAI accepts JSON Schema, Google accepts OpenAPI schema.
- _openai_function_object["parameters"] = build_vertex_schema(_openai_function_object["parameters"])
+ _openai_function_object["parameters"] = build_vertex_schema(
+ _openai_function_object["parameters"], send_integer_enums=send_integer_enums
+ )
openai_function_object = _openai_function_object
@@ -875,21 +879,28 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
self,
value: list[dict[str, object]], # mutable-ok: mirrors override contract
optional_params: dict[str, object], # mutable-ok: mirrors override contract
+ send_integer_enums: bool = False,
) -> list[Tools]: # mutable-ok: mirrors override contract
- return self._map_function(value, optional_params)
+ return self._map_function(value, optional_params, send_integer_enums)
- def _map_response_schema(self, value: dict) -> dict:
+ def _map_response_schema(self, value: dict, send_integer_enums: bool = False) -> Mapping[str, object]:
old_schema = deepcopy(value)
if isinstance(old_schema, list):
for item in old_schema:
if isinstance(item, dict):
- item = build_vertex_schema(parameters=item, add_property_ordering=True)
+ item = build_vertex_schema(
+ parameters=item, add_property_ordering=True, send_integer_enums=send_integer_enums
+ )
elif isinstance(old_schema, dict):
- old_schema = build_vertex_schema(parameters=old_schema, add_property_ordering=True)
+ old_schema = build_vertex_schema(
+ parameters=old_schema, add_property_ordering=True, send_integer_enums=send_integer_enums
+ )
return old_schema
- def apply_response_schema_transformation(self, value: dict, optional_params: dict, model: str):
+ def apply_response_schema_transformation(
+ self, value: dict, optional_params: dict, model: str, allow_integer_enums: bool = True
+ ):
new_value = deepcopy(value)
# remove 'strict' from json schema (not supported by Gemini)
new_value = remove_strict_from_schema(new_value)
@@ -931,7 +942,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
# - OpenAPI-style format (uppercase types)
# - No additionalProperties support
# - Requires propertyOrdering
- optional_params["response_schema"] = self._map_response_schema(value=schema)
+ optional_params["response_schema"] = with_integer_enums_that_fit(
+ partial(self._map_response_schema, schema),
+ allow_integer_enums and self._is_gemini_3_or_newer(model),
+ )
@property
def accepts_reasoning_summary_in_reasoning_effort(self) -> bool:
@@ -1249,6 +1263,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
optional_params: dict,
model: str,
drop_params: bool,
+ allow_integer_enums: bool = True,
) -> dict:
self._apply_include_server_side_tool_invocations(non_default_params, optional_params)
gemini_sampling_params_warned: bool = False
@@ -1299,7 +1314,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
elif param == "max_tokens" or param == "max_completion_tokens":
optional_params["max_output_tokens"] = value
elif param == "response_format" and isinstance(value, dict):
- self.apply_response_schema_transformation(value=value, optional_params=optional_params, model=model)
+ self.apply_response_schema_transformation(
+ value=value, optional_params=optional_params, model=model, allow_integer_enums=allow_integer_enums
+ )
elif param == "frequency_penalty":
if self._supports_penalty_parameters(model):
optional_params["frequency_penalty"] = value
@@ -1312,7 +1329,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
optional_params["logprobs"] = value
elif (param == "tools" or param == "functions") and isinstance(value, list) and value:
# Pass optional_params so _map_function can add toolConfig if needed
- mapped_tools = self._map_function(value=value, optional_params=optional_params)
+ mapped_tools = with_integer_enums_that_fit(
+ partial(self._map_function, value, optional_params),
+ allow_integer_enums and self._is_gemini_3_or_newer(model),
+ )
optional_params = self._add_tools_to_optional_params(optional_params, mapped_tools)
elif param == "tool_choice" and (isinstance(value, str) or isinstance(value, dict)):
_tool_choice_value = self.map_tool_choice_values(
diff --git a/tests/integration/providers/test_gemini_anyof_null_branches_wire.py b/tests/integration/providers/test_gemini_anyof_null_branches_wire.py
index 9fa99cb69f8..79820ac2efb 100644
--- a/tests/integration/providers/test_gemini_anyof_null_branches_wire.py
+++ b/tests/integration/providers/test_gemini_anyof_null_branches_wire.py
@@ -360,8 +360,9 @@ def test_a_repeated_identical_request_sends_the_same_folded_union_each_time(gate
model: Final = _deployment(gateway, scenario, wire, "vertex_ai")
description: Final = _description()
path, body = _request_body("chat", model, description, _parameters({"anyOf": [_NULL, _NULL, _STRING]}), False)
- first: Final = gateway.request("POST", path, body)
- second: Final = gateway.request("POST", path, body)
+ uncached: Final[dict[str, JsonValue]] = {**body, "cache": {"no-cache": True}}
+ first: Final = gateway.request("POST", path, uncached)
+ second: Final = gateway.request("POST", path, uncached)
_assert_caller_saw_ok("chat", first, False)
_assert_caller_saw_ok("chat", second, False)
assert _json(first)["id"] != _json(second)["id"]
diff --git a/tests/unit/llms/gemini/google_genai/test_google_genai_transformation.py b/tests/unit/llms/gemini/google_genai/test_google_genai_transformation.py
index b4c654ee175..da8ab138416 100644
--- a/tests/unit/llms/gemini/google_genai/test_google_genai_transformation.py
+++ b/tests/unit/llms/gemini/google_genai/test_google_genai_transformation.py
@@ -9,6 +9,7 @@ from respx import MockRouter
import litellm
from litellm.google_genai import agenerate_content_stream
from litellm.llms.gemini.google_genai.transformation import GoogleGenAIConfig
+from litellm.llms.vertex_ai.common_utils import GEMINI_MAX_ENUM_CHARACTERS
_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
_PROMPT: Final = "Hello, can you tell me a short joke?"
@@ -239,3 +240,43 @@ async def test_generate_content_stream_parses_function_call(
},
)
assert _JSON_OBJECT.validate_json(route.calls.last.request.content)["tools"] == tools
+
+
+ ("model", "expected_level"),
+ [
+ ("gemini-flash-latest", {"type": "integer", "enum": ["1", "2", "5"]}),
+ ("gemini-1.5-pro", {"type": "integer"}),
+ ],
+)
+def test_normalize_response_schema_sends_integer_enums_to_gemini_3(
+ model: str, expected_level: dict[str, object]
+) -> None:
+ config_dict: Final = {
+ "responseSchema": {"type": "object", "properties": {"level": {"type": "integer", "enum": [1, 2, 5]}}}
+ }
+
+ GoogleGenAIConfig._normalize_response_schema(config_dict, model)
+
+ assert config_dict["responseSchema"]["properties"]["level"] == expected_level
+
+
+ ("value_count", "integer_enum_sent"),
+ [(GEMINI_MAX_ENUM_CHARACTERS // 10, True), (GEMINI_MAX_ENUM_CHARACTERS // 10 + 1, False)],
+)
+def test_normalize_response_schema_drops_integer_enums_past_the_enum_budget(
+ value_count: int, integer_enum_sent: bool
+) -> None:
+ values: Final = [10**9 + n for n in range(value_count)]
+ config_dict: Final = {
+ "responseSchema": {"type": "object", "properties": {"level": {"type": "integer", "enum": values}}}
+ }
+
+ GoogleGenAIConfig._normalize_response_schema(config_dict, "gemini-flash-latest")
+
+ assert config_dict["responseSchema"]["properties"]["level"] == (
+ {"type": "integer", "enum": [str(value) for value in values]}
+ if integer_enum_sent
+ else {"type": "integer"}
+ )
diff --git a/tests/unit/llms/vertex_ai/count_tokens/test_context.py b/tests/unit/llms/vertex_ai/count_tokens/test_context.py
index 405b7234c81..948f66ab84d 100644
--- a/tests/unit/llms/vertex_ai/count_tokens/test_context.py
+++ b/tests/unit/llms/vertex_ai/count_tokens/test_context.py
@@ -73,7 +73,7 @@ _FUNCTION_DECLARATION: Final = {
ids=("anthropic", "openai-chat", "responses"),
)
def test_function_tool_shapes_map_to_vertex_declarations(tool: JsonValue) -> None:
- context: Final = vertex_gemini_count_context(system=None, tools=[tool])
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash", system=None, tools=[tool])
assert isinstance(context, VertexGeminiCountContext)
assert context.tools == (_FUNCTION_DECLARATION,)
@@ -82,7 +82,7 @@ def test_function_tool_shapes_map_to_vertex_declarations(tool: JsonValue) -> Non
def test_long_anthropic_tool_name_is_truncated_for_vertex() -> None:
name: Final = "mcp__docs__" + "a" * 70
- context: Final = vertex_gemini_count_context(
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash",
system=None,
tools=[{"name": name, "description": "Look up a value", "input_schema": _SCHEMA}],
)
@@ -104,7 +104,7 @@ def test_long_anthropic_tool_name_is_truncated_for_vertex() -> None:
def test_64_character_anthropic_tool_name_is_unchanged_for_vertex() -> None:
name: Final = "mcp__docs__" + "a" * 53
- context: Final = vertex_gemini_count_context(
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash",
system=None,
tools=[{"name": name, "input_schema": _SCHEMA}],
)
@@ -115,7 +115,7 @@ def test_64_character_anthropic_tool_name_is_unchanged_for_vertex() -> None:
def test_long_openai_chat_tool_name_is_unchanged_for_vertex() -> None:
name: Final = "mcp__docs__" + "a" * 70
- context: Final = vertex_gemini_count_context(
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash",
system=None,
tools=[{"type": "function", "function": {"name": name, "parameters": _SCHEMA}}],
)
@@ -125,7 +125,7 @@ def test_long_openai_chat_tool_name_is_unchanged_for_vertex() -> None:
def test_unknown_tools_are_omitted() -> None:
- context: Final = vertex_gemini_count_context(
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash",
system=None,
tools=[{"type": "web_search_preview"}, {"type": "computer_use"}],
)
@@ -135,7 +135,7 @@ def test_unknown_tools_are_omitted() -> None:
def test_text_block_system_instruction_keeps_one_part_per_block() -> None:
- context: Final = vertex_gemini_count_context(
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash",
system=[{"type": "text", "text": "First instruction."}, {"type": "text", "text": "Second instruction."}],
tools=None,
)
@@ -145,14 +145,14 @@ def test_text_block_system_instruction_keeps_one_part_per_block() -> None:
def test_string_system_instruction_maps_to_one_part() -> None:
- context: Final = vertex_gemini_count_context(system="Follow this instruction.", tools=None)
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash", system="Follow this instruction.", tools=None)
assert isinstance(context, VertexGeminiCountContext)
assert context.system_instruction == {"parts": ({"text": "Follow this instruction."},)}
def test_non_text_system_block_returns_an_error_value() -> None:
- context: Final = vertex_gemini_count_context(
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash",
system=[{"type": "image", "source": {"type": "base64", "data": "AAAA"}}],
tools=None,
)
@@ -163,7 +163,7 @@ def test_non_text_system_block_returns_an_error_value() -> None:
@pytest.mark.parametrize(("system", "tools"), ((None, None), ("", None), ([], [])))
def test_empty_context_is_omitted(system: JsonValue | None, tools: JsonValue | None) -> None:
- context: Final = vertex_gemini_count_context(system=system, tools=tools)
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash", system=system, tools=tools)
assert isinstance(context, VertexGeminiCountContext)
assert context.system_instruction is None
@@ -185,7 +185,7 @@ def test_anthropic_tools_count_the_same_declarations_inference_sends(tool: dict[
optional_params={},
)
- context: Final = vertex_gemini_count_context(system=None, tools=[tool])
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash", system=None, tools=[tool])
assert isinstance(context, VertexGeminiCountContext)
assert context.tools is not None
@@ -194,6 +194,33 @@ def test_anthropic_tools_count_the_same_declarations_inference_sends(tool: dict[
]
[email protected]("model", ("gemini-3.8-flash", "gemini-2.5-flash"))
[email protected]("ids", (range(3), range(10**12, 10**12 + 200)), ids=("small-enum", "past-enum-budget"))
+def test_count_context_counts_the_integer_enums_inference_sends(model: str, ids: range) -> None:
+ tool: Final = {
+ "type": "function",
+ "function": {
+ "name": "open_record",
+ "parameters": {
+ "type": "object",
+ "properties": {"record_id": {"type": "integer", "enum": list(ids)}},
+ "required": ["record_id"],
+ },
+ },
+ }
+ inference_params: Final = VertexGeminiConfig().map_openai_params(
+ non_default_params={"tools": [tool]}, optional_params={}, model=model, drop_params=False
+ )
+
+ context: Final = vertex_gemini_count_context(model=model, system=None, tools=[tool])
+
+ assert isinstance(context, VertexGeminiCountContext)
+ assert context.tools is not None
+ assert [tool_value["functionDeclarations"] for tool_value in context.tools] == [
+ inference_tool["function_declarations"] for inference_tool in inference_params["tools"]
+ ]
+
+
@pytest.mark.parametrize(
"tools",
(
@@ -206,7 +233,7 @@ def test_anthropic_tools_count_the_same_declarations_inference_sends(tool: dict[
ids=("not-a-list", "non-object-tool", "string-schema", "list-parameters", "malformed-property"),
)
def test_invalid_tools_return_an_error_value(tools: JsonValue) -> None:
- context: Final = vertex_gemini_count_context(system=None, tools=tools)
+ context: Final = vertex_gemini_count_context(model="gemini-2.5-flash", system=None, tools=tools)
assert isinstance(context, VertexGeminiCountContextError)
assert "tools" in context.error_message
diff --git a/tests/unit/llms/vertex_ai/files/test_vertex_ai_files_transformation.py b/tests/unit/llms/vertex_ai/files/test_vertex_ai_files_transformation.py
index dde3df6fcc0..dc1e762e752 100644
--- a/tests/unit/llms/vertex_ai/files/test_vertex_ai_files_transformation.py
+++ b/tests/unit/llms/vertex_ai/files/test_vertex_ai_files_transformation.py
@@ -6,6 +6,7 @@ Includes tests for Vertex AI batch output transformation to OpenAI format.
import json
import urllib.parse
from collections.abc import Mapping
+from typing import Final
from types import MappingProxyType
from urllib.parse import parse_qs, urlparse
@@ -1638,6 +1639,45 @@ class TestVertexResponsesBatchInputTranslation:
assert request["contents"] == [{"role": "user", "parts": [{"text": "ping"}]}]
+_PRIORITY_SCHEMA: Final = {
+ "type": "object",
+ "properties": {
+ "level": {"type": "integer", "enum": [1, 2, 5]},
+ "mode": {"type": "string", "enum": ["fast", "slow"]},
+ },
+}
+
+
+class TestVertexBatchIntegerEnums:
+ """
+ Vertex batch reads each row's string enum values back as numbers and then fails the
+ row, so batch rows drop integer enums on every model, as before Gemini 3 sent them.
+ """
+
+ @pytest.mark.parametrize("model", ["gemini-3.8-flash", "vertex-batch-alias"])
+ def test_tool_rows_drop_integer_enums_and_keep_string_enums(self, model: str):
+ (row,) = _wrap_entries(
+ [
+ {
+ "custom_id": "enum-1",
+ "method": "POST",
+ "url": "/v1/chat/completions",
+ "body": {
+ "model": model,
+ "messages": [{"role": "user", "content": "Set priority 3"}],
+ "tools": [
+ {"type": "function", "function": {"name": "set_priority", "parameters": _PRIORITY_SCHEMA}}
+ ],
+ },
+ }
+ ]
+ )
+
+ properties: Final = row["request"]["tools"][0]["function_declarations"][0]["parameters"]["properties"]
+ assert "enum" not in properties["level"]
+ assert properties["mode"]["enum"] == ["fast", "slow"]
+
+
class TestVertexEmbeddingsBatchOutputTranslation:
"""Vertex Gemini Embedding batch output rows must come back as OpenAI batch rows."""
diff --git a/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
index 5c0e9f1a305..636d4034ccc 100644
--- a/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
+++ b/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
@@ -17,7 +17,7 @@ from litellm.litellm_core_utils.exception_mapping_utils import exception_type
from litellm.llms.anthropic.pass_through.messages import handler as anthropic_messages_handler
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
from litellm.llms.gemini.chat.transformation import GoogleAIStudioGeminiConfig
-from litellm.llms.vertex_ai.common_utils import VertexAIError
+from litellm.llms.vertex_ai.common_utils import GEMINI_MAX_ENUM_CHARACTERS, VertexAIError
from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
VertexGeminiConfig,
@@ -2120,6 +2120,207 @@ def test_gemini_reasoning_effort_and_function_tool_share_request() -> None:
]
+ ("model", "expected_level"),
+ [
+ ("gemini-3.8-flash", {"type": "integer", "enum": ["1", "2", "5"]}),
+ ("gemini-2.5-flash", {"type": "integer"}),
+ ],
+)
+def test_gemini_tool_mapping_sends_integer_enums_to_gemini_3_and_keeps_caller_tools(
+ model: str, expected_level: dict[str, object]
+) -> None:
+ tools: Final = [
+ {
+ "type": "function",
+ "function": {
+ "name": "set_priority",
+ "strict": True,
+ "parameters": {
+ "type": "object",
+ "properties": {"level": {"type": "integer", "enum": [1, 2, 5]}},
+ "required": ["level"],
+ "additionalProperties": False,
+ },
+ },
+ }
+ ]
+ caller_tools: Final = deepcopy(tools)
+
+ request_params: Final = VertexGeminiConfig().map_openai_params(
+ non_default_params={"tools": tools},
+ optional_params={},
+ model=model,
+ drop_params=False,
+ )
+
+ sent_level: Final = request_params["tools"][0]["function_declarations"][0]["parameters"]["properties"]["level"]
+ assert sent_level == expected_level
+ assert tools == caller_tools
+
+
+ ("model", "expected_level"),
+ [
+ ("gemini-flash-latest", {"type": "integer", "enum": ["1", "2", "5"]}),
+ ("gemini-1.5-pro", {"type": "integer"}),
+ ],
+)
+def test_gemini_response_schema_sends_integer_enums_to_gemini_3(model: str, expected_level: dict[str, object]) -> None:
+ response_format: Final = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "task",
+ "schema": {
+ "type": "object",
+ "properties": {"level": {"type": "integer", "enum": [1, 2, 5]}},
+ "required": ["level"],
+ },
+ },
+ }
+
+ request_params: Final = VertexGeminiConfig().map_openai_params(
+ non_default_params={"response_format": response_format},
+ optional_params={},
+ model=model,
+ drop_params=False,
+ )
+
+ assert request_params["response_schema"]["properties"]["level"] == expected_level
+
+
+def test_gemini_mapping_drops_integer_enums_when_the_caller_disallows_them() -> None:
+ level_schema: Final = {"type": "object", "properties": {"level": {"type": "integer", "enum": [1, 2, 5]}}}
+
+ request_params: Final = VertexGeminiConfig().map_openai_params(
+ non_default_params={
+ "tools": [{"type": "function", "function": {"name": "set_priority", "parameters": level_schema}}],
+ "response_format": {"type": "json_schema", "json_schema": {"name": "task", "schema": level_schema}},
+ },
+ optional_params={},
+ model="gemini-flash-latest",
+ drop_params=False,
+ allow_integer_enums=False,
+ )
+
+ assert request_params["tools"][0]["function_declarations"][0]["parameters"]["properties"]["level"] == {
+ "type": "integer"
+ }
+ assert request_params["response_schema"]["properties"]["level"] == {"type": "integer"}
+
+
+_TEN_DIGIT_VALUES_IN_BUDGET: Final = GEMINI_MAX_ENUM_CHARACTERS // 10
+
+
+def _ten_digit_integer_enum_tool(name: str, value_count: int) -> dict[str, object]:
+ return {
+ "type": "function",
+ "function": {
+ "name": name,
+ "parameters": {
+ "type": "object",
+ "properties": {"level": {"type": "integer", "enum": [10**9 + n for n in range(value_count)]}},
+ "required": ["level"],
+ },
+ },
+ }
+
+
+ ("value_counts", "integer_enums_sent"),
+ [
+ ((_TEN_DIGIT_VALUES_IN_BUDGET,), True),
+ ((_TEN_DIGIT_VALUES_IN_BUDGET + 1,), False),
+ ((_TEN_DIGIT_VALUES_IN_BUDGET // 2, _TEN_DIGIT_VALUES_IN_BUDGET - _TEN_DIGIT_VALUES_IN_BUDGET // 2), True),
+ ((_TEN_DIGIT_VALUES_IN_BUDGET // 2, _TEN_DIGIT_VALUES_IN_BUDGET - _TEN_DIGIT_VALUES_IN_BUDGET // 2 + 1), False),
+ ],
+ ids=["one-tool-at-budget", "one-tool-over-budget", "two-tools-at-budget", "two-tools-over-budget"],
+)
+def test_gemini_tool_mapping_drops_every_integer_enum_when_the_request_exceeds_the_enum_budget(
+ value_counts: tuple[int, ...], integer_enums_sent: bool
+) -> None:
+ request_params: Final = VertexGeminiConfig().map_openai_params(
+ non_default_params={
+ "tools": [_ten_digit_integer_enum_tool(f"tool_{i}", count) for i, count in enumerate(value_counts)]
+ },
+ optional_params={},
+ model="gemini-3.8-flash",
+ drop_params=False,
+ )
+
+ sent_levels: Final = [
+ declaration["parameters"]["properties"]["level"]
+ for declaration in request_params["tools"][0]["function_declarations"]
+ ]
+ assert sent_levels == [
+ (
+ {"type": "integer", "enum": [str(10**9 + n) for n in range(count)]}
+ if integer_enums_sent
+ else {"type": "integer"}
+ )
+ for count in value_counts
+ ]
+
+
+def test_gemini_tool_mapping_counts_string_enums_toward_the_enum_budget() -> None:
+ names: Final = [f"name{n:06d}" for n in range(GEMINI_MAX_ENUM_CHARACTERS // 10)]
+ tool: Final = {
+ "type": "function",
+ "function": {
+ "name": "set_priority",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "enum": names},
+ "level": {"type": "integer", "enum": [1, 2, 5]},
+ },
+ },
+ },
+ }
+
+ request_params: Final = VertexGeminiConfig().map_openai_params(
+ non_default_params={"tools": [tool]}, optional_params={}, model="gemini-3.8-flash", drop_params=False
+ )
+
+ sent_properties: Final = request_params["tools"][0]["function_declarations"][0]["parameters"]["properties"]
+ assert sent_properties["level"] == {"type": "integer"}
+ assert sent_properties["name"]["enum"] == names
+
+
+ ("value_count", "expected_level"),
+ [
+ (
+ _TEN_DIGIT_VALUES_IN_BUDGET,
+ {"type": "integer", "enum": [str(10**9 + n) for n in range(_TEN_DIGIT_VALUES_IN_BUDGET)]},
+ ),
+ (_TEN_DIGIT_VALUES_IN_BUDGET + 1, {"type": "integer"}),
+ ],
+)
+def test_gemini_response_schema_drops_integer_enums_past_the_enum_budget(
+ value_count: int, expected_level: dict[str, object]
+) -> None:
+ response_format: Final = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "task",
+ "schema": {
+ "type": "object",
+ "properties": {"level": {"type": "integer", "enum": [10**9 + n for n in range(value_count)]}},
+ },
+ },
+ }
+
+ request_params: Final = VertexGeminiConfig().map_openai_params(
+ non_default_params={"response_format": response_format},
+ optional_params={},
+ model="gemini-flash-latest",
+ drop_params=False,
+ )
+
+ assert request_params["response_schema"]["properties"]["level"] == expected_level
+
+
def test_vertex_ai_transform_parts():
"""
Test the _transform_parts method for converting Vertex AI function calls
diff --git a/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py b/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py
index 38737df7545..152ab2ffc13 100644
--- a/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py
+++ b/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py
@@ -2,6 +2,7 @@ import copy
import time
from collections.abc import Iterator
from contextlib import contextmanager
+from enum import Enum
from typing import Final
from unittest.mock import AsyncMock, patch
@@ -15,6 +16,7 @@ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.llms.gemini.count_tokens import handler as gemini_count_tokens_handler
from litellm.llms.vertex_ai.common_utils import (
VertexAITokenCounter,
+ _fix_enum_types,
build_vertex_schema,
convert_anyof_null_to_nullable,
convert_vertex_datetime_to_openai_datetime,
@@ -1407,12 +1409,11 @@ def test_construct_target_url_versionless_project_route_gets_api_version(
def test_fix_enum_types():
"""
- Test _fix_enum_types function removes enum fields when type is not string.
+ Test _fix_enum_types keeps string enums, converts integer enums to the form
+ Gemini accepts, and removes enums on other non-string types.
- This test verifies the fix for the issue where Gemini rejects cached content
- with function parameter enums on non-string types, causing API failures.
-
- Relevant issue: Gemini only allows enums for string-typed fields
+ Gemini rejects non-string enum values, causing API failures. Integer enums are
+ sent as type INTEGER with string values.
"""
from litellm.llms.vertex_ai.common_utils import _fix_enum_types
@@ -1426,7 +1427,7 @@ def test_fix_enum_types():
"description": "How to truncate content",
},
"maxLength": {
- "enum": [100, 200, 500], # This should be removed
+ "enum": [100, 200, 500],
"type": "integer",
"description": "Maximum length",
},
@@ -1443,7 +1444,7 @@ def test_fix_enum_types():
"type": "string",
},
"innerNonStringEnum": {
- "enum": [1, 2, 3], # This should be removed
+ "enum": [1, 2, 3],
"type": "integer",
},
},
@@ -1454,13 +1455,13 @@ def test_fix_enum_types():
"type": "string",
"enum": ["option1", "option2"],
}, # This should be kept
- {"type": "integer", "enum": [1, 2, 3]}, # This should be removed
+ {"type": "integer", "enum": [1, 2, 3]},
]
},
},
}
- # Expected output: Non-string enums removed, string enums kept
+ # Expected output: string enums kept, integer enums converted, others removed
expected_output = {
"type": "object",
"properties": {
@@ -1469,7 +1470,8 @@ def test_fix_enum_types():
"type": "string",
"description": "How to truncate content",
},
- "maxLength": { # enum removed
+ "maxLength": {
+ "enum": ["100", "200", "500"],
"type": "integer",
"description": "Maximum length",
},
@@ -1484,7 +1486,10 @@ def test_fix_enum_types():
"enum": ["a", "b", "c"], # Kept - string type
"type": "string",
},
- "innerNonStringEnum": {"type": "integer"}, # enum removed
+ "innerNonStringEnum": {
+ "enum": ["1", "2", "3"],
+ "type": "integer",
+ },
},
},
"anyOfField": {
@@ -1493,14 +1498,14 @@ def test_fix_enum_types():
"type": "string",
"enum": ["option1", "option2"],
}, # Kept - has string type
- {"type": "integer"}, # enum removed
+ {"type": "integer", "enum": ["1", "2", "3"]},
]
},
},
}
# Apply the transformation
- _fix_enum_types(input_schema)
+ _fix_enum_types(input_schema, send_integer_enums=True)
# Verify the transformation
assert input_schema == expected_output
@@ -1522,20 +1527,135 @@ def test_fix_enum_types():
"c",
]
- # 2. Non-string enums are removed
- assert "enum" not in input_schema["properties"]["maxLength"]
+ # 2. Integer enums are converted, other non-string enums are removed
+ assert input_schema["properties"]["maxLength"]["enum"] == ["100", "200", "500"]
assert "enum" not in input_schema["properties"]["enabled"]
- assert "enum" not in input_schema["properties"]["nested"]["properties"]["innerNonStringEnum"]
+ assert input_schema["properties"]["nested"]["properties"]["innerNonStringEnum"]["enum"] == ["1", "2", "3"]
- # 3. anyOf with string type keeps enum, non-string removes it
+ # 3. anyOf keeps the string enum and converts the integer one
assert "enum" in input_schema["properties"]["anyOfField"]["anyOf"][0]
- assert "enum" not in input_schema["properties"]["anyOfField"]["anyOf"][1]
+ assert input_schema["properties"]["anyOfField"]["anyOf"][1]["enum"] == ["1", "2", "3"]
# 4. Other properties preserved
assert input_schema["properties"]["maxLength"]["type"] == "integer"
assert input_schema["properties"]["enabled"]["type"] == "boolean"
+
+def test_build_vertex_schema_sends_integer_enum_as_string_values():
+ """An integer enum tool parameter reaches Gemini as INTEGER with string values and no enum format."""
+ from litellm.llms.vertex_ai.common_utils import _build_vertex_schema
+
+ parameters = {
+ "type": "object",
+ "properties": {
+ "level": {"type": "integer", "enum": [1, 2, 5]},
+ "flag": {"type": "boolean", "enum": [True]},
+ },
+ "required": ["level"],
+ }
+
+ result = _build_vertex_schema(parameters, send_integer_enums=True)
+
+ assert "format" not in result["properties"]["level"]
+ assert result["properties"]["level"]["enum"] == ["1", "2", "5"]
+ assert result["properties"]["level"]["type"].lower() == "integer"
+ assert "enum" not in result["properties"]["flag"]
+
+
+ ("enum_values", "send_integer_enums", "expected_level"),
+ [
+ (
+ [1, 2, 5],
+ True,
+ {"anyOf": [{"type": "integer", "enum": ["1", "2", "5"], "nullable": True}]},
+ ),
+ (
+ [1, 2, 5, None],
+ True,
+ {"anyOf": [{"type": "integer", "enum": ["1", "2", "5"], "nullable": True}]},
+ ),
+ ([1, 2, 5], False, {"anyOf": [{"type": "integer", "nullable": True}]}),
+ ([1, "a"], True, {"anyOf": [{"type": "integer", "nullable": True}]}),
+ ],
+ ids=["sent", "null-in-enum", "not-sent", "mixed-values"],
+)
+def test_build_vertex_schema_keeps_integer_enum_on_nullable_type_list(
+ enum_values: list[object], send_integer_enums: bool, expected_level: JsonValue
+) -> None:
+ schema: Final = build_vertex_schema(
+ {"type": "object", "properties": {"level": {"type": ["integer", "null"], "enum": enum_values}}},
+ send_integer_enums=send_integer_enums,
+ )
+
+ assert schema["properties"]["level"] == expected_level
+
+
+def test_map_function_keeps_integer_enum_when_tools_are_reused():
+ from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig
+
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "set_priority",
+ "parameters": {
+ "type": "object",
+ "properties": {"level": {"type": "integer", "enum": [1, 2, 5]}},
+ "required": ["level"],
+ },
+ },
+ }
+ ]
+ config = VertexGeminiConfig()
+
+ sent = [
+ config._map_function(tools, {}, send_integer_enums=True)[0]["function_declarations"][0]["parameters"][
+ "properties"
+ ]["level"]
+ for _ in range(2)
+ ]
+
+ assert sent[0]["enum"] == ["1", "2", "5"]
+ assert sent[1]["enum"] == ["1", "2", "5"]
+ assert sent[0] == sent[1]
+
+
+class _Priority(int, Enum):
+ LOW = 1
+ HIGH = 3
+
+
+ ("enum_values", "send_integer_enums", "expected_enum"),
+ [
+ ([1, 2, 5], False, None),
+ (["-3", "007", 4], True, ["-3", "7", "4"]),
+ ([1, 2**53], True, None),
+ ([1, -(2**53)], True, None),
+ (["1", str(2**53)], True, None),
+ ([-(2**53 - 1), 2**53 - 1], True, [str(-(2**53 - 1)), str(2**53 - 1)]),
+ ([str(-(2**53 - 1)), str(2**53 - 1)], True, [str(-(2**53 - 1)), str(2**53 - 1)]),
+ (["1", "9" * 5000], True, None),
+ (["1", "--2"], True, None),
+ (["1", "\u00b2"], True, None),
+ ([True, 1], True, None),
+ ([1.5, 2], True, None),
+ ([], True, None),
+ ([_Priority.LOW, _Priority.HIGH], True, ["1", "3"]),
+ ],
+)
+def test_fix_enum_types_sends_only_integer_enums_gemini_accepts(
+ enum_values: list[object], send_integer_enums: bool, expected_enum: list[str] | None
+) -> None:
+ schema: Final = {"type": "integer", "enum": enum_values}
+
+ _fix_enum_types(schema, send_integer_enums=send_integer_enums)
+
+ assert schema.get("enum") == expected_enum
+ assert "format" not in schema
+
def test_get_token_url():
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
VertexLLM,