Skip to content
Open
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
4 changes: 3 additions & 1 deletion src/google/adk/tools/_automatic_function_calling_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,9 @@ def from_function_with_options(
)
if param.default is not inspect.Parameter.empty:
if param.default is not None:
parameters_json_schema[name].default = param.default
parameters_json_schema[name].default = (
_function_parameter_parse_util._json_schema_default(param)
)
else:
parameters_json_schema[name].nullable = True
except Exception as e:
Expand Down
52 changes: 51 additions & 1 deletion src/google/adk/tools/_function_parameter_parse_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@

from google.genai import types
import pydantic
import pydantic.json_schema
import pydantic_core

from ..tools.tool_context import ToolContext
from ..utils.variant_utils import GoogleLLMVariant
Expand Down Expand Up @@ -184,6 +186,52 @@ def _render_enum_value(value: object, annotation: object) -> str:
) from e


def _render_enum_json_value(value: object, annotation: object) -> str:
"""Renders an enum value to string from its JSON form.

Unlike `_render_enum_value`, a value that `json.dumps` cannot encode but
pydantic can, such as a date, is rendered as pydantic encodes it.
"""
return _render_enum_value(pydantic_core.to_jsonable_python(value), annotation)


class _StringEnumGenerateJsonSchema(pydantic.json_schema.GenerateJsonSchema):
"""Declares every Enum as a STRING schema with string values.

`types.Schema.enum` only takes strings, so the schema pydantic emits for an
Enum with other values, such as `{'enum': [1, 2], 'type': 'integer'}` for an
IntEnum, cannot be converted to it. `_parse_schema_from_parameter` declares an
Enum the same way.
"""

def enum_schema(
self, schema: pydantic_core.core_schema.EnumSchema
) -> pydantic.json_schema.JsonSchemaValue:
json_schema = super().enum_schema(schema)
json_schema['type'] = 'string'
json_schema['enum'] = [
_render_enum_json_value(member.value, schema['cls'])
for member in schema['members']
]
return json_schema


def _json_schema_default(param: inspect.Parameter) -> Any:
"""Returns the default of `param` for its schema generated by pydantic.

An Enum default is rendered like the values of the schema's `enum`, so it is
one of them.
"""
if not (
inspect.isclass(param.annotation) and issubclass(param.annotation, Enum)
):
return param.default
default_value = (
param.default.value if isinstance(param.default, Enum) else param.default
)
return _render_enum_json_value(default_value, param.annotation)


def _generate_json_schema_for_parameter(
param: inspect.Parameter,
) -> dict[str, Any]:
Expand All @@ -198,7 +246,9 @@ def _generate_json_schema_for_parameter(
param.annotation,
config=pydantic.ConfigDict(arbitrary_types_allowed=True),
)
json_schema_dict = param_schema_adapter.json_schema()
json_schema_dict = param_schema_adapter.json_schema(
schema_generator=_StringEnumGenerateJsonSchema
)
json_schema_dict = _dereference_schema(json_schema_dict)
json_schema_dict = _add_unevaluated_items_to_fixed_len_tuple_schema(
json_schema_dict
Expand Down
49 changes: 47 additions & 2 deletions tests/unittests/tools/test_build_function_declaration.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,8 +577,9 @@ def set_date(date: DateEnum = DateEnum.EPOCH):
function_decl = _automatic_function_calling_util.build_function_declaration(
func=set_date
)
assert 'date' in function_decl.parameters.properties
assert function_decl.parameters.properties['date'].default == DateEnum.EPOCH
date_schema = function_decl.parameters.properties['date']
assert date_schema.enum == ['1970-01-01']
assert date_schema.default == '1970-01-01'

def test_enum_fallback_rejects_invalid_default(self):
"""An Enum falling back to pydantic rejects an invalid default value."""
Expand All @@ -594,6 +595,50 @@ def set_date_invalid(date: DateEnum = datetime.date(2000, 1, 1)):
func=set_date_invalid
)

@pytest.mark.parametrize(
'variant', [GoogleLLMVariant.GEMINI_API, GoogleLLMVariant.VERTEX_AI]
)
def test_int_enum_falling_back_to_pydantic(self, variant):
"""An IntEnum declares its values as strings when its function falls back.

The tuple parameter makes every parameter of the function fall back to
pydantic schema generation.
"""

class Level(IntEnum):
LOW = 1
HIGH = 2

def set_level(level: Level = Level.HIGH, pair: tuple[str, int] = None):
return level.value

function_decl = _automatic_function_calling_util.build_function_declaration(
func=set_level, variant=variant
)

level_schema = function_decl.parameters.properties['level']
assert level_schema.type == 'STRING'
assert level_schema.enum == ['1', '2']
assert level_schema.default == '2'

def test_nested_int_enum_falling_back_to_pydantic(self):
"""An IntEnum nested in a fallback parameter declares string values."""

class Level(IntEnum):
LOW = 1
HIGH = 2

def set_levels(levels: list[Level], pair: tuple[str, int] = None):
return levels

function_decl = _automatic_function_calling_util.build_function_declaration(
func=set_levels
)

items_schema = function_decl.parameters.properties['levels'].items
assert items_schema.type == 'STRING'
assert items_schema.enum == ['1', '2']

def test_basemodel_list(self):
class ChildInput(BaseModel):
input_str: str
Expand Down
Loading