fix(vertex_ai): pin const values on Gemini tool and response schemas (#53413)

* fix(vertex_ai): pin const values on Gemini tool and response schemas as one-value enums

* fix(vertex_ai): keep a const its declared type cannot hold out of the Gemini enum

A property like {"type": "string", "const": 7} allows no value. Sent as enum [7] it made Vertex and the Gemini API answer 400, where the merge base answered 200, so such a const keeps today's behavior

* fix(vertex_ai): keep const pins for type lists, unions and whole floats, and skip empty strings

* fix(vertex_ai): drop union branches that cannot hold the const beside them

* fix(vertex_ai): copy a union branch before adding the const so a dict the schema reuses keeps its value

* fix(vertex_ai): send consts unpinned once a request's enums pass Gemini's enum budget

Gemini answers 400 once a request's one-value enums pass its enum size limit,
so const pins are kept only while every enum in the request, pins included,
fits GEMINI_MAX_ENUM_CHARACTERS. Pins are dropped before integer enums, the
public map_function is budgeted too, integer consts outside the exact range
stay as sent, and JSON-schema builders now pin an empty-string const.

* fix(vertex_ai): count const pins against one enum budget per request and skip the pin pass without a const

* fix(vertex_ai): count the enum budget in bytes, keep pins out of $ref and conflicting const branches, and end walks on schemas that contain themselves

* fix(vertex_ai): stop counting enum bytes once the request is over Gemini's enum budget

* fix(vertex_ai): walk schemas depth first so the const and enum checks keep memory flat on a wide, deep schema

* fix(vertex_ai): keep map_function a plain forwarder so a subclass that overrides _map_function still runs

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
This commit is contained in:
edvinsqandmateo-berri authored and GitHub committed 2026-11-22 18:27:58 +00:00
1 parent a4597077e1
commit 151a6392de
8 files changed
+966 -68

No files matched your search

@@ -6,6 +6,7 @@ from copy import deepcopy
from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, cast
import httpx
from pydantic import JsonValue
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
@@ -14,8 +15,9 @@ from litellm.llms.base_llm.google_genai.transformation import (
)
from litellm.llms.vertex_ai.common_utils import (
build_vertex_schema,
has_const,
supports_response_json_schema,
with_integer_enums_that_fit,
with_enums_that_fit,
)
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig, VertexLLM
from litellm.types.router import GenericLiteLLMParams
@@ -336,11 +338,15 @@ 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] = 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
generate_content_config_dict[schema_key] = with_enums_that_fit(
lambda send_integer_enums, pin_consts: build_vertex_schema(
parameters=deepcopy(value),
add_property_ordering=True,
send_integer_enums=send_integer_enums,
pin_consts=pin_consts,
),
VertexGeminiConfig.is_gemini_3_or_newer(model),
has_const(cast(JsonValue, value)), # cast-ok: response schemas are JSON request data
)
def transform_generate_content_request(
+205 -29
View File
@@ -1,11 +1,11 @@
import math
import re
from collections.abc import Callable, Iterable, Mapping, Sequence
from collections.abc import Callable, Iterable, Iterator, 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 functools import lru_cache, partial
from itertools import accumulate, chain, starmap
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, Literal, TypeVar, cast, get_type_hints
@@ -731,7 +731,7 @@ def _fix_enum_empty_strings(schema, depth=0):
_fix_enum_empty_strings(items, depth=depth + 1)
GEMINI_MAX_ENUM_CHARACTERS: Final = 2000
GEMINI_MAX_ENUM_BYTES: Final = 2000
_GEMINI_EXACT_INT_MAX: Final = 2**53 - 1
@@ -766,25 +766,47 @@ def _json_children(node: JsonValue) -> Iterable[JsonValue]:
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:
def _enum_bytes(node: JsonValue) -> int:
match node:
case {"enum": list() as values}:
return (str(node.get("type")).lower() == "integer", sum(len(str(value)) for value in values))
return sum(len(str(value).encode()) for value in values)
case _:
return None
return 0
def _is_integer_enum(node: JsonValue) -> bool:
match node:
case {"enum": list()}:
return str(node.get("type")).lower() == "integer"
case _:
return False
def _json_nodes(schema: JsonValue) -> Iterator[JsonValue]:
on_path: Final = {id(schema)}
frames: Final = [(schema, iter(_json_children(schema)))]
yield schema
while frames:
node, children = frames[-1]
if (child := next((c for c in children if isinstance(c, (dict, list)) and id(c) not in on_path), None)) is None:
frames.pop()
on_path.discard(id(node))
continue
yield child
on_path.add(id(child))
frames.append((child, iter(_json_children(child))))
def has_const(schema: JsonValue) -> bool:
return any(isinstance(node, dict) and "const" in node for node in _json_nodes(schema))
def enums_fit(request_parts: JsonValue) -> bool:
return all(total <= GEMINI_MAX_ENUM_BYTES for total in accumulate(map(_enum_bytes, _json_nodes(request_parts))))
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
)
return enums_fit(schema) or not any(map(_is_integer_enum, _json_nodes(schema)))
_GeminiRequestPart: Final = TypeVar("_GeminiRequestPart")
@@ -801,11 +823,31 @@ def with_integer_enums_that_fit(
):
return with_integer_enums
verbose_logger.debug(
"Gemini integer enums dropped: the request's enum values exceed %s characters", GEMINI_MAX_ENUM_CHARACTERS
"Gemini integer enums dropped: the request's enum values exceed %s bytes", GEMINI_MAX_ENUM_BYTES
)
return build(False)
def with_pins_that_fit(build: Callable[[bool], _GeminiRequestPart], pin_consts: bool) -> _GeminiRequestPart:
if not pin_consts:
return build(False)
pinned: Final = build(True)
if enums_fit(cast(JsonValue, pinned)): # cast-ok: built tools and schemas are JSON
return pinned
verbose_logger.debug(
"Gemini consts sent unpinned: the request's enum values exceed %s bytes", GEMINI_MAX_ENUM_BYTES
)
return build(False)
def with_enums_that_fit(
build: Callable[[bool, bool], _GeminiRequestPart], send_integer_enums: bool, pin_consts: bool
) -> _GeminiRequestPart:
return with_integer_enums_that_fit(
lambda integer_enums: with_pins_that_fit(partial(build, integer_enums), pin_consts), send_integer_enums
)
def _fix_enum_types(schema, depth=0, send_integer_enums: bool = False):
"""Make `enum` fields acceptable to Gemini / Vertex.
@@ -866,8 +908,124 @@ def _fix_enum_types(schema, depth=0, send_integer_enums: bool = False):
_fix_enum_types(item, depth=depth + 1, send_integer_enums=send_integer_enums)
_MAP_SCHEMA_KEYWORDS: Final = frozenset({"properties", "$defs", "definitions", "patternProperties"})
_SINGLE_SCHEMA_KEYWORDS: Final = frozenset({"items", "additionalProperties", "not", "contains"})
_LIST_SCHEMA_KEYWORDS: Final = frozenset({"items", "anyOf", "oneOf", "allOf", "prefixItems"})
def _pinnable_type_of(value: JsonValue) -> Literal["boolean", "integer", "number", "string"] | None:
match value:
case bool():
return "boolean"
case int() if -_GEMINI_EXACT_INT_MAX <= value <= _GEMINI_EXACT_INT_MAX:
return "integer"
case float():
return "number"
case str():
return "string"
case _:
return None
_TYPES_HOLDING: Final = MappingProxyType(
{
"boolean": frozenset({"boolean"}),
"integer": frozenset({"integer", "number"}),
"number": frozenset({"number"}),
"string": frozenset({"string"}),
}
)
def _declared_type_holds(
declared_type: JsonValue, json_type: Literal["boolean", "integer", "number", "string"]
) -> bool:
match declared_type:
case None:
return True
case str():
return declared_type.lower() in _TYPES_HOLDING[json_type]
case list():
return any(isinstance(item, str) and item.lower() in _TYPES_HOLDING[json_type] for item in declared_type)
case _:
return False
def _subschemas(keyword: str, value: JsonValue) -> Iterable[JsonValue]:
match value:
case dict() if keyword in _MAP_SCHEMA_KEYWORDS:
return value.values()
case dict() if keyword in _SINGLE_SCHEMA_KEYWORDS:
return (value,)
case list() if keyword in _LIST_SCHEMA_KEYWORDS:
return value
case _:
return ()
def _const_as_declared(value: JsonValue, declared_type: JsonValue) -> JsonValue:
match value:
case float() if value.is_integer() and not _declared_type_holds(declared_type, "number"):
return int(value)
case _:
return value
def _branch_holds(branch: JsonValue, const: JsonValue) -> bool:
if not isinstance(branch, dict):
return True
if "$ref" in branch or ("const" in branch and branch["const"] != const):
return False
declared_type: Final = branch.get("type")
json_type: Final = _pinnable_type_of(_const_as_declared(const, declared_type))
return json_type is not None and _declared_type_holds(declared_type, json_type)
def _union_keyword(schema: Mapping[str, JsonValue]) -> Literal["anyOf", "oneOf"]:
return "anyOf" if "anyOf" in schema else "oneOf"
def _push_const_into_branches(schema: JsonValue) -> None:
if not isinstance(schema, dict) or _pinnable_type_of(schema.get("const")) is None:
return
keyword: Final = _union_keyword(schema)
branches: Final = schema.get(keyword)
if not isinstance(branches, list):
return
const: Final = schema["const"]
holding: Final = tuple(branch for branch in branches if _branch_holds(branch, const))
if not holding:
return
del schema["const"] # rebind-ok: the schema builders edit their own copy in place
schema[keyword] = [ # rebind-ok: the schema builders edit their own copy in place
{**branch, "const": const} if isinstance(branch, dict) else branch for branch in holding
]
def _pin_scalar_consts(schema: JsonValue, *, pins_empty_string: bool, depth: int = 0) -> None:
if depth > DEFAULT_MAX_RECURSE_DEPTH or not isinstance(schema, dict):
return
_push_const_into_branches(schema)
declared_type: Final = schema.get("type")
const: Final = _const_as_declared(schema.get("const"), declared_type)
unresolved: Final = _is_union(schema) or "$ref" in schema
unpinned_empty_string: Final = const == "" and not pins_empty_string
json_type: Final = None if unresolved or unpinned_empty_string else _pinnable_type_of(const)
if json_type is not None and _declared_type_holds(declared_type, json_type):
del schema["const"] # rebind-ok: the schema builders edit their own copy in place
schema["enum"] = [const] # rebind-ok: the schema builders edit their own copy in place
schema["type"] = declared_type if isinstance(declared_type, str) else json_type # rebind-ok: same copy
if unpinned_empty_string and declared_type is None and not unresolved:
schema["type"] = "string" # rebind-ok: the schema builders edit their own copy in place
for subschema in chain.from_iterable(starmap(_subschemas, schema.items())):
_pin_scalar_consts(subschema, pins_empty_string=pins_empty_string, depth=depth + 1)
def build_vertex_schema(
parameters: dict, add_property_ordering: bool = False, send_integer_enums: bool = False
parameters: dict,
add_property_ordering: bool = False,
send_integer_enums: bool = False,
pin_consts: bool = True,
) -> 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
@@ -879,6 +1037,7 @@ def build_vertex_schema(
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
pin_consts: bool - whether to send each scalar `const` as a one-value enum, since Gemini ignores `const`
Returns:
parameters: dict - the input parameters, modified in place
"""
@@ -891,6 +1050,11 @@ def build_vertex_schema(
# with circular references (see issue #19098). unpack_defs handles nested
# refs recursively and correctly detects/skips circular references.
unpack_defs(parameters, defs)
if pin_consts:
_pin_scalar_consts(
cast(JsonValue, parameters), # cast-ok: tool and response schemas are JSON request data
pins_empty_string=False,
)
_convert_schema_types(parameters)
@@ -1001,7 +1165,9 @@ def _forces(function_calling_config: JsonValue, name: JsonValue) -> bool:
def _vertex_parameters(json_schema: Mapping[str, JsonValue], send_integer_enums: bool) -> Mapping[str, JsonValue]:
stripped: Final = remove_strict_from_schema(remove_additional_properties(deepcopy(dict(json_schema))))
return _JSON_SCHEMA.validate_python(build_vertex_schema(stripped, send_integer_enums=send_integer_enums))
return _JSON_SCHEMA.validate_python(
build_vertex_schema(stripped, send_integer_enums=send_integer_enums, pin_consts=False)
)
def _declaration_for(declaration: JsonValue, function_calling_config: JsonValue, send_integer_enums: bool) -> JsonValue:
@@ -1042,14 +1208,21 @@ def with_forced_bare_root_unions_on_parameters(
return tools
def parameters_json_schema_for(parameters: Mapping[str, object]) -> Mapping[str, JsonValue] | None:
def parameters_json_schema_for(
parameters: Mapping[str, object], pin_consts: bool = True
) -> Mapping[str, JsonValue] | None:
if "$ref" not in parameters and not _root_cannot_be_vertex_parameters(parameters):
return None
json_schema: Final = _JSON_SCHEMA.validate_python(to_jsonable_python(parameters))
return json_schema if needs_parameters_json_schema(json_schema) else None
if not needs_parameters_json_schema(json_schema):
return None
pinned: Final = dict(json_schema)
if pin_consts:
_pin_scalar_consts(pinned, pins_empty_string=True)
return pinned
def build_json_schema(parameters: dict) -> dict:
def build_json_schema(parameters: Mapping[str, object], pin_consts: bool = True) -> dict[str, object]:
"""
Build a JSON Schema for use with Gemini's responseJsonSchema parameter.
@@ -1060,19 +1233,22 @@ def build_json_schema(parameters: dict) -> dict:
- Preserves $defs/$ref (Gemini 2.0+ supports JSON Schema references natively)
Parameters:
parameters: dict - the JSON schema to process
parameters: Mapping - the JSON schema to process, left unchanged
Returns:
dict - the processed schema in standard JSON Schema format
"""
# Gemini 2.0+ with responseJsonSchema accepts standard JSON Schema as-is,
# including $ref, $defs, anyOf, etc. No transformations needed — the
# OpenAPI-specific fixes (unpack_defs, add_object_type, convert_anyof, etc.)
# The OpenAPI-specific fixes (unpack_defs, add_object_type, convert_anyof, etc.)
# are only required for responseSchema (Gemini 1.5) and can break valid
# JSON Schema by adding conflicting fields to $ref nodes.
# See: https://blog.google/technology/developers/gemini-api-structured-outputs/
return parameters
schema: Final = deepcopy(dict(parameters))
if pin_consts:
_pin_scalar_consts(
cast(JsonValue, schema), # cast-ok: response schemas are JSON request data
pins_empty_string=True,
)
return schema
_build_json_schema = build_json_schema
@@ -117,10 +117,13 @@ from ..common_utils import (
VertexAIError,
build_json_schema,
build_vertex_schema,
enums_fit,
has_bare_root_union,
has_const,
parameters_json_schema_for,
supports_response_json_schema,
with_integer_enums_that_fit,
with_enums_that_fit,
with_pins_that_fit,
)
from ..context_caching.known_cached_contents import known_cached_contents
from ..context_caching.rejected_cache_retry import (
@@ -376,6 +379,7 @@ _GEMINI_SPEECH_CONFIG_KEY_MAP: Final[Mapping[str, str]] = MappingProxyType(
_SPEECH_CONFIG_ITEMS: Final = TypeAdapter(list[object])
_CALLER_HEADERS: Final = TypeAdapter(dict[str, str])
_REQUEST_PARAMS: Final = TypeAdapter(dict[str, object])
def _normalize_gemini_speech_config_item(value: Mapping[str, object]) -> Mapping[str, object]:
@@ -678,19 +682,24 @@ def _caller_parameters(tool: object) -> Mapping[str, object] | None:
return caller_tool.get("function", caller_tool).get("parameters")
def _parameters_json_schema(tool: object, forced_function_names: frozenset[str]) -> Mapping[str, JsonValue] | None:
def _parameters_json_schema(
tool: object, forced_function_names: frozenset[str], pin_consts: bool
) -> Mapping[str, JsonValue] | None:
parameters: Final = _caller_parameters(tool)
json_schema: Final = None if parameters is None else parameters_json_schema_for(parameters)
json_schema: Final = None if parameters is None else parameters_json_schema_for(parameters, pin_consts)
if json_schema is None or declared_function_name(tool) not in forced_function_names:
return json_schema
return None if has_bare_root_union(json_schema) else json_schema
def _parameters_json_schemas(
tools: object, allow_parameters_json_schema: bool, forced_function_names: frozenset[str]
tools: object,
allow_parameters_json_schema: bool,
forced_function_names: frozenset[str],
pin_consts: bool,
) -> tuple[Mapping[str, JsonValue] | None, ...]:
return tuple(
_parameters_json_schema(tool, forced_function_names) if allow_parameters_json_schema else None
_parameters_json_schema(tool, forced_function_names, pin_consts) if allow_parameters_json_schema else None
for tool in _CALLER_TOOLS.validate_python(tools)
)
@@ -1375,10 +1384,33 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
return googleSearch, googleSearchRetrieval, enterpriseWebSearch, urlContext
def _map_function(
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,
allow_parameters_json_schema: bool = True,
outside_declarations: JsonValue = None,
tool_choice: object = None,
) -> list[Tools]: # mutable-ok: mirrors override contract
return with_pins_that_fit(
partial(
self._build_function_tools,
value,
optional_params,
send_integer_enums,
allow_parameters_json_schema=allow_parameters_json_schema,
outside_declarations=outside_declarations,
tool_choice=tool_choice,
),
has_const(cast(JsonValue, value)), # cast-ok: tools are JSON request data
)
def _build_function_tools(
self,
value: list[dict],
optional_params: dict,
send_integer_enums: bool = False,
pin_consts: bool = True,
allow_parameters_json_schema: bool = True,
outside_declarations: JsonValue = None,
tool_choice: object = None,
@@ -1390,6 +1422,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
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
pin_consts: Whether to send each scalar `const` as a one-value enum
allow_parameters_json_schema: Whether a tool whose parameters root Vertex cannot take as `parameters`
goes as `parametersJsonSchema`
@@ -1415,6 +1448,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
_with_namespace_members_inlined(schema_value, outside_declarations),
allow_parameters_json_schema,
_function_names_forced_by(tool_choice, [*_listed(schema_value), *_listed(outside_declarations)]),
pin_consts,
)
remove_additional_properties(schema_value)
# remove 'strict' from tools
@@ -1434,7 +1468,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
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"], send_integer_enums=send_integer_enums
_openai_function_object["parameters"],
send_integer_enums=send_integer_enums,
pin_consts=pin_consts,
)
openai_function_object = _openai_function_object
@@ -1587,23 +1623,39 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
) -> list[Tools]: # mutable-ok: mirrors override contract
return self._map_function(value, optional_params, send_integer_enums, allow_parameters_json_schema)
def _map_response_schema(self, value: dict, send_integer_enums: bool = False) -> Mapping[str, object]:
def _map_response_schema(
self,
value: dict,
send_integer_enums: bool = False,
pin_consts: bool = True,
) -> 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, send_integer_enums=send_integer_enums
parameters=item,
add_property_ordering=True,
send_integer_enums=send_integer_enums,
pin_consts=pin_consts,
)
elif isinstance(old_schema, dict):
old_schema = build_vertex_schema(
parameters=old_schema, add_property_ordering=True, send_integer_enums=send_integer_enums
parameters=old_schema,
add_property_ordering=True,
send_integer_enums=send_integer_enums,
pin_consts=pin_consts,
)
return old_schema
def apply_response_schema_transformation(
self, value: dict, optional_params: dict, model: str, allow_integer_enums: bool = True
self,
value: dict,
optional_params: dict,
model: str,
allow_integer_enums: bool = True,
pin_consts: bool = True,
):
new_value = deepcopy(value)
# remove 'strict' from json schema (not supported by Gemini)
@@ -1640,15 +1692,20 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
# - Standard JSON Schema format (lowercase types)
# - Supports additionalProperties
# - No propertyOrdering needed
optional_params["response_json_schema"] = build_json_schema(deepcopy(schema))
json_schema: Final[Mapping[str, object]] = schema
optional_params["response_json_schema"] = with_pins_that_fit(
partial(build_json_schema, json_schema),
pin_consts and has_const(cast(JsonValue, schema)), # cast-ok: response schemas are JSON
)
else:
# Use responseSchema (default, backwards compatible)
# - OpenAPI-style format (uppercase types)
# - No additionalProperties support
# - Requires propertyOrdering
optional_params["response_schema"] = with_integer_enums_that_fit(
optional_params["response_schema"] = with_enums_that_fit(
partial(self._map_response_schema, schema),
allow_integer_enums and self._is_gemini_3_or_newer(model),
pin_consts and has_const(cast(JsonValue, schema)), # cast-ok: response schemas are JSON
)
@property
@@ -2042,6 +2099,54 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
)
return {"includeThoughts": VertexGeminiConfig._include_thoughts(thinking_config.get("includeThoughts"))}
def _tools_builder(
self,
param: str,
request_params: Mapping[str, object],
optional_params: dict[str, object], # mutable-ok: _map_function adds toolConfig to the request's params
allow_parameters_json_schema: bool,
) -> Callable[[bool, bool], Sequence[Tools]]:
return partial(
self._build_function_tools,
cast(list[dict], request_params[param]), # cast-ok: the caller checked it is a non-empty tools list
optional_params,
allow_parameters_json_schema=allow_parameters_json_schema,
outside_declarations=cast( # cast-ok: tools are JSON request data
JsonValue, request_params.get("functions" if param == "tools" else "tools")
),
tool_choice=_TOOL_CHOICE_PARAM.validate_python(request_params).get("tool_choice"),
)
def _schema_pins_fit(
self,
request_params: Mapping[str, object],
model: str,
allow_integer_enums: bool,
allow_parameters_json_schema: bool,
) -> bool:
tool_params: Final = tuple(
param
for param in ("tools", "functions")
if isinstance(listed := request_params.get(param), list) and listed
)
response_format: Final = request_params.get("response_format")
schema_parts: Final = [request_params.get(param) for param in (*tool_params, "response_format")]
if not tool_params or not isinstance(response_format, dict):
return True
if not has_const(cast(JsonValue, schema_parts)): # cast-ok: tools and response formats are JSON request data
return True
response_params: Final[dict[str, object]] = {} # mutable-ok: the transformation writes the schema into it
self.apply_response_schema_transformation(response_format, response_params, model, allow_integer_enums)
tools: Final = [
with_enums_that_fit(
self._tools_builder(param, request_params, {}, allow_parameters_json_schema),
allow_integer_enums and self._is_gemini_3_or_newer(model),
has_const(cast(JsonValue, request_params[param])), # cast-ok: tools are JSON request data
)
for param in tool_params
]
return enums_fit(cast(JsonValue, [response_params, tools])) # cast-ok: built tools and schemas are JSON
def map_openai_params(
self,
non_default_params: dict,
@@ -2059,6 +2164,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
self._apply_include_server_side_tool_invocations(request_params, optional_params)
supports_sampling_params: Final = self.supports_sampling_params(model)
drops_logprobs: Final = self._drops_logprobs(model, drop_params, allowed_openai_params)
typed_request_params: Final = _REQUEST_PARAMS.validate_python(request_params)
pins_fit: Final = self._schema_pins_fit(
typed_request_params, model, allow_integer_enums, allow_parameters_json_schema
)
for param, value in request_params.items():
if param in ("temperature", "top_p", "top_k") and not supports_sampling_params:
continue
@@ -2098,7 +2207,11 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
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, allow_integer_enums=allow_integer_enums
value=value,
optional_params=optional_params,
model=model,
allow_integer_enums=allow_integer_enums,
pin_consts=pins_fit,
)
elif param == "frequency_penalty":
if self._supports_penalty_parameters(model):
@@ -2112,18 +2225,12 @@ 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 = with_integer_enums_that_fit(
partial(
self._map_function,
value,
optional_params,
allow_parameters_json_schema=allow_parameters_json_schema,
outside_declarations=request_params.get("functions" if param == "tools" else "tools"),
tool_choice=_TOOL_CHOICE_PARAM.validate_python(request_params).get("tool_choice"),
),
mapped_tools = with_enums_that_fit(
self._tools_builder(param, typed_request_params, optional_params, allow_parameters_json_schema),
allow_integer_enums and self._is_gemini_3_or_newer(model),
pins_fit and has_const(cast(JsonValue, value)), # cast-ok: tools are JSON request data
)
optional_params = self._add_tools_to_optional_params(optional_params, mapped_tools)
optional_params = self._add_tools_to_optional_params(optional_params, list(mapped_tools))
elif param == "tool_choice" and (isinstance(value, str) or isinstance(value, dict)):
_tool_choice_value = self.map_tool_choice_values(
model=model,
@@ -46,6 +46,7 @@ IGNORE_FUNCTIONS = [
"_contains_vision_content", # max depth set.
"_read_all_bytes", # max depth set.
"_fix_enum_types", # max depth set.
"_pin_scalar_consts", # max depth set (DEFAULT_MAX_RECURSE_DEPTH); leaves the subtree past the cap untouched.
"_collect_argument_paths", # max depth set.
"_split_text", # max depth set.
"_mask_sequence", # max depth set.
@@ -9,7 +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
from litellm.llms.vertex_ai.common_utils import GEMINI_MAX_ENUM_BYTES
_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
_PROMPT: Final = "Hello, can you tell me a short joke?"
@@ -283,7 +283,7 @@ def test_normalize_response_schema_sends_integer_enums_to_gemini_3(
@pytest.mark.parametrize(
("value_count", "integer_enum_sent"),
[(GEMINI_MAX_ENUM_CHARACTERS // 10, True), (GEMINI_MAX_ENUM_CHARACTERS // 10 + 1, False)],
[(GEMINI_MAX_ENUM_BYTES // 10, True), (GEMINI_MAX_ENUM_BYTES // 10 + 1, False)],
)
def test_normalize_response_schema_drops_integer_enums_past_the_enum_budget(
value_count: int, integer_enum_sent: bool
@@ -2667,6 +2667,23 @@ def test_a_json_schema_row_with_defs_holds_no_key_bigquery_refuses() -> None:
] == {"type": "object", "properties": {"capital": city, "largest": city}, "required": ["capital", "largest"]}
def test_a_json_schema_row_builds_with_a_const_beside_a_union_whose_branch_is_a_ref() -> None:
schema: Final = {
"type": "object",
"properties": {"source": {"anyOf": [{"$ref": "#/$defs/Ledger"}, {"type": "null"}], "const": "ledger-7"}},
"$defs": {"Ledger": {"type": "string", "enum": ["ledger-7", "ledger-9"]}},
}
(row,) = _wrap_entries(
[
_chat_entry(
"gemini-2.5-flash",
{"response_format": {"type": "json_schema", "json_schema": {"name": "a", "schema": schema}}},
)
]
)
assert not any("$" in key for key in _keys_anywhere(row))
_GEMINI_DEPLOYMENT: Final = MappingProxyType({"gcs_bucket_name": "my-bucket", "model": "vertex_ai/gemini-2.5-flash"})
_ANNOTATED_ANSWER_SCHEMA: Final = MappingProxyType(
{
@@ -26,7 +26,7 @@ from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_toke
from litellm.llms.anthropic.messages.native 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 GEMINI_MAX_ENUM_CHARACTERS, VertexAIError
from litellm.llms.vertex_ai.common_utils import GEMINI_MAX_ENUM_BYTES, VertexAIError
from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (
OPENAI_TO_GEMINI_TTS_VOICES,
@@ -3529,6 +3529,271 @@ def test_vertex_keeps_a_union_root_tool_on_parameters_when_the_call_can_be_force
assert weather == {"name": "weather", "parameters": _WEATHER_VERTEX_PARAMETERS}
@pytest.mark.parametrize(
("model", "kind_schema", "expected_kind"),
[
("gemini-2.5-flash", {"const": "card"}, {"type": "string", "enum": ["card"]}),
("gemini-2.5-flash", {"const": "ledger-7", "type": "string"}, {"type": "string", "enum": ["ledger-7"]}),
("gemini-2.5-flash", {"const": "card", "enum": ["card", "bank"]}, {"type": "string", "enum": ["card"]}),
("gemini-4-argon", {"const": 7}, {"type": "integer", "enum": ["7"]}),
("gemini-2.5-flash", {"const": 7}, {"type": "integer"}),
("gemini-2.5-flash", {"const": 1.5}, {"type": "number"}),
("gemini-2.5-flash", {"const": True}, {"type": "boolean"}),
("gemini-2.5-flash", {"type": ["string", "null"], "const": "card"}, {"type": "string", "enum": ["card"]}),
("gemini-4-argon", {"type": "integer", "const": 7.0}, {"type": "integer", "enum": ["7"]}),
],
ids=[
"const-only-string",
"typed-string",
"const-beside-enum",
"integer-with-integer-enums",
"integer-without-integer-enums",
"number",
"boolean",
"nullable-type-list",
"whole-float-under-integer",
],
)
def test_vertex_sends_a_tool_parameter_const_as_its_type_and_the_one_enum_value_gemini_enforces(
model: str, kind_schema: dict[str, object], expected_kind: dict[str, object]
) -> None:
request_params: Final = VertexGeminiConfig().map_openai_params(
non_default_params={
"tools": [
{
"type": "function",
"function": {"name": "pay", "parameters": {"type": "object", "properties": {"kind": kind_schema}}},
}
]
},
optional_params={},
model=model,
drop_params=False,
)
assert request_params["tools"][0]["function_declarations"][0]["parameters"]["properties"]["kind"] == expected_kind
_CARD_PAYMENT: Final = {
"type": "object",
"properties": {"kind": {"const": "card"}, "number": {"type": "string"}},
"required": ["kind", "number"],
}
_BANK_PAYMENT: Final = {
"type": "object",
"properties": {"kind": {"const": "bank"}, "iban": {"type": "string"}},
"required": ["kind", "iban"],
}
_PINNED_PAYMENTS: Final = {
"anyOf": [
{
"type": "object",
"properties": {"kind": {"type": "string", "enum": ["card"]}, "number": {"type": "string"}},
"required": ["kind", "number"],
},
{
"type": "object",
"properties": {"kind": {"type": "string", "enum": ["bank"]}, "iban": {"type": "string"}},
"required": ["kind", "iban"],
},
]
}
@pytest.mark.parametrize(
("parameters", "tool_choice", "expected_declaration"),
[
(
{"anyOf": [_CARD_PAYMENT, _BANK_PAYMENT]},
"auto",
{"name": "pay", "parametersJsonSchema": _PINNED_PAYMENTS},
),
(
{"anyOf": [_CARD_PAYMENT, _BANK_PAYMENT]},
{"type": "function", "function": {"name": "pay"}},
{"name": "pay", "parameters": _PINNED_PAYMENTS},
),
(
{"$ref": "#/$defs/Card", "$defs": {"Card": _CARD_PAYMENT}},
"auto",
{"name": "pay", "parameters": _PINNED_PAYMENTS["anyOf"][0]},
),
],
ids=["union-root-auto", "union-root-forced", "root-ref-to-object"],
)
def test_vertex_pins_tool_consts_on_whichever_schema_field_the_tool_goes_on(
parameters: dict[str, object], tool_choice: str | dict[str, object], expected_declaration: dict[str, object]
) -> None:
request_params: Final = VertexGeminiConfig().map_openai_params(
non_default_params={
"tool_choice": tool_choice,
"tools": [{"type": "function", "function": {"name": "pay", "parameters": deepcopy(parameters)}}],
},
optional_params={},
model="gemini-2.5-flash",
drop_params=False,
)
assert request_params["tools"][0]["function_declarations"] == [expected_declaration]
def test_vertex_response_json_schema_pins_a_const_inside_the_defs_it_keeps() -> None:
response_format: Final = {
"type": "json_schema",
"json_schema": {
"name": "payment",
"schema": {
"type": "object",
"properties": {"payment": {"$ref": "#/$defs/Card"}},
"required": ["payment"],
"$defs": {"Card": {"type": "object", "properties": {"kind": {"const": "card", "type": "string"}}}},
},
},
}
request_params: Final = VertexGeminiConfig().map_openai_params(
non_default_params={"response_format": response_format},
optional_params={},
model="gemini-4-argon",
drop_params=False,
)
assert request_params["response_json_schema"] == {
"type": "object",
"properties": {"payment": {"$ref": "#/$defs/Card"}},
"required": ["payment"],
"$defs": {"Card": {"type": "object", "properties": {"kind": {"type": "string", "enum": ["card"]}}}},
}
_TEN_CHARACTER_CONSTS_IN_BUDGET: Final = GEMINI_MAX_ENUM_BYTES // 10
def _ten_character_const_properties(numbers: range) -> dict[str, object]:
return {f"tag{n}": {"type": "string", "const": f"tag-{n:06d}"} for n in numbers}
def _tool(name: str, properties: dict[str, object]) -> dict[str, object]:
return {"type": "function", "function": {"name": name, "parameters": {"type": "object", "properties": properties}}}
_SentDeclarations = list[dict[str, list[dict[str, dict[str, dict[str, object]]]]]]
def _tools_through_chat(tools: list[dict[str, object]]) -> _SentDeclarations:
return VertexGeminiConfig().map_openai_params(
non_default_params={"tools": tools}, optional_params={}, model="gemini-4-argon", drop_params=False
)["tools"]
def _tools_through_map_function(tools: list[dict[str, object]]) -> _SentDeclarations:
return cast(_SentDeclarations, VertexGeminiConfig().map_function(value=tools, optional_params={}))
@pytest.mark.parametrize("map_tools", [_tools_through_chat, _tools_through_map_function], ids=["chat", "map-function"])
@pytest.mark.parametrize(
("const_count", "pinned"),
[(_TEN_CHARACTER_CONSTS_IN_BUDGET, True), (_TEN_CHARACTER_CONSTS_IN_BUDGET + 1, False)],
ids=["at-budget", "over-budget"],
)
def test_gemini_tools_send_consts_unpinned_once_the_request_enums_pass_the_enum_budget(
map_tools: Callable[[list[dict[str, object]]], _SentDeclarations], const_count: int, pinned: bool
) -> None:
half: Final = const_count // 2
tools: Final = [
_tool("first", _ten_character_const_properties(range(half))),
_tool("second", _ten_character_const_properties(range(half, const_count))),
]
declarations: Final = map_tools(tools)[0]["function_declarations"]
sent_properties: Final = dict(
chain.from_iterable(declaration["parameters"]["properties"].items() for declaration in declarations)
)
assert sent_properties == {
f"tag{n}": {"type": "string", "enum": [f"tag-{n:06d}"]} if pinned else {"type": "string"}
for n in range(const_count)
}
@pytest.mark.parametrize(
("const_count", "pinned"),
[(_TEN_CHARACTER_CONSTS_IN_BUDGET, True), (_TEN_CHARACTER_CONSTS_IN_BUDGET + 1, False)],
ids=["at-budget", "over-budget"],
)
def test_gemini_response_json_schema_keeps_consts_as_sent_once_its_enums_pass_the_enum_budget(
const_count: int, pinned: bool
) -> None:
schema: Final = {"type": "object", "properties": _ten_character_const_properties(range(const_count))}
request_params: Final = VertexGeminiConfig().map_openai_params(
non_default_params={
"response_format": {"type": "json_schema", "json_schema": {"name": "tags", "schema": schema}}
},
optional_params={},
model="gemini-4-argon",
drop_params=False,
)
assert request_params["response_json_schema"]["properties"] == (
{f"tag{n}": {"type": "string", "enum": [f"tag-{n:06d}"]} for n in range(const_count)}
if pinned
else schema["properties"]
)
@pytest.mark.parametrize(
("const_count", "pinned"),
[(_TEN_CHARACTER_CONSTS_IN_BUDGET, True), (_TEN_CHARACTER_CONSTS_IN_BUDGET + 1, False)],
ids=["at-budget", "over-budget"],
)
def test_gemini_sends_consts_unpinned_once_tools_and_response_format_pass_the_enum_budget_together(
const_count: int, pinned: bool
) -> None:
half: Final = const_count // 2
response_properties: Final = _ten_character_const_properties(range(half, const_count))
request_params: Final = VertexGeminiConfig().map_openai_params(
non_default_params={
"tools": [_tool("record", _ten_character_const_properties(range(half)))],
"response_format": {
"type": "json_schema",
"json_schema": {"name": "tags", "schema": {"type": "object", "properties": response_properties}},
},
},
optional_params={},
model="gemini-4-argon",
drop_params=False,
)
assert request_params["tools"][0]["function_declarations"][0]["parameters"]["properties"] == {
f"tag{n}": {"type": "string", "enum": [f"tag-{n:06d}"]} if pinned else {"type": "string"} for n in range(half)
}
assert request_params["response_json_schema"]["properties"] == (
{f"tag{n}": {"type": "string", "enum": [f"tag-{n:06d}"]} for n in range(half, const_count)}
if pinned
else response_properties
)
def test_gemini_tools_keep_integer_enums_that_fit_when_const_pins_pass_the_enum_budget() -> None:
tool: Final = _tool(
"set_priority",
{
**_ten_character_const_properties(range(_TEN_CHARACTER_CONSTS_IN_BUDGET)),
"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", "enum": ["1", "2", "5"]}
assert sent_properties["tag0"] == {"type": "string"}
@pytest.mark.parametrize(
("model", "expected_level"),
[
@@ -3618,7 +3883,7 @@ def test_gemini_mapping_drops_integer_enums_when_the_caller_disallows_them() ->
assert request_params["response_schema"]["properties"]["level"] == {"type": "integer"}
_TEN_DIGIT_VALUES_IN_BUDGET: Final = GEMINI_MAX_ENUM_CHARACTERS // 10
_TEN_DIGIT_VALUES_IN_BUDGET: Final = GEMINI_MAX_ENUM_BYTES // 10
def _ten_digit_integer_enum_tool(name: str, value_count: int) -> dict[str, object]:
@@ -3672,7 +3937,7 @@ def test_gemini_tool_mapping_drops_every_integer_enum_when_the_request_exceeds_t
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)]
names: Final = [f"name{n:06d}" for n in range(GEMINI_MAX_ENUM_BYTES // 10)]
tool: Final = {
"type": "function",
"function": {
@@ -13005,3 +13270,18 @@ async def test_gemini_malformed_finish_with_no_output_bills_the_tokens_on_the_fa
assert capture.failures[0]["completion_tokens"] == 381
assert capture.failures[0]["prompt_tokens"] == 9098
assert cast(float, capture.failures[0]["response_cost"]) > 0
@pytest.mark.parametrize(
("const", "pinned"),
[("a" * GEMINI_MAX_ENUM_BYTES, True), ("账" * (GEMINI_MAX_ENUM_BYTES // 3 + 1), False)],
ids=["ascii-at-budget", "multibyte-over-budget"],
)
def test_gemini_tools_measure_the_enum_budget_in_utf8_bytes(const: str, pinned: bool) -> None:
declarations: Final = _tools_through_chat([_tool("record", {"source": {"type": "string", "const": const}})])[0][
"function_declarations"
]
assert declarations[0]["parameters"]["properties"]["source"] == (
{"type": "string", "enum": [const]} if pinned else {"type": "string"}
)
@@ -1,9 +1,11 @@
import copy
import threading
import time
import tracemalloc
from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
from enum import Enum
from functools import reduce
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
@@ -20,13 +22,17 @@ from litellm.llms.gemini.count_tokens import handler as gemini_count_tokens_hand
from litellm.llms.vertex_ai.common_utils import (
VertexAITokenCounter,
_fix_enum_types,
build_json_schema,
build_vertex_schema,
convert_anyof_null_to_nullable,
convert_vertex_datetime_to_openai_datetime,
get_vertex_location_from_url,
get_vertex_project_id_from_url,
enums_fit,
get_vertex_url,
has_const,
needs_parameters_json_schema,
parameters_json_schema_for,
pop_vertex_request_labels,
set_schema_property_ordering,
supports_response_json_schema,
@@ -1580,7 +1586,6 @@ def test_fix_enum_types():
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
@@ -1661,6 +1666,251 @@ def test_map_function_keeps_integer_enum_when_tools_are_reused():
assert sent[0] == sent[1]
@pytest.mark.parametrize(
("parameters", "expected"),
[
(
{"type": "object", "properties": {"kinds": {"type": "array", "items": {"const": "card"}}}},
{
"type": "object",
"properties": {"kinds": {"type": "array", "items": {"type": "string", "enum": ["card"]}}},
},
),
(
{
"type": "object",
"properties": {"kind": {"anyOf": [{"const": "card", "type": "string"}, {"type": "null"}]}},
},
{
"type": "object",
"properties": {"kind": {"anyOf": [{"type": "string", "enum": ["card"], "nullable": True}]}},
},
),
(
{
"type": "object",
"properties": {"payment": {"$ref": "#/$defs/Card"}},
"$defs": {"Card": {"type": "object", "properties": {"kind": {"const": "card"}}, "required": ["kind"]}},
},
{
"type": "object",
"properties": {
"payment": {
"type": "object",
"properties": {"kind": {"type": "string", "enum": ["card"]}},
"required": ["kind"],
}
},
},
),
(
{"type": "object", "properties": {"code": {"type": "string", "const": 7}}},
{"type": "object", "properties": {"code": {"type": "string"}}},
),
(
{"type": "object", "properties": {"kind": {"type": ["string", "null"], "const": "card"}}},
{"type": "object", "properties": {"kind": {"type": "string", "enum": ["card"]}}},
),
(
{"type": "object", "properties": {"note": {"type": "string", "const": ""}}},
{"type": "object", "properties": {"note": {"type": "string"}}},
),
(
{
"type": "object",
"properties": {"kind": {"anyOf": [{"type": "string"}, {"type": "null"}], "const": "card"}},
},
{"type": "object", "properties": {"kind": {"anyOf": [{"type": "string", "enum": ["card"]}]}}},
),
(
{
"type": "object",
"properties": {"kind": {"anyOf": [{"type": "string"}, {"type": "integer"}], "const": "card"}},
},
{"type": "object", "properties": {"kind": {"anyOf": [{"type": "string", "enum": ["card"]}]}}},
),
(
{
"type": "object",
"properties": {"kind": {"anyOf": [{"const": "card"}, {"const": "bank"}], "const": "bank"}},
},
{"type": "object", "properties": {"kind": {"anyOf": [{"type": "string", "enum": ["bank"]}]}}},
),
(
{"type": "object", "properties": {"note": {"const": ""}}},
{"type": "object", "properties": {"note": {"type": "string"}}},
),
],
ids=[
"items",
"any-of-branch",
"ref-to-defs",
"const-the-type-cannot-hold",
"nullable-type-list",
"empty-string",
"const-beside-any-of",
"const-beside-mixed-type-any-of",
"const-beside-branches-with-other-consts",
"typeless-empty-string",
],
)
def test_build_vertex_schema_pins_a_nested_const_as_a_one_value_enum(
parameters: dict[str, JsonValue], expected: dict[str, JsonValue]
) -> None:
assert build_vertex_schema(parameters) == expected
_PINNED_CARD: Final = {"type": "string", "enum": ["card"]}
_SUBSCHEMA_PLACES: Final[tuple[Callable[[JsonValue], dict[str, JsonValue]], ...]] = (
lambda schema: {"type": "object", "properties": {"kind": schema}},
lambda schema: {"type": "object", "patternProperties": {"^kind$": schema}},
lambda schema: {"type": "object", "additionalProperties": schema},
lambda schema: {"$ref": "#/$defs/Kind", "$defs": {"Kind": schema}},
lambda schema: {"$ref": "#/definitions/Kind", "definitions": {"Kind": schema}},
lambda schema: {"type": "array", "items": schema},
lambda schema: {"type": "array", "items": [schema]},
lambda schema: {"type": "array", "prefixItems": [schema]},
lambda schema: {"type": "array", "contains": schema},
lambda schema: {"not": schema},
lambda schema: {"anyOf": [schema]},
lambda schema: {"oneOf": [schema]},
lambda schema: {"allOf": [schema]},
)
@pytest.mark.parametrize(
"place",
_SUBSCHEMA_PLACES,
ids=[
"properties",
"pattern-properties",
"additional-properties",
"defs",
"definitions",
"items",
"items-list",
"prefix-items",
"contains",
"not",
"any-of",
"one-of",
"all-of",
],
)
def test_build_json_schema_pins_a_const_in_every_subschema_keyword(
place: Callable[[JsonValue], dict[str, JsonValue]],
) -> None:
assert build_json_schema(place({"const": "card"})) == place(_PINNED_CARD)
def _payment_union(other: JsonValue) -> dict[str, JsonValue]:
return {"anyOf": [{"type": "object", "properties": {"kind": {"const": "card"}, "other": other}}]}
@pytest.mark.parametrize(
"build",
[build_json_schema, parameters_json_schema_for],
ids=["response-json-schema", "parameters-json-schema"],
)
@pytest.mark.parametrize(
("other", "expected_other"),
[
({"type": "object", "default": {"const": "bank"}}, {"type": "object", "default": {"const": "bank"}}),
({"type": "object", "examples": [{"const": "bank"}]}, {"type": "object", "examples": [{"const": "bank"}]}),
({"type": "object", "properties": {"const": True}}, {"type": "object", "properties": {"const": True}}),
({"const": None}, {"const": None}),
({"const": {"kind": "bank"}}, {"const": {"kind": "bank"}}),
({"const": ["bank"]}, {"const": ["bank"]}),
({"const": "bank", "type": ["string", "null"]}, {"type": "string", "enum": ["bank"]}),
({"const": 7.0, "type": "integer"}, {"type": "integer", "enum": [7]}),
({"const": 7.0, "type": "number"}, {"type": "number", "enum": [7.0]}),
({"const": ""}, {"type": "string", "enum": [""]}),
({"const": 2**53}, {"const": 2**53}),
({"const": 1e16, "type": "integer"}, {"const": 1e16, "type": "integer"}),
(
{"anyOf": [{"type": "string"}, {"type": "null"}], "const": "bank"},
{"anyOf": [{"type": "string", "enum": ["bank"]}]},
),
(
{"anyOf": [{"type": "string"}, {"type": "integer"}], "const": "bank"},
{"anyOf": [{"type": "string", "enum": ["bank"]}]},
),
(
{"anyOf": [{"type": "integer"}, {"type": "null"}], "const": "bank"},
{"anyOf": [{"type": "integer"}, {"type": "null"}], "const": "bank"},
),
({"oneOf": [{"type": "string"}], "const": "bank"}, {"oneOf": [{"type": "string", "enum": ["bank"]}]}),
({"const": 7, "type": "number"}, {"type": "number", "enum": [7]}),
({"const": "bank", "type": "STRING"}, {"type": "STRING", "enum": ["bank"]}),
({"const": 7, "type": "string"}, {"const": 7, "type": "string"}),
({"const": "7", "type": ["integer", "null"]}, {"const": "7", "type": ["integer", "null"]}),
],
ids=[
"default",
"examples",
"property-named-const",
"null-const",
"object-const",
"array-const",
"typed-const",
"whole-float-const-under-integer",
"whole-float-const-under-number",
"empty-string-const",
"integer-const-past-exact-range",
"whole-float-const-past-exact-range",
"const-beside-any-of",
"const-beside-mixed-type-any-of",
"const-no-branch-holds",
"const-beside-one-of",
"integer-const-under-number",
"upper-case-type",
"const-the-type-cannot-hold",
"const-no-listed-type-holds",
],
)
def test_json_schema_builders_pin_only_scalar_consts_their_declared_type_can_hold(
build: Callable[[dict[str, JsonValue]], Mapping[str, JsonValue] | None],
other: JsonValue,
expected_other: JsonValue,
) -> None:
assert build(_payment_union(other)) == {
"anyOf": [{"type": "object", "properties": {"kind": _PINNED_CARD, "other": expected_other}}]
}
@pytest.mark.parametrize("build", [build_vertex_schema, build_json_schema], ids=["parameters", "response-json-schema"])
def test_schema_builders_keep_a_const_out_of_a_branch_another_property_shares(
build: Callable[[dict[str, JsonValue]], dict[str, object]],
) -> None:
shared: Final[dict[str, JsonValue]] = {"type": "string"}
sent: Final[dict[str, JsonValue]] = {
"type": "object",
"properties": {"kind": {"anyOf": [shared, {"type": "null"}], "const": "card"}, "memo": shared},
}
assert build(sent)["properties"] == {"kind": {"anyOf": [_PINNED_CARD]}, "memo": {"type": "string"}}
def _kind_beside_a_leaf_at_depth(kind: JsonValue, depth: int, leaf: JsonValue) -> dict[str, JsonValue]:
nested: Final = reduce(lambda inner, _: {"type": "object", "properties": {"next": inner}}, range(depth - 1), leaf)
return {"type": "object", "properties": {"kind": kind, "next": nested}}
@pytest.mark.parametrize(
("depth", "expected_leaf"),
[(DEFAULT_MAX_RECURSE_DEPTH, _PINNED_CARD), (DEFAULT_MAX_RECURSE_DEPTH + 1, {"const": "card"})],
ids=["at-the-cap", "past-the-cap"],
)
def test_build_json_schema_pins_consts_down_to_the_recursion_cap_and_sends_deeper_ones_as_given(
depth: int, expected_leaf: JsonValue
) -> None:
sent: Final = _kind_beside_a_leaf_at_depth({"const": "card"}, depth, {"const": "card"})
assert build_json_schema(sent) == _kind_beside_a_leaf_at_depth(_PINNED_CARD, depth, expected_leaf)
_OBJECT_BRANCH: Final = {"type": "object", "properties": {"a": {"type": "string"}}, "required": ["a"]}
_DEEP_ROOT_REF_CHAIN_LENGTH: Final = 3000
@@ -1693,10 +1943,29 @@ def _deep_root_ref_chain(end: Mapping[str, JsonValue]) -> Mapping[str, JsonValue
({"$ref": "#/$defs/A", "$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"anyOf": [_OBJECT_BRANCH]}}}, True),
({"$ref": "#/$defs/A", "$defs": {"A": {"$ref": "#/$defs/B"}, "B": _OBJECT_BRANCH}}, False),
({"$ref": "#/$defs/Lookup", "anyOf": [{"required": ["a"]}], "$defs": {"Lookup": _OBJECT_BRANCH}}, True),
({"$ref": "#/$defs/A", "$defs": {"A": {"$ref": "#/$defs/B", "oneOf": [_OBJECT_BRANCH]}, "B": _OBJECT_BRANCH}}, True),
(
{
"$ref": "#/$defs/A",
"$defs": {"A": {"$ref": "#/$defs/B", "oneOf": [_OBJECT_BRANCH]}, "B": _OBJECT_BRANCH},
},
True,
),
({"$ref": "#/$defs/A", "$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A"}}}, False),
({"$ref": "#/$defs/A", "$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A", "anyOf": [_OBJECT_BRANCH]}}}, False),
({"$ref": "#/$defs/A", "anyOf": [{"required": ["a"]}], "$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A"}}}, False),
(
{
"$ref": "#/$defs/A",
"$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A", "anyOf": [_OBJECT_BRANCH]}},
},
False,
),
(
{
"$ref": "#/$defs/A",
"anyOf": [{"required": ["a"]}],
"$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A"}},
},
False,
),
(_deep_root_ref_chain({"anyOf": [_OBJECT_BRANCH]}), True),
(_deep_root_ref_chain(_OBJECT_BRANCH), False),
],
@@ -1798,6 +2067,7 @@ def test_fix_enum_types_sends_only_integer_enums_gemini_accepts(
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,
@@ -1993,7 +2263,9 @@ async def test_vertex_claude_count_forwards_the_context_edits_and_beta_vertex_in
fake_http_client: Final = FakeHttpClient()
spec: Final[dict[str, JsonValue]] = {"edits": [{"type": edit_type}]}
application_default_credentials: Final = MagicMock(token="fake-token", valid=True, expiry=None)
monkeypatch.setattr("google.auth.default", lambda *args, **kwargs: (application_default_credentials, "test-project"))
monkeypatch.setattr(
"google.auth.default", lambda *args, **kwargs: (application_default_credentials, "test-project")
)
with patch.object(handler, "get_async_httpx_client", return_value=fake_http_client):
result: Final = await VertexAITokenCounter().count_tokens(
model_to_use="claude-opus-4-8",
@@ -2038,7 +2310,9 @@ async def test_vertex_claude_count_sends_the_thinking_vertex_inference_sends(
fake_http_client: Final = FakeHttpClient()
application_default_credentials: Final = MagicMock(token="fake-token", valid=True, expiry=None)
monkeypatch.setattr("google.auth.default", lambda *args, **kwargs: (application_default_credentials, "test-project"))
monkeypatch.setattr(
"google.auth.default", lambda *args, **kwargs: (application_default_credentials, "test-project")
)
with patch.object(handler, "get_async_httpx_client", return_value=fake_http_client):
result: Final = await VertexAITokenCounter().count_tokens(
model_to_use="claude-opus-4-8",
@@ -2086,7 +2360,9 @@ async def test_vertex_claude_count_with_an_edit_fetches_the_remote_beta_config_o
monkeypatch.setattr(anthropic_beta_headers_manager, "_BETA_HEADERS_CONFIG", None)
fetch_threads: Final = FetchThreads()
application_default_credentials: Final = MagicMock(token="fake-token", valid=True, expiry=None)
monkeypatch.setattr("google.auth.default", lambda *args, **kwargs: (application_default_credentials, "test-project"))
monkeypatch.setattr(
"google.auth.default", lambda *args, **kwargs: (application_default_credentials, "test-project")
)
with patch.object(handler, "get_async_httpx_client", return_value=FakeHttpClient()), respx.mock:
respx.get(litellm.anthropic_beta_headers_url).mock(side_effect=fetch_threads)
result: Final = await VertexAITokenCounter().count_tokens(
@@ -2937,3 +3213,38 @@ async def test_vertex_ai_token_counter_routes_like_generate_content(
)
assert (None if result is None else result.total_tokens) == vertex_counted_tokens
@pytest.mark.timeout(10)
def test_const_and_enum_walks_end_on_a_schema_that_contains_itself() -> None:
node: Final[dict[str, JsonValue]] = {"type": "object"}
node["properties"] = { # rebind-ok: a schema that contains itself needs a store after it exists
"left": node,
"right": node,
"kind": {"type": "string", "enum": ["x" * 2001]},
}
assert has_const(node) is False
assert enums_fit(node) is False
def test_const_and_enum_walks_keep_memory_flat_on_a_deep_schema_with_many_branches() -> None:
wide: Final[JsonValue] = {"anyOf": [{"not": {}} for _ in range(20_000)]}
schema: Final = reduce(lambda inner, _: {"not": inner}, range(64), wide)
tracemalloc.start()
try:
answers: Final = (has_const(schema), enums_fit(schema))
peak: Final = tracemalloc.get_traced_memory()[1]
finally:
tracemalloc.stop()
assert answers == (False, True)
assert peak < 8 * 1024 * 1024
@pytest.mark.timeout(10)
def test_enum_budget_answers_fast_when_one_huge_enum_value_repeats_across_branches() -> None:
huge: Final = "x" * (8 * 1024 * 1024)
assert enums_fit({"anyOf": [{"type": "string", "enum": [huge]} for _ in range(20_000)]}) is False