@devries-cameron20 / composio-1 / commits / 2f8820fca
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(gemini): run optional and constrained arguments through AFC again

#4316 built the Gemini validation model with skip_default=True, so every optional argument became required, and gave the signature Annotated and Dict[str, Any] annotations. google-genai's automatic function calling converts arguments with isinstance on those annotations, which raises for enums, patterns, bounds, anyOf, const, free-form objects and arrays of objects. Build the validation model with defaults, hand AFC plain annotations (the declarations match the ones from before #4316), and serialize AFC's models with exclude_unset and aliases so omitted nested fields are not sent as null.

jkomyno committed Sep 29, 2026 at 15:05 UTC 2f8820fcad428fbd81052571316f66e3eee0236d
2 files changed +163 -13
python/providers/gemini/composio_gemini/provider.py
+41 -10
@@ -42,12 +42,15 @@ def _to_serializable(value: t.Any) -> t.Any:
42 the Composio ``execute_tool`` call fails. This helper normalises them back
43 to plain Python primitives before handing off to the API.
44 """
45 + # Only fields the model returned: AFC fills omitted optional fields with
46 + # ``None``, which the tool schema may not allow. Aliases restore reserved
47 + # names such as ``from``.
48 # Pydantic v2 BaseModel
49 if hasattr(value, "model_dump"):
47 - return value.model_dump()
50 + return value.model_dump(exclude_unset=True, by_alias=True)
51 # Pydantic v1 BaseModel
52 if hasattr(value, "dict") and hasattr(value, "__fields__"):
50 - return value.dict()
53 + return value.dict(exclude_unset=True, by_alias=True)
54 if isinstance(value, dict):
55 return {k: _to_serializable(v) for k, v in value.items()}
56 if isinstance(value, (list, tuple)):
@@ -55,6 +58,31 @@ def _to_serializable(value: t.Any) -> t.Any:
58 return value
59
60
61 +def _afc_annotation(annotation: t.Any) -> t.Any:
62 + """Return an annotation google-genai AFC can convert arguments with.
63 +
64 + AFC reads the callable's signature both to declare the function and to
65 + convert the arguments the model returns, and the conversion calls
66 + ``isinstance`` with the annotation. That raises on ``Annotated[...]``,
67 + parameterized ``Dict`` and ``typing.Any``, so any tool using them failed
68 + before it ran. The plain annotations declare the same function; the source
69 + schema is still enforced by ``args_schema``.
70 + """
71 + origin = t.get_origin(annotation)
72 + args = t.get_args(annotation)
73 + if origin is t.Annotated:
74 + return _afc_annotation(args[0])
75 + if origin is list and args:
76 + return t.List[_afc_annotation(args[0])] # type: ignore[misc]
77 + if origin is dict:
78 + return dict
79 + if origin in (t.Union, pytypes.UnionType):
80 + return t.Union[tuple(_afc_annotation(arg) for arg in args)]
81 + if annotation is t.Any:
82 + return object
83 + return annotation
84 +
85 +
86 def _process_execution_result(result: t.Any) -> t.Dict:
87 """Process a tool execution result into a dict suitable for Gemini function responses."""
88 if not isinstance(result, dict):
@@ -105,10 +133,10 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
133 2. Store it in the AFC ``function_map`` for automatic execution
134 """
135 aliases = alias_tool_input_schema(schema=tool.input_parameters)
108 - args_schema = json_schema_to_model(
109 - aliases.schema,
110 - skip_default=self.skip_default,
111 - )
136 + # Defaults stay out of the function declaration (see below), but the
137 + # validation model needs them: without a default every optional field
138 + # would be required.
139 + args_schema = json_schema_to_model(aliases.schema, skip_default=False)
140 self._executors[tool.slug] = (execute_tool, aliases, args_schema)
141
142 def function(**kwargs: t.Any) -> t.Dict:
@@ -137,10 +165,13 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
165 # parameterized generics (e.g. List[str] instead of bare List).
166 # The google-genai SDK requires parameterized array types — bare List
167 # generates {"type": "ARRAY"} without "items", which the API rejects.
140 - sig_params = get_pydantic_signature_format_from_schema_params(
141 - schema_params=aliases.schema,
142 - skip_default=True,
143 - )
168 + sig_params = [
169 + param.replace(annotation=_afc_annotation(param.annotation))
170 + for param in get_pydantic_signature_format_from_schema_params(
171 + schema_params=aliases.schema,
172 + skip_default=True,
173 + )
174 + ]
175 action_func.__signature__ = Signature(parameters=sig_params) # type: ignore
176 action_func.__doc__ = tool.description or f"Execute {tool.slug}"
177
python/tests/test_gemini_provider.py
+122 -3
@@ -10,7 +10,6 @@ Verifies:
10 """
11
12 import inspect
13 -import typing as t
13 from unittest.mock import MagicMock, Mock
14
15 import pytest
@@ -194,8 +193,10 @@ class TestWrapTool:
193 result = provider.wrap_tool(tool, create_mock_execute_tool())
194 parameter = inspect.signature(result).parameters["payload"]
195
197 - assert parameter.annotation == t.Dict[str, t.Any] # noqa: UP006
198 - assert result.__annotations__["payload"] == t.Dict[str, t.Any] # noqa: UP006
196 + # Plain `dict`: AFC calls `isinstance` with each value's annotation, and
197 + # `Dict[str, Any]` makes that raise for every nested value.
198 + assert parameter.annotation is dict
199 + assert result.__annotations__["payload"] is dict
200
201 def test_callable_has_annotations(self):
202 from composio_gemini import GeminiProvider
@@ -585,6 +586,124 @@ class TestAFCCompatibility:
586 function_map[func.__name__] = func
587 assert "GITHUB_STAR_REPO" in function_map
588
589 + @pytest.mark.parametrize(
590 + ("properties", "required", "arguments"),
591 + [
592 + (
593 + {"query": {"type": "string"}, "max_results": {"type": "integer"}},
594 + ["query"],
595 + {"query": "is:unread"},
596 + ),
597 + (
598 + {"order": {"type": "string", "enum": ["asc", "desc"]}},
599 + ["order"],
600 + {"order": "asc"},
601 + ),
602 + (
603 + {"slug": {"type": "string", "pattern": "^[a-z_]+$"}},
604 + ["slug"],
605 + {"slug": "a_b"},
606 + ),
607 + ({"n": {"type": "integer", "minimum": 1}}, ["n"], {"n": 3}),
608 + (
609 + {"v": {"anyOf": [{"type": "integer"}, {"type": "string"}]}},
610 + ["v"],
611 + {"v": "x"},
612 + ),
613 + ({"meta": {"type": "object"}}, ["meta"], {"meta": {"x": {"y": 1}}}),
614 + ({"c": {"const": "fixed"}}, ["c"], {"c": "fixed"}),
615 + (
616 + {
617 + "body": {
618 + "type": "object",
619 + "properties": {
620 + "a": {"type": "string"},
621 + "b": {"type": "integer"},
622 + },
623 + "required": ["a"],
624 + }
625 + },
626 + ["body"],
627 + {"body": {"a": "x"}},
628 + ),
629 + (
630 + {
631 + "items": {
632 + "type": "array",
633 + "items": {
634 + "type": "object",
635 + "properties": {
636 + "k": {"type": "string"},
637 + "v": {"type": "string"},
638 + },
639 + "required": ["k"],
640 + },
641 + }
642 + },
643 + ["items"],
644 + {"items": [{"k": "a"}, {"k": "b", "v": "c"}]},
645 + ),
646 + ],
647 + ids=[
648 + "omitted-optional",
649 + "enum",
650 + "pattern",
651 + "minimum",
652 + "any-of",
653 + "free-form-object",
654 + "const",
655 + "nested-omitted-optional",
656 + "array-of-objects",
657 + ],
658 + )
659 + def test_afc_executes_arguments_as_returned(self, properties, required, arguments):
660 + """AFC converts each argument with its annotation before calling the tool."""
661 + from composio_gemini import GeminiProvider
662 + from google import genai
663 + from google.genai import _extra_utils
664 +
665 + provider = GeminiProvider()
666 + tool = create_mock_tool(
667 + "AFC_TOOL",
668 + "test",
669 + input_parameters={
670 + "type": "object",
671 + "properties": properties,
672 + "required": required,
673 + },
674 + )
675 + execute_tool = create_mock_execute_tool()
676 + func = provider.wrap_tool(tool, execute_tool)
677 +
678 + client = genai.Client(api_key="test")
679 + genai_types.FunctionDeclaration.from_callable(
680 + client=client._api_client, callable=func
681 + )
682 + _extra_utils.invoke_function_from_dict_args(arguments, func)
683 +
684 + execute_tool.assert_called_once_with("AFC_TOOL", arguments)
685 +
686 + def test_afc_still_validates_the_source_schema(self):
687 + from composio_gemini import GeminiProvider
688 + from google.genai import _extra_utils, errors
689 +
690 + provider = GeminiProvider()
691 + tool = create_mock_tool(
692 + "AFC_TOOL",
693 + "test",
694 + input_parameters={
695 + "type": "object",
696 + "properties": {"slug": {"type": "string", "pattern": "^[a-z_]+$"}},
697 + "required": ["slug"],
698 + },
699 + )
700 + execute_tool = create_mock_execute_tool()
701 + func = provider.wrap_tool(tool, execute_tool)
702 +
703 + with pytest.raises(errors.FunctionInvocationError):
704 + _extra_utils.invoke_function_from_dict_args({"slug": "Not Valid"}, func)
705 + execute_tool.assert_not_called()
706 +
707 def test_callables_in_generate_content_config(self):
708 """Wrapped callables can be passed to GenerateContentConfig without error."""
709 from composio_gemini import GeminiProvider