From 68ee7edec03389318279c43fdea43501199118ae Mon Sep 17 00:00:00 2001 From: Hilary Date: Mon, 26 Oct 2026 19:52:55 +0100 Subject: [PATCH 1/2] fix(google-genai): resolve JSON pointer $refs in tool schemas A tool output schema that still can't be converted is now dropped with a warning instead of failing the request. --- .../genkit_google_genai/_models/_gemini.py | 98 ++++++++---- .../tests/models/googlegenai_gemini_test.py | 146 ++++++++++++++++-- 2 files changed, 200 insertions(+), 44 deletions(-) diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index f48dca11..1d3e6524 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -24,6 +24,7 @@ from datetime import datetime, timedelta, timezone from functools import cached_property from typing import Annotated, Any, Any as JsonAny, Literal, TypeAlias, cast, get_args +from urllib.parse import unquote from genkit_google_genai._auth import GOOGLE_AUTH_ERRORS, raise_auth_error from genkit_google_genai._models._context_caching._constants import DEFAULT_TTL @@ -76,6 +77,7 @@ ModelResponseChunk, Part, Role, + get_logger, ) from genkit.model import ( ConstrainedSupport, @@ -88,6 +90,8 @@ ToolDefinition, ) +logger = get_logger(__name__) + def _to_dict(obj: JsonAny) -> JsonAny: # noqa: ANN401 """Convert object to dict if it's a Pydantic model, otherwise return as-is.""" @@ -1785,12 +1789,19 @@ def _create_tool(self, tool: ToolDefinition) -> tuple[genai_types.Tool, ToolWire required=[TOOL_INPUT_FIELD], ) + response = None + if tool.output_schema: + try: + response = self._convert_schema_property(tool.output_schema) + except GenkitError as e: + logger.warning('Sending tool %s without its output schema: %s', tool.name, e.message) + wire_name = tool.name.replace('/', '__') function = genai_types.FunctionDeclaration( name=wire_name, description=tool.description, parameters=params, - response=self._convert_schema_property(tool.output_schema) if tool.output_schema else None, + response=response, ) return genai_types.Tool(function_declarations=[function]), ToolWire( original_name=tool.name, @@ -1827,27 +1838,29 @@ def _create_tool(self, tool: ToolDefinition) -> tuple[genai_types.Tool, ToolWire def _convert_schema_property( self, input_schema: dict[str, object] | None, - defs: dict[str, object] | None = None, + root: dict[str, object] | None = None, *, strict: bool = False, - refs: frozenset[str] = frozenset(), + ancestors: frozenset[int] = frozenset(), ) -> genai_types.Schema | None: """Convert a JSON Schema dict into a Gemini ``Schema``. - Resolves local ``$ref``, maps ``anyOf`` and ``oneOf`` on a node with - no ``type`` to ``any_of``, folds a ``null`` branch of either or of a - ``type`` list into ``nullable``, maps the ``enum`` type to STRING and a - string ``const`` to a one-value ``enum``. An ``enum`` is kept only on a - STRING node whose members are all strings, dropping a ``null`` member; - a node with such an ``enum`` and no ``type`` is treated as a string. + Resolves a local ``$ref`` as a JSON pointer into ``root``, maps + ``anyOf`` and ``oneOf`` on a node with no ``type`` to ``any_of``, folds + a ``null`` branch of either or of a ``type`` list into ``nullable``, + maps the ``enum`` type to STRING and a string ``const`` to a one-value + ``enum``. An ``enum`` is kept only on a STRING node whose members are + all strings, dropping a ``null`` member; a node with such an ``enum`` + and no ``type`` is treated as a string. Any other node with no ``type``, an array with no ``items`` object or - whose ``items`` convert to None, and a ``$ref`` back to a definition - that contains it convert to None and are left out of the parent's + whose ``items`` convert to None, and a ``$ref`` to a node that + contains it convert to None and are left out of the parent's ``properties`` and ``required``. Args: input_schema: A JSON Schema dict. - defs: Dictionary with definitions. Optional. + root: The document a ``$ref`` resolves against. Defaults to + ``input_schema``. strict: Raise ``INVALID_ARGUMENT`` for a node that constrains without a ``type``, for a required property that converts to None, for a ``type`` list, ``anyOf`` or ``oneOf`` that would @@ -1855,7 +1868,7 @@ def _convert_schema_property( keyword value that cannot be coerced, instead of leaving them out. An object with ``additionalProperties`` and no ``properties`` also converts to None. - refs: Names of the definitions being expanded on the current path. + ancestors: Ids of the nodes being converted on the current path. Returns: Schema or None @@ -1863,28 +1876,20 @@ def _convert_schema_property( if input_schema is None: return None - if defs is None: - defs_value = input_schema.get('$defs') - defs = cast(dict[str, object], defs_value) if isinstance(defs_value, dict) else {} + if root is None: + root = input_schema + ancestors |= {id(input_schema)} if '$ref' in input_schema: ref_path = input_schema['$ref'] if isinstance(ref_path, str): - ref_tokens = ref_path.split('/') - ref_name = ref_tokens[-1] - - if defs is None or ref_name not in defs: - raise GenkitError( - status='INVALID_ARGUMENT', - message=f'{self._version}: schema $ref {ref_path!r} cannot be resolved', - ) - if ref_name in refs: + ref_schema = self._resolve_ref(ref_path, root) + if id(ref_schema) in ancestors: return None - ref_schema = defs[ref_name] if isinstance(ref_schema, dict): schema = self._convert_schema_property( - cast(dict[str, object], ref_schema), defs, strict=strict, refs=refs | {ref_name} + cast(dict[str, object], ref_schema), root, strict=strict, ancestors=ancestors ) else: schema = None @@ -1899,13 +1904,13 @@ def _convert_schema_property( branches = input_schema.get(keyword) if isinstance(branches, list): return self._convert_union( - input_schema, keyword, cast(list[object], branches), defs, strict=strict, refs=refs + input_schema, keyword, cast(list[object], branches), root, strict=strict, ancestors=ancestors ) enum = input_schema.get('enum') if isinstance(enum, list) and self._string_enum_members(cast(list[object], enum)) is not None: nullable = any(m is None for m in cast(list[object], enum)) typed: dict[str, object] = {**input_schema, 'type': ['string', 'null'] if nullable else 'string'} - return self._convert_schema_property(typed, defs, strict=strict, refs=refs) + return self._convert_schema_property(typed, root, strict=strict, ancestors=ancestors) if strict: unsupported = sorted(set(input_schema) - self._SCHEMA_ANNOTATION_KEYS) if unsupported: @@ -1956,7 +1961,7 @@ def _convert_schema_property( items_value = input_schema.get('items') if isinstance(items_value, dict): schema.items = self._convert_schema_property( - cast(dict[str, object], items_value), defs, strict=strict, refs=refs + cast(dict[str, object], items_value), root, strict=strict, ancestors=ancestors ) if schema.items is None: return None @@ -1971,7 +1976,9 @@ def _convert_schema_property( properties = cast(dict[str, object], properties_value) for key, value in properties.items(): nested_schema = ( - self._convert_schema_property(cast(dict[str, object], value), defs, strict=strict, refs=refs) + self._convert_schema_property( + cast(dict[str, object], value), root, strict=strict, ancestors=ancestors + ) if isinstance(value, dict) else None ) @@ -1992,10 +1999,10 @@ def _convert_union( input_schema: dict[str, object], keyword: str, union: list[object], - defs: dict[str, object] | None, + root: dict[str, object], *, strict: bool, - refs: frozenset[str], + ancestors: frozenset[int], ) -> genai_types.Schema | None: """Convert an ``anyOf`` or ``oneOf`` node to ``any_of``; a ``null`` branch becomes ``nullable``. @@ -2006,7 +2013,9 @@ def _convert_union( branches = [cast(dict[str, object], b) for b in union if isinstance(b, dict)] typed = [b for b in branches if b.get('type') not in ('null', ['null'])] converted = [ - s for b in typed if (s := self._convert_schema_property(b, defs, strict=strict, refs=refs)) is not None + s + for b in typed + if (s := self._convert_schema_property(b, root, strict=strict, ancestors=ancestors)) is not None ] if not converted: return None @@ -2022,6 +2031,27 @@ def _convert_union( self._copy_schema_keywords(input_schema, schema, strict=strict) return schema + def _resolve_ref(self, ref_path: str, root: dict[str, object]) -> object: + """Resolve a ``#`` or ``#/...`` JSON pointer ``$ref`` against ``root``.""" + if ref_path == '#': + return root + if ref_path.startswith('#/'): + node: object = root + for token in unquote(ref_path[2:]).split('/'): + key = token.replace('~1', '/').replace('~0', '~') + if isinstance(node, dict) and key in node: + node = cast(dict[str, object], node)[key] + elif isinstance(node, list) and key.isdecimal() and int(key) < len(node): + node = cast(list[object], node)[int(key)] + else: + break + else: + return node + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'{self._version}: schema $ref {ref_path!r} cannot be resolved', + ) + def _copy_schema_keywords( self, input_schema: dict[str, object], schema: genai_types.Schema, *, strict: bool ) -> None: diff --git a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py index ee484be5..b2e52462 100644 --- a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py +++ b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py @@ -52,6 +52,7 @@ from google.genai.errors import APIError from pydantic import BaseModel, Field, HttpUrl, ValidationError from pytest_mock import MockerFixture +from structlog.testing import capture_logs from genkit import ErrorReason, FinishReason, Genkit, GenkitError, Message, ModelResponse, Part, Role from genkit.model import ( @@ -905,7 +906,7 @@ def test_gemini_model__create_tool( @pytest.mark.parametrize( - 'input_schema, defs, expected_schema', + 'input_schema, root, expected_schema', [ # Test Case 1: None input_schema ( @@ -982,13 +983,13 @@ def test_gemini_model__create_tool( }, ), ), - # Test Case 9: Object with nested $ref and existing defs + # Test Case 9: Object with nested $ref and a separate root ( { 'type': 'OBJECT', 'properties': {'address': {'$ref': '#/$defs/Address'}}, }, - {'Address': {'type': 'OBJECT', 'properties': {'street': {'type': 'STRING'}}}}, + {'$defs': {'Address': {'type': 'OBJECT', 'properties': {'street': {'type': 'STRING'}}}}}, genai_types.Schema( type=genai_types.Type.OBJECT, properties={ @@ -1072,12 +1073,12 @@ def test_gemini_model__create_tool( ) def test_gemini_model__convert_schema_property( input_schema: dict[str, object] | None, - defs: dict[str, object] | None, + root: dict[str, object] | None, expected_schema: genai_types.Schema | None, gemini_model_instance: GeminiModel, ) -> None: """Unit tests for GeminiModel._convert_schema_property with various valid schema inputs.""" - result_schema = gemini_model_instance._convert_schema_property(input_schema, defs) + result_schema = gemini_model_instance._convert_schema_property(input_schema, root) if expected_schema is None: assert result_schema is None @@ -1110,7 +1111,7 @@ def compare_schemas(s1: genai_types.Schema, s2: genai_types.Schema) -> None: @pytest.mark.parametrize( - 'input_schema, defs', + 'input_schema, root', [ # Test Case 11: Unresolvable $ref ( @@ -1122,26 +1123,151 @@ def compare_schemas(s1: genai_types.Schema, s2: genai_types.Schema) -> None: {'type': 'OBJECT', 'properties': {'user': {'$ref': '#/$defs/NonExistent'}}}, None, ), - # Test Case 13: $ref to the document root + # Test Case 13: JSON pointer past the end of a list ( - {'type': 'OBJECT', 'properties': {'user': {'$ref': '#'}}}, + {'type': 'OBJECT', 'properties': {'user': {'$ref': '#/anyOf/0'}}, 'anyOf': []}, + None, + ), + # Test Case 14: Remote $ref + ( + {'type': 'OBJECT', 'properties': {'user': {'$ref': 'https://example.com/user.json'}}}, + None, + ), + # Test Case 15: Non-numeric JSON pointer token into a list + ( + {'type': 'OBJECT', 'properties': {'user': {'$ref': '#/anyOf/x'}}, 'anyOf': [{'type': 'STRING'}]}, None, ), ], ) def test_gemini_model__convert_schema_property_raises_exception( input_schema: dict[str, object], - defs: dict[str, object] | None, + root: dict[str, object] | None, gemini_model_instance: GeminiModel, ) -> None: """Test GeminiModel._convert_schema_property raises an exception for unresolvable schemas.""" with pytest.raises(GenkitError) as exc_info: - gemini_model_instance._convert_schema_property(input_schema, defs) + gemini_model_instance._convert_schema_property(input_schema, root) assert exc_info.value.status == 'INVALID_ARGUMENT' assert 'cannot be resolved' in exc_info.value.message +@pytest.mark.parametrize('strict', [False, True]) +@pytest.mark.parametrize( + 'ref, root_extra', + [ + ('#/definitions/Name', {'definitions': {'Name': {'type': 'string'}}}), + ('#/properties/a', {}), + ('#/properties/list/items', {}), + ('#/properties/a~1b~0c', {}), + ('#/properties/a~01b', {}), + ('#/properties/a%20b', {}), + ('#/anyOf/0', {'anyOf': [{'type': 'string'}]}), + ], +) +def test_gemini_model__convert_schema_property_resolves_json_pointer_ref( + ref: str, root_extra: dict[str, object], strict: bool, gemini_model_instance: GeminiModel +) -> None: + """A $ref resolves as a JSON pointer into the document, not only into $defs.""" + string = {'type': 'string'} + input_schema: dict[str, object] = { + 'type': 'object', + 'properties': { + 'a': string, + 'list': {'type': 'array', 'items': string}, + 'a/b~c': string, + 'a~1b': string, + 'a b': string, + 'ref': {'$ref': ref}, + }, + **root_extra, + } + + schema = gemini_model_instance._convert_schema_property(input_schema, strict=strict) + + assert schema is not None and schema.properties is not None + assert schema.properties['ref'] == genai_types.Schema(type=genai_types.Type.STRING) + + +@pytest.mark.parametrize( + 'input_schema', + [ + # draft-07 definitions that refer back to themselves + { + '$ref': '#/definitions/Node', + 'definitions': { + 'Node': { + 'type': 'object', + 'properties': {'value': {'type': 'integer'}, 'next': {'$ref': '#/definitions/Node'}}, + }, + }, + }, + # a JSON pointer to a property that contains it + { + 'type': 'object', + 'properties': { + 'node': { + 'type': 'object', + 'properties': {'value': {'type': 'integer'}, 'next': {'$ref': '#/properties/node'}}, + }, + }, + }, + # the document root + {'type': 'object', 'properties': {'value': {'type': 'integer'}, 'next': {'$ref': '#'}}}, + ], +) +def test_gemini_model__convert_schema_property_leaves_out_recursive_json_pointer_ref( + input_schema: dict[str, object], gemini_model_instance: GeminiModel +) -> None: + """A $ref to a node that contains it is left out, whatever the pointer.""" + schema = gemini_model_instance._convert_schema_property(input_schema) + + node = genai_types.Schema( + type=genai_types.Type.OBJECT, properties={'value': genai_types.Schema(type=genai_types.Type.INTEGER)} + ) + assert schema is not None + assert node in (schema, (schema.properties or {}).get('node')) + + +def test_gemini_model__create_tool_drops_unconvertible_output_schema(gemini_model_instance: GeminiModel) -> None: + """A tool whose output schema cannot be converted is sent without one.""" + tool = ToolDefinition( + name='t', + description='d', + input_schema={'type': 'object', 'properties': {'q': {'type': 'string'}}}, + output_schema={'type': 'object', 'properties': {'r': {'$ref': '#/properties/missing'}}}, + ) + + with capture_logs() as entries: + gemini_tool, _ = gemini_model_instance._create_tool(tool) + + declarations = gemini_tool.function_declarations + assert declarations is not None + assert declarations[0].response is None + assert declarations[0].parameters == genai_types.Schema( + type=genai_types.Type.OBJECT, properties={'q': genai_types.Schema(type=genai_types.Type.STRING)} + ) + assert [entry['event'] for entry in entries if entry['log_level'] == 'warning'] == [ + "Sending tool t without its output schema: version: schema $ref '#/properties/missing' cannot be resolved" + ] + + +def test_gemini_model__create_tool_rejects_unconvertible_input_schema(gemini_model_instance: GeminiModel) -> None: + """A tool whose input schema cannot be converted still fails.""" + tool = ToolDefinition( + name='t', + description='d', + input_schema={'type': 'object', 'properties': {'q': {'$ref': '#/properties/missing'}}}, + output_schema={'type': 'string'}, + ) + + with pytest.raises(GenkitError) as exc_info: + gemini_model_instance._create_tool(tool) + + assert exc_info.value.status == 'INVALID_ARGUMENT' + + class _LinkedList(BaseModel): value: int next: '_LinkedList | None' = None From 130fed46654ff568958222bceed5a2369c280ceb Mon Sep 17 00:00:00 2001 From: Hilary Date: Thu, 5 Nov 2026 11:46:14 +0100 Subject: [PATCH 2/2] fix(google-genai): warn when a tool schema is sent without parts --- .../genkit_google_genai/_models/_gemini.py | 38 +++++-- .../tests/models/googlegenai_gemini_test.py | 100 +++++++++++++++++- 2 files changed, 127 insertions(+), 11 deletions(-) diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index 1d3e6524..5b04c27c 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -1774,10 +1774,19 @@ def _create_tool(self, tool: ToolDefinition) -> tuple[genai_types.Tool, ToolWire Returns: Genai tool compatible with Gemini API, plus how it was declared. """ - params = self._convert_schema_property(tool.input_schema) + dropped: list[str] = [] + params = self._convert_schema_property(tool.input_schema, dropped=dropped) + if dropped: + logger.warning( + 'Sending tool %s without required properties %s, which cannot be converted', + tool.name, + ', '.join(dict.fromkeys(dropped)), + ) wrapped = False # Empty params: Gemini requires type=OBJECT even for no-arg tools. if not params: + if tool.input_schema: + logger.warning('Sending tool %s without its input schema, which cannot be converted', tool.name) params = genai_types.Schema(type=genai_types.Type.OBJECT, properties={}) elif params.type != genai_types.Type.OBJECT: # wrap after convert so OBJECT / Type.OBJECT / $ref enums / ['null'] @@ -1795,6 +1804,9 @@ def _create_tool(self, tool: ToolDefinition) -> tuple[genai_types.Tool, ToolWire response = self._convert_schema_property(tool.output_schema) except GenkitError as e: logger.warning('Sending tool %s without its output schema: %s', tool.name, e.message) + else: + if response is None: + logger.warning('Sending tool %s without its output schema, which cannot be converted', tool.name) wire_name = tool.name.replace('/', '__') function = genai_types.FunctionDeclaration( @@ -1842,6 +1854,7 @@ def _convert_schema_property( *, strict: bool = False, ancestors: frozenset[int] = frozenset(), + dropped: list[str] | None = None, ) -> genai_types.Schema | None: """Convert a JSON Schema dict into a Gemini ``Schema``. @@ -1869,6 +1882,7 @@ def _convert_schema_property( out. An object with ``additionalProperties`` and no ``properties`` also converts to None. ancestors: Ids of the nodes being converted on the current path. + dropped: Collects the names of required properties left out. Returns: Schema or None @@ -1889,7 +1903,7 @@ def _convert_schema_property( if isinstance(ref_schema, dict): schema = self._convert_schema_property( - cast(dict[str, object], ref_schema), root, strict=strict, ancestors=ancestors + cast(dict[str, object], ref_schema), root, strict=strict, ancestors=ancestors, dropped=dropped ) else: schema = None @@ -1904,13 +1918,19 @@ def _convert_schema_property( branches = input_schema.get(keyword) if isinstance(branches, list): return self._convert_union( - input_schema, keyword, cast(list[object], branches), root, strict=strict, ancestors=ancestors + input_schema, + keyword, + cast(list[object], branches), + root, + strict=strict, + ancestors=ancestors, + dropped=dropped, ) enum = input_schema.get('enum') if isinstance(enum, list) and self._string_enum_members(cast(list[object], enum)) is not None: nullable = any(m is None for m in cast(list[object], enum)) typed: dict[str, object] = {**input_schema, 'type': ['string', 'null'] if nullable else 'string'} - return self._convert_schema_property(typed, root, strict=strict, ancestors=ancestors) + return self._convert_schema_property(typed, root, strict=strict, ancestors=ancestors, dropped=dropped) if strict: unsupported = sorted(set(input_schema) - self._SCHEMA_ANNOTATION_KEYS) if unsupported: @@ -1961,7 +1981,7 @@ def _convert_schema_property( items_value = input_schema.get('items') if isinstance(items_value, dict): schema.items = self._convert_schema_property( - cast(dict[str, object], items_value), root, strict=strict, ancestors=ancestors + cast(dict[str, object], items_value), root, strict=strict, ancestors=ancestors, dropped=dropped ) if schema.items is None: return None @@ -1977,7 +1997,7 @@ def _convert_schema_property( for key, value in properties.items(): nested_schema = ( self._convert_schema_property( - cast(dict[str, object], value), root, strict=strict, ancestors=ancestors + cast(dict[str, object], value), root, strict=strict, ancestors=ancestors, dropped=dropped ) if isinstance(value, dict) else None @@ -1990,6 +2010,8 @@ def _convert_schema_property( status='INVALID_ARGUMENT', message=f'{self._version}: required property {key} cannot be converted', ) + if dropped is not None: + dropped.append(key) schema.required = [name for name in schema.required or () if name != key] or None return schema @@ -2003,6 +2025,7 @@ def _convert_union( *, strict: bool, ancestors: frozenset[int], + dropped: list[str] | None, ) -> genai_types.Schema | None: """Convert an ``anyOf`` or ``oneOf`` node to ``any_of``; a ``null`` branch becomes ``nullable``. @@ -2015,7 +2038,8 @@ def _convert_union( converted = [ s for b in typed - if (s := self._convert_schema_property(b, root, strict=strict, ancestors=ancestors)) is not None + if (s := self._convert_schema_property(b, root, strict=strict, ancestors=ancestors, dropped=dropped)) + is not None ] if not converted: return None diff --git a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py index b2e52462..d7850b85 100644 --- a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py +++ b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py @@ -972,7 +972,7 @@ def test_gemini_model__create_tool( 'properties': {'user': {'$ref': '#/$defs/User'}}, '$defs': {'User': {'type': 'OBJECT', 'properties': {'name': {'type': 'STRING'}}}}, }, - None, # defs will be picked from input_schema['$defs'] + None, # root defaults to input_schema genai_types.Schema( type=genai_types.Type.OBJECT, properties={ @@ -1118,7 +1118,7 @@ def compare_schemas(s1: genai_types.Schema, s2: genai_types.Schema) -> None: {'type': 'OBJECT', 'properties': {'user': {'$ref': '#/$defs/NonExistent'}}}, {'$defs': {'SomeOtherDef': {'type': 'STRING'}}}, ), - # Test Case 12: $ref with missing defs dict + # Test Case 12: $ref with root defaulting to input_schema ( {'type': 'OBJECT', 'properties': {'user': {'$ref': '#/$defs/NonExistent'}}}, None, @@ -1253,6 +1253,64 @@ def test_gemini_model__create_tool_drops_unconvertible_output_schema(gemini_mode ] +@pytest.mark.parametrize('output_schema', [{'type': 'array'}, {'description': 'anything'}]) +def test_gemini_model__create_tool_warns_on_output_schema_that_converts_to_none( + output_schema: dict[str, object], gemini_model_instance: GeminiModel +) -> None: + """A tool whose output schema converts to None is sent without one, with a warning.""" + tool = ToolDefinition(name='t', description='d', input_schema={'type': 'string'}, output_schema=output_schema) + + with capture_logs() as entries: + gemini_tool, _ = gemini_model_instance._create_tool(tool) + + declarations = gemini_tool.function_declarations + assert declarations is not None + assert declarations[0].response is None + assert [entry['event'] for entry in entries if entry['log_level'] == 'warning'] == [ + 'Sending tool t without its output schema, which cannot be converted' + ] + + +@pytest.mark.parametrize( + 'output_schema', + [ + {'type': 'string'}, + {'type': 'object', 'properties': {'value': {'type': 'integer'}, 'next': {'$ref': '#'}}, 'required': ['next']}, + ], +) +def test_gemini_model__create_tool_keeps_convertible_output_schema_without_warning( + output_schema: dict[str, object], gemini_model_instance: GeminiModel +) -> None: + """A tool whose output schema converts is sent with it and logs nothing, even when a property is left out.""" + tool = ToolDefinition(name='t', description='d', input_schema={'type': 'string'}, output_schema=output_schema) + + with capture_logs() as entries: + gemini_tool, _ = gemini_model_instance._create_tool(tool) + + declarations = gemini_tool.function_declarations + assert declarations is not None + assert declarations[0].response is not None + assert not [entry for entry in entries if entry['log_level'] == 'warning'] + + +@pytest.mark.parametrize('input_schema', [{'type': 'array'}, {'type': 'array', 'items': {'$ref': '#'}}]) +def test_gemini_model__create_tool_warns_on_input_schema_that_converts_to_none( + input_schema: dict[str, object], gemini_model_instance: GeminiModel +) -> None: + """A tool whose input schema converts to None is sent with no parameters, with a warning.""" + tool = ToolDefinition(name='t', description='d', input_schema=input_schema) + + with capture_logs() as entries: + gemini_tool, _ = gemini_model_instance._create_tool(tool) + + declarations = gemini_tool.function_declarations + assert declarations is not None + assert declarations[0].parameters == genai_types.Schema(type=genai_types.Type.OBJECT, properties={}) + assert [entry['event'] for entry in entries if entry['log_level'] == 'warning'] == [ + 'Sending tool t without its input schema, which cannot be converted' + ] + + def test_gemini_model__create_tool_rejects_unconvertible_input_schema(gemini_model_instance: GeminiModel) -> None: """A tool whose input schema cannot be converted still fails.""" tool = ToolDefinition( @@ -1310,7 +1368,8 @@ def test_gemini_model__create_tool_leaves_out_recursive_param(gemini_model_insta """A property that refers back to a model that contains it is left out.""" tool = ToolDefinition(name='t', description='d', input_schema=to_json_schema(_LinkedList)) - gemini_tool, _ = gemini_model_instance._create_tool(tool) + with capture_logs() as entries: + gemini_tool, _ = gemini_model_instance._create_tool(tool) declarations = gemini_tool.function_declarations assert declarations is not None @@ -1319,6 +1378,38 @@ def test_gemini_model__create_tool_leaves_out_recursive_param(gemini_model_insta required=['value'], properties={'value': genai_types.Schema(type=genai_types.Type.INTEGER)}, ) + assert not [entry for entry in entries if entry['log_level'] == 'warning'] + + +@pytest.mark.parametrize( + 'input_schema', + [ + to_json_schema(_RequiredLinkedList), + {'type': 'object', 'properties': {'value': {'type': 'integer'}, 'next': {'$ref': '#'}}, 'required': ['next']}, + { + 'type': 'object', + 'properties': {'value': {'type': 'integer'}, 'a': {'$ref': '#/$defs/N'}, 'b': {'$ref': '#/$defs/N'}}, + '$defs': {'N': {'type': 'object', 'properties': {'next': {'$ref': '#/$defs/N'}}, 'required': ['next']}}, + }, + ], +) +def test_gemini_model__create_tool_warns_on_required_recursive_param( + input_schema: dict[str, object], gemini_model_instance: GeminiModel +) -> None: + """A required property that refers back to a model that contains it is left out with one warning.""" + tool = ToolDefinition(name='t', description='d', input_schema=input_schema) + + with capture_logs() as entries: + gemini_tool, _ = gemini_model_instance._create_tool(tool) + + declarations = gemini_tool.function_declarations + assert declarations is not None + assert declarations[0].parameters is not None + assert 'next' not in (declarations[0].parameters.properties or {}) + assert 'next' not in (declarations[0].parameters.required or []) + assert [entry['event'] for entry in entries if entry['log_level'] == 'warning'] == [ + 'Sending tool t without required properties next, which cannot be converted' + ] @pytest.mark.parametrize('model', [_Tree, _OptionalTree, _Grid]) @@ -1369,11 +1460,12 @@ def test_gemini_model__convert_schema_property_strict_rejects_required_recursive gemini_model_instance: GeminiModel, ) -> None: """In strict mode a required recursive property cannot be left out, so it raises naming the property.""" - with pytest.raises(GenkitError) as exc_info: + with capture_logs() as entries, pytest.raises(GenkitError) as exc_info: gemini_model_instance._convert_schema_property(to_json_schema(_RequiredLinkedList), strict=True) assert exc_info.value.status == 'INVALID_ARGUMENT' assert 'next' in exc_info.value.message + assert not [entry for entry in entries if entry['log_level'] == 'warning'] @pytest.mark.parametrize(