Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions google/genai/_extra_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,15 @@ def convert_if_exist_pydantic_model(
(get_args(arg) and get_origin(arg) is list)
or isinstance(value, arg)
or (isinstance(value, dict) and is_annotation_pydantic_model(arg))
# int values are also accepted for a float member of the union,
# mirroring the int to float exception in the non-union path
# below. bool is excluded because it is an int subclass and a
# bool member may appear later in the union.
or (
isinstance(value, int)
and not isinstance(value, bool)
and arg is float
)
):
try:
return convert_if_exist_pydantic_model(
Expand Down
45 changes: 45 additions & 0 deletions google/genai/tests/afc/test_convert_if_exist_pydantic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,51 @@ def test_value_int_annotation_float():
)


def test_value_int_annotation_optional_float():
# Whole numbers arrive as int after
# convert_number_values_for_function_call_args, and must still be
# accepted when float appears inside a union annotation.
assert (
convert_if_exist_pydantic_model(
21, Optional[float], 'param_name', 'func_name'
)
== 21
)
assert (
convert_if_exist_pydantic_model(
21, Union[float, None], 'param_name', 'func_name'
)
== 21
)
# The int member is written first, so it wins for an int value.
assert (
convert_if_exist_pydantic_model(
21, Union[int, float], 'param_name', 'func_name'
)
== 21
)
assert (
convert_if_exist_pydantic_model(
None, Optional[float], 'param_name', 'func_name'
)
is None
)
assert (
convert_if_exist_pydantic_model(
21.5, Optional[float], 'param_name', 'func_name'
)
== 21.5
)
# | in 3.10+
if sys.version_info >= (3, 10):
assert (
convert_if_exist_pydantic_model(
21, float | None, 'param_name', 'func_name'
)
== 21
)


def test_union_types():
assert (
convert_if_exist_pydantic_model(
Expand Down
Loading