@devries-cameron20 / composio-1 / commits / 2665be5b6
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(py): gemini for Tool Router

jkomyno committed Feb 6, 2026 at 03:37 UTC 2665be5b6a1dead33fb2ebdd7322fed79a4c43ff
3 files changed +746 -199
python/config/pytest.ini
+1
@@ -5,3 +5,4 @@ markers =
5 openai: marks tests that check the OpenAIProvider
6 langchain: marks tests that check the LangChainProvider
7 agno: marks tests that check the AgnoProvider
8 + gemini: marks tests that check the GeminiProvider
python/providers/gemini/composio_gemini/provider.py
+158 -199
@@ -1,12 +1,20 @@
1 -"""Gemini provider for Composio SDK."""
1 +"""Gemini provider for Composio SDK.
2
3 +Returns Python callables compatible with google-genai's Automatic Function
4 +Calling (AFC). The SDK can introspect the callable's signature to derive
5 +FunctionDeclaration schemas and auto-execute tool calls in the chat loop.
6 +"""
7 +
8 +import types as pytypes
9 import typing as t
10 +from inspect import Parameter, Signature
11
12 from composio.client.types import Tool
13 from composio.core.provider import AgenticProvider
14 from composio.core.provider.agentic import AgenticProviderExecuteFn
15 +from composio.utils.shared import get_pydantic_signature_format_from_schema_params
16
9 -# Try to import Google GenAI types
17 +# google-genai is only needed for handle_response (backward compat)
18 try:
19 from google.genai import types as genai_types
20
@@ -15,219 +23,180 @@ except ImportError:
23 genai_types = None # type: ignore
24 HAS_GENAI = False
25
26 +_python_reserved = {"for", "async"}
27
19 -class GeminiTool:
20 - """
21 - Enhanced Gemini Tool wrapper that handles automatic function execution.
22 - Acts as a drop-in replacement for genai_types.Tool with execution support.
23 - """
28
25 - def __init__(
26 - self,
27 - tool: Tool,
28 - execute_tool: AgenticProviderExecuteFn,
29 - function_declaration: t.Optional[t.Any] = None,
30 - ):
31 - self.tool = tool
32 - self.execute_tool = execute_tool
33 - self.function_declaration = function_declaration
34 -
35 - # Create the actual Gemini Tool if we have genai support
36 - self._genai_tool = None
37 - if HAS_GENAI and function_declaration:
38 - self._genai_tool = genai_types.Tool(
39 - function_declarations=[function_declaration]
40 - )
41 -
42 - # Store executor for easy access
43 - self._executors = {tool.slug: self}
29 +def _clean_reserved_keyword(keyword: str) -> str:
30 + return f"{keyword}_rs"
31
45 - # Copy function attributes for compatibility
46 - self.__name__ = tool.slug
47 - self.__module__ = "composio_gemini"
48 - self.__doc__ = tool.description
32
50 - def __call__(self, **kwargs: t.Any) -> t.Dict:
51 - """Execute the tool when called."""
52 - result = self.execute_tool(slug=self.tool.slug, arguments=kwargs)
33 +def _substitute_reserved_python_keywords(schema: t.Dict) -> t.Tuple[dict, dict]:
34 + if "properties" not in schema:
35 + return schema, {}
36
54 - # Process the result for Gemini
55 - if not isinstance(result, dict):
56 - return {"result": result}
37 + keywords: t.Dict[str, str] = {}
38 + for p_name in list(schema["properties"]):
39 + if p_name not in _python_reserved:
40 + continue
41
58 - # Extract data field if present and successful
59 - if result.get("successful", True) and "data" in result:
60 - data = result["data"]
61 - return data if isinstance(data, dict) else {"result": data}
42 + p_val = schema["properties"].pop(p_name)
43 + p_name_clean = _clean_reserved_keyword(keyword=p_name)
44 + schema["properties"][p_name_clean] = p_val
45 + keywords[p_name_clean] = p_name
46
63 - # Return error info if failed
64 - if not result.get("successful", True):
65 - return {
66 - "error": result.get("error", "Tool execution failed"),
67 - "details": result,
68 - }
47 + return schema, keywords
48
70 - return result
49
72 - @property
73 - def function_declarations(self):
74 - """Pass through to the underlying Gemini tool."""
75 - return self._genai_tool.function_declarations if self._genai_tool else []
50 +def _reinstate_reserved_python_keywords(request: dict, keywords: dict) -> dict:
51 + for clean_key, original_key in keywords.items():
52 + if clean_key not in request:
53 + continue
54 + request[original_key] = request.pop(clean_key)
55 + return request
56
77 - def to_dict(self):
78 - """Convert to dict for Gemini API."""
79 - return self._genai_tool.to_dict() if self._genai_tool else {}
57
58 +def _to_serializable(value: t.Any) -> t.Any:
59 + """Recursively convert Pydantic models (and other non-JSON types) to plain dicts/lists.
60
82 -class GeminiProvider(AgenticProvider[t.Any, list[t.Any]], name="gemini"):
83 - """
84 - Composio toolset for Google AI Python Gemini framework.
85 - Supports automatic function calling with native Gemini tools.
61 + The google-genai SDK's AFC pipeline calls ``convert_if_exist_pydantic_model``
62 + on function arguments, turning nested dicts into dynamically-generated
63 + Pydantic ``GeneratedModel`` instances. These are not JSON-serializable, so
64 + the Composio ``execute_tool`` call fails. This helper normalises them back
65 + to plain Python primitives before handing off to the API.
66 """
67 + # Pydantic v2 BaseModel
68 + if hasattr(value, "model_dump"):
69 + return value.model_dump()
70 + # Pydantic v1 BaseModel
71 + if hasattr(value, "dict") and hasattr(value, "__fields__"):
72 + return value.dict()
73 + if isinstance(value, dict):
74 + return {k: _to_serializable(v) for k, v in value.items()}
75 + if isinstance(value, (list, tuple)):
76 + return [_to_serializable(v) for v in value]
77 + return value
78 +
79 +
80 +def _process_execution_result(result: t.Any) -> t.Dict:
81 + """Process a tool execution result into a dict suitable for Gemini function responses."""
82 + if not isinstance(result, dict):
83 + return {"result": result}
84 +
85 + if result.get("successful", True) and "data" in result:
86 + data = result["data"]
87 + return data if isinstance(data, dict) else {"result": data}
88 +
89 + if not result.get("successful", True):
90 + return {
91 + "error": result.get("error", "Tool execution failed"),
92 + "details": result,
93 + }
94
88 - __schema_skip_defaults__ = True
95 + return result
96
90 - def _json_to_genai_schema(self, json_schema: dict) -> t.Optional[t.Any]:
91 - """Convert JSON Schema to GenAI Schema format, handling composite types."""
92 - if not HAS_GENAI:
93 - return None
94 -
95 - # Handle composite types (patterns from openapi.py)
96 - if "oneOf" in json_schema:
97 - # Gemini doesn't support unions directly, use first valid schema
98 - # This is a limitation but better than failing
99 - return self._json_to_genai_schema(json_schema["oneOf"][0])
100 -
101 - if "anyOf" in json_schema:
102 - # Similar to oneOf
103 - return self._json_to_genai_schema(json_schema["anyOf"][0])
104 -
105 - if "allOf" in json_schema:
106 - # Merge all schemas (pattern from openapi.py's _all_of_to_parameter)
107 - merged = {}
108 - for subschema in json_schema["allOf"]:
109 - merged.update(subschema)
110 - return self._json_to_genai_schema(merged)
111 -
112 - # Handle enum independently (can appear with or without type)
113 - if "enum" in json_schema:
114 - return self._handle_enum_schema(json_schema)
115 -
116 - schema_type = json_schema.get("type", "string")
117 -
118 - # Map type handlers
119 - type_handlers = {
120 - "array": self._handle_array_schema,
121 - "object": self._handle_object_schema,
122 - "string": self._handle_string_schema,
123 - "number": lambda _: genai_types.Schema(type=genai_types.Type.NUMBER),
124 - "integer": lambda _: genai_types.Schema(type=genai_types.Type.INTEGER),
125 - "boolean": lambda _: genai_types.Schema(type=genai_types.Type.BOOLEAN),
126 - "null": lambda _: genai_types.Schema(
127 - type=genai_types.Type.STRING
128 - ), # Gemini doesn't have null type
129 - }
97
131 - handler = type_handlers.get(
132 - schema_type, lambda _: genai_types.Schema(type=genai_types.Type.STRING)
133 - )
134 - return handler(json_schema)
135 -
136 - def _handle_array_schema(self, json_schema: dict) -> t.Any:
137 - """Handle array type schema conversion."""
138 - items = json_schema.get("items", {})
139 - return genai_types.Schema(
140 - type=genai_types.Type.ARRAY,
141 - items=self._json_to_genai_schema(items)
142 - if items
143 - else genai_types.Schema(type=genai_types.Type.STRING),
144 - )
98 +class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini"):
99 + """Composio toolset for Google AI Python Gemini framework.
100
146 - def _handle_object_schema(self, json_schema: dict) -> t.Any:
147 - """Handle object type schema conversion."""
148 - properties = {
149 - name: schema_obj
150 - for name, schema in json_schema.get("properties", {}).items()
151 - if (schema_obj := self._json_to_genai_schema(schema)) is not None
152 - }
153 - return genai_types.Schema(
154 - type=genai_types.Type.OBJECT,
155 - properties=properties,
156 - required=json_schema.get("required", []),
157 - )
101 + Returns Python callables compatible with google-genai's Automatic Function
102 + Calling (AFC). Pass the result of ``wrap_tools()`` directly to
103 + ``GenerateContentConfig(tools=...)`` and the SDK will auto-execute tool
104 + calls in the ``chat.send_message()`` loop.
105 + """
106
159 - def _handle_string_schema(self, json_schema: dict) -> t.Any:
160 - """Handle string type schema conversion."""
161 - if enum_values := json_schema.get("enum"):
162 - return genai_types.Schema(type=genai_types.Type.STRING, enum=enum_values)
163 - return genai_types.Schema(type=genai_types.Type.STRING)
164 -
165 - def _handle_enum_schema(self, json_schema: dict) -> t.Any:
166 - """Handle enum schema conversion (pattern from openapi.py)."""
167 - # Enum can be of any type, default to string if no type specified
168 - base_type = json_schema.get("type", "string")
169 - type_map = {
170 - "string": genai_types.Type.STRING,
171 - "integer": genai_types.Type.INTEGER,
172 - "number": genai_types.Type.NUMBER,
173 - }
174 - schema_type = type_map.get(base_type, genai_types.Type.STRING)
175 - return genai_types.Schema(type=schema_type, enum=json_schema["enum"])
107 + __schema_skip_defaults__ = True
108
177 - def _create_function_declaration(self, tool: Tool) -> t.Optional[t.Any]:
178 - """Create a native Gemini FunctionDeclaration if possible."""
179 - if not HAS_GENAI:
180 - return None
181 -
182 - try:
183 - genai_schema = self._json_to_genai_schema(tool.input_parameters)
184 - return genai_types.FunctionDeclaration(
185 - name=tool.slug,
186 - description=tool.description or f"Execute {tool.slug}",
187 - parameters=genai_schema,
188 - )
189 - except Exception as e:
190 - print(f"Warning: Could not create FunctionDeclaration for {tool.slug}: {e}")
191 - return None
109 + def __init__(self, **kwargs: t.Any):
110 + super().__init__(**kwargs)
111 + self._executors: t.Dict[str, AgenticProviderExecuteFn] = {}
112
113 def wrap_tool(
114 self,
115 tool: Tool,
116 execute_tool: AgenticProviderExecuteFn,
197 - ) -> GeminiTool:
198 - """Wrap a Composio tool for Gemini compatibility."""
199 - # Create native FunctionDeclaration
200 - function_declaration = self._create_function_declaration(tool)
201 -
202 - # Return the GeminiTool wrapper
203 - return GeminiTool(
204 - tool=tool,
205 - execute_tool=execute_tool,
206 - function_declaration=function_declaration,
117 + ) -> t.Callable:
118 + """Wrap a Composio tool as a Python callable for google-genai AFC.
119 +
120 + The returned function has ``__name__``, ``__doc__``, ``__signature__``
121 + and ``__annotations__`` set so the google-genai SDK can:
122 +
123 + 1. Derive a ``FunctionDeclaration`` schema via ``from_callable()``
124 + 2. Store it in the AFC ``function_map`` for automatic execution
125 + """
126 + self._executors[tool.slug] = execute_tool
127 +
128 + # Handle reserved Python keywords in parameter names
129 + schema_params, keywords = _substitute_reserved_python_keywords(
130 + schema=tool.input_parameters
131 + )
132 +
133 + def function(**kwargs: t.Any) -> t.Dict:
134 + """Composio tool execution wrapper."""
135 + kwargs = _to_serializable(kwargs)
136 + kwargs = _reinstate_reserved_python_keywords(
137 + request=kwargs, keywords=keywords
138 + )
139 + result = execute_tool(tool.slug, kwargs)
140 + return _process_execution_result(result)
141 +
142 + # Create a real function object (passes inspect.isfunction)
143 + action_func = pytypes.FunctionType(
144 + function.__code__,
145 + globals=globals(),
146 + name=tool.slug,
147 + closure=function.__closure__,
148 + )
149 +
150 + # Build typed signature from JSON schema.
151 + # Uses get_pydantic_signature_format_from_schema_params (not
152 + # get_signature_format_from_schema_params) because the pydantic variant
153 + # goes through json_schema_to_pydantic_type() which produces
154 + # parameterized generics (e.g. List[str] instead of bare List).
155 + # The google-genai SDK requires parameterized array types — bare List
156 + # generates {"type": "ARRAY"} without "items", which the API rejects.
157 + sig_params = get_pydantic_signature_format_from_schema_params(
158 + schema_params=schema_params,
159 + skip_default=True,
160 )
161 + action_func.__signature__ = Signature(parameters=sig_params) # type: ignore
162 + action_func.__doc__ = tool.description or f"Execute {tool.slug}"
163 +
164 + # Build __annotations__ for typing.get_type_hints() compatibility
165 + annotations: t.Dict[str, t.Any] = {}
166 + for param in sig_params:
167 + if param.annotation is not Parameter.empty:
168 + annotations[param.name] = param.annotation
169 + annotations["return"] = dict
170 + action_func.__annotations__ = annotations
171 +
172 + return action_func
173
174 def wrap_tools(
175 self,
176 tools: t.Sequence[Tool],
177 execute_tool: AgenticProviderExecuteFn,
213 - ) -> list[GeminiTool]:
214 - """Wrap multiple tools for Gemini compatibility."""
178 + ) -> list[t.Callable]:
179 + """Wrap multiple Composio tools as Python callables for google-genai AFC."""
180 return [self.wrap_tool(tool, execute_tool) for tool in tools]
181
217 - @staticmethod
218 - def handle_response(response, tools: list[GeminiTool]) -> tuple[list, bool]:
219 - """
220 - Automatically handle function calls in a Gemini response.
182 + # --- Backward compatibility: manual function calling ---
183
222 - Args:
223 - response: The response from Gemini chat
224 - tools: The list of GeminiTool objects passed to the chat
184 + def handle_response(self, response: t.Any) -> tuple[list, bool]:
185 + """Manually handle function calls in a Gemini response.
186 +
187 + Provided for backward compatibility with code that uses manual function
188 + calling instead of AFC. For new code, pass the callables from
189 + ``wrap_tools()`` to ``GenerateContentConfig(tools=...)`` and AFC will
190 + handle execution automatically.
191
192 Returns:
227 - tuple: (function_responses, executed) where function_responses are ready
228 - to send back and executed is True if functions were executed
193 + tuple: ``(function_responses, executed)`` where *function_responses*
194 + are ``genai_types.Part`` objects ready to send back, and *executed*
195 + is ``True`` if any functions were executed.
196 """
230 - # Check if we have a valid response with candidates
197 + if not HAS_GENAI:
198 + return [], False
199 +
200 if not (hasattr(response, "candidates") and response.candidates):
201 return [], False
202
@@ -235,14 +204,7 @@ class GeminiProvider(AgenticProvider[t.Any, list[t.Any]], name="gemini"):
204 if not (hasattr(candidate, "content") and candidate.content.parts):
205 return [], False
206
238 - # Build executor map from tools
239 - executors = {}
240 - for tool in tools:
241 - if isinstance(tool, GeminiTool):
242 - executors.update(tool._executors)
243 -
244 - # Process function calls
245 - function_responses = []
207 + function_responses: list = []
208 executed = False
209
210 for part in candidate.content.parts:
@@ -250,22 +212,19 @@ class GeminiProvider(AgenticProvider[t.Any, list[t.Any]], name="gemini"):
212 continue
213
214 fc = part.function_call
253 - if fc.name not in executors:
215 + if fc.name not in self._executors:
216 continue
217
256 - # Execute the function
257 - executor = executors[fc.name]
258 - result = executor(**fc.args)
259 -
260 - # Create function response
261 - if HAS_GENAI:
262 - function_responses.append(
263 - genai_types.Part(
264 - function_response=genai_types.FunctionResponse(
265 - name=fc.name, response=result
266 - )
218 + result = self._executors[fc.name](slug=fc.name, arguments=dict(fc.args))
219 + processed = _process_execution_result(result)
220 +
221 + function_responses.append(
222 + genai_types.Part(
223 + function_response=genai_types.FunctionResponse(
224 + name=fc.name, response=processed
225 )
226 )
227 + )
228 executed = True
229
230 return function_responses, executed
python/tests/test_gemini_provider.py new
+587
@@ -0,0 +1,587 @@
1 +"""Test Gemini provider functionality.
2 +
3 +Verifies:
4 +- Provider initialization and attributes
5 +- wrap_tool returns Python callables with correct metadata
6 +- wrap_tools returns list of callables
7 +- Callables are AFC-compatible (work with google-genai's function map)
8 +- handle_response dispatches function calls via stored executors (backward compat)
9 +- _process_execution_result helper
10 +"""
11 +
12 +import inspect
13 +from unittest.mock import MagicMock, Mock
14 +
15 +import pytest
16 +
17 +from composio.client.types import Tool, tool_list_response
18 +from composio.core.models.base import allow_tracking
19 +from composio.core.provider import AgenticProvider
20 +
21 +try:
22 + from google.genai import types as genai_types
23 +
24 + HAS_GENAI = True
25 +except ImportError:
26 + genai_types = None
27 + HAS_GENAI = False
28 +
29 +pytestmark = pytest.mark.gemini
30 +
31 +requires_genai = pytest.mark.skipif(
32 + not HAS_GENAI, reason="google-genai package not installed"
33 +)
34 +
35 +
36 +@pytest.fixture(autouse=True)
37 +def disable_telemetry():
38 + """Disable telemetry for all tests to prevent thread issues."""
39 + token = allow_tracking.set(False)
40 + yield
41 + allow_tracking.reset(token)
42 +
43 +
44 +def create_mock_tool(
45 + slug: str,
46 + toolkit_slug: str,
47 + version: str = "12012025_00",
48 + input_parameters: dict | None = None,
49 + description: str = "Test tool for provider testing",
50 +) -> Tool:
51 + """Create a mock tool for testing."""
52 + return Tool(
53 + name=f"Test {slug}",
54 + slug=slug,
55 + description=description,
56 + input_parameters=input_parameters
57 + or {"type": "object", "properties": {}, "required": []},
58 + output_parameters={},
59 + available_versions=[version],
60 + version=version,
61 + scopes=[],
62 + status="active",
63 + toolkit=tool_list_response.ItemToolkit(
64 + name=toolkit_slug.title(), slug=toolkit_slug, logo=""
65 + ),
66 + deprecated=tool_list_response.ItemDeprecated(
67 + available_versions=[version],
68 + displayName=f"Test {slug}",
69 + version=version,
70 + toolkit=tool_list_response.ItemDeprecatedToolkit(logo=""),
71 + is_deprecated=False,
72 + ),
73 + is_deprecated=False,
74 + no_auth=False,
75 + tags=[],
76 + )
77 +
78 +
79 +def create_mock_execute_tool():
80 + """Create a mock execute_tool function matching AgenticProviderExecuteFn."""
81 + mock_fn = Mock()
82 + mock_fn.return_value = {
83 + "data": {"result": "success"},
84 + "error": None,
85 + "successful": True,
86 + }
87 + return mock_fn
88 +
89 +
90 +# ---------------------------------------------------------------------------
91 +# Initialization
92 +# ---------------------------------------------------------------------------
93 +
94 +
95 +class TestGeminiProviderInitialization:
96 + def test_initialization(self):
97 + from composio_gemini import GeminiProvider
98 +
99 + provider = GeminiProvider()
100 + assert provider is not None
101 + assert provider.name == "gemini"
102 + assert isinstance(provider, AgenticProvider)
103 +
104 + def test_has_empty_executors_on_init(self):
105 + from composio_gemini import GeminiProvider
106 +
107 + provider = GeminiProvider()
108 + assert provider._executors == {}
109 +
110 +
111 +# ---------------------------------------------------------------------------
112 +# wrap_tool – callable creation
113 +# ---------------------------------------------------------------------------
114 +
115 +
116 +class TestWrapTool:
117 + def test_returns_callable(self):
118 + from composio_gemini import GeminiProvider
119 +
120 + provider = GeminiProvider()
121 + tool = create_mock_tool("GITHUB_STAR_REPO", "github")
122 + result = provider.wrap_tool(tool, create_mock_execute_tool())
123 + assert callable(result)
124 + assert inspect.isfunction(result)
125 +
126 + def test_callable_has_correct_name(self):
127 + from composio_gemini import GeminiProvider
128 +
129 + provider = GeminiProvider()
130 + tool = create_mock_tool("GITHUB_STAR_REPO", "github")
131 + result = provider.wrap_tool(tool, create_mock_execute_tool())
132 + assert result.__name__ == "GITHUB_STAR_REPO"
133 +
134 + def test_callable_has_correct_doc(self):
135 + from composio_gemini import GeminiProvider
136 +
137 + provider = GeminiProvider()
138 + tool = create_mock_tool(
139 + "GITHUB_STAR_REPO", "github", description="Star a GitHub repository"
140 + )
141 + result = provider.wrap_tool(tool, create_mock_execute_tool())
142 + assert result.__doc__ == "Star a GitHub repository"
143 +
144 + def test_callable_has_typed_signature(self):
145 + from composio_gemini import GeminiProvider
146 +
147 + provider = GeminiProvider()
148 + tool = create_mock_tool(
149 + "GITHUB_CREATE_ISSUE",
150 + "github",
151 + input_parameters={
152 + "type": "object",
153 + "properties": {
154 + "title": {"type": "string"},
155 + "body": {"type": "string"},
156 + },
157 + "required": ["title"],
158 + },
159 + )
160 + result = provider.wrap_tool(tool, create_mock_execute_tool())
161 +
162 + sig = inspect.signature(result)
163 + assert "title" in sig.parameters
164 + assert "body" in sig.parameters
165 + assert sig.parameters["title"].annotation is str
166 + assert sig.parameters["body"].annotation is str
167 +
168 + def test_callable_has_annotations(self):
169 + from composio_gemini import GeminiProvider
170 +
171 + provider = GeminiProvider()
172 + tool = create_mock_tool(
173 + "TEST_TOOL",
174 + "test",
175 + input_parameters={
176 + "type": "object",
177 + "properties": {"name": {"type": "string"}},
178 + "required": ["name"],
179 + },
180 + )
181 + result = provider.wrap_tool(tool, create_mock_execute_tool())
182 +
183 + assert "name" in result.__annotations__
184 + assert result.__annotations__["name"] is str
185 + assert result.__annotations__["return"] is dict
186 +
187 + def test_stores_executor(self):
188 + from composio_gemini import GeminiProvider
189 +
190 + provider = GeminiProvider()
191 + tool = create_mock_tool("GITHUB_STAR_REPO", "github")
192 + execute_tool = create_mock_execute_tool()
193 + provider.wrap_tool(tool, execute_tool)
194 +
195 + assert "GITHUB_STAR_REPO" in provider._executors
196 + assert provider._executors["GITHUB_STAR_REPO"] is execute_tool
197 +
198 + def test_callable_executes_correctly(self):
199 + from composio_gemini import GeminiProvider
200 +
201 + provider = GeminiProvider()
202 + tool = create_mock_tool(
203 + "MY_TOOL",
204 + "test",
205 + input_parameters={
206 + "type": "object",
207 + "properties": {"query": {"type": "string"}},
208 + "required": ["query"],
209 + },
210 + )
211 + execute_tool = create_mock_execute_tool()
212 + func = provider.wrap_tool(tool, execute_tool)
213 +
214 + result = func(query="hello")
215 + execute_tool.assert_called_once_with("MY_TOOL", {"query": "hello"})
216 + # _process_execution_result extracts data when successful
217 + assert result == {"result": "success"}
218 +
219 + def test_callable_processes_error_result(self):
220 + from composio_gemini import GeminiProvider
221 +
222 + provider = GeminiProvider()
223 + tool = create_mock_tool(
224 + "MY_TOOL",
225 + "test",
226 + input_parameters={
227 + "type": "object",
228 + "properties": {"q": {"type": "string"}},
229 + "required": [],
230 + },
231 + )
232 + execute_tool = Mock()
233 + execute_tool.return_value = {
234 + "data": {},
235 + "error": "Auth failed",
236 + "successful": False,
237 + }
238 + func = provider.wrap_tool(tool, execute_tool)
239 + result = func(q="test")
240 + assert result["error"] == "Auth failed"
241 +
242 + def test_callable_converts_pydantic_args_to_dicts(self):
243 + """AFC may pass Pydantic GeneratedModel instances as kwargs; they must be
244 + converted to plain dicts before reaching execute_tool so the Composio
245 + API can JSON-serialize them.
246 + """
247 + from pydantic import BaseModel
248 +
249 + from composio_gemini import GeminiProvider
250 +
251 + class FakeQuery(BaseModel):
252 + use_case: str = ""
253 + known_fields: str = ""
254 +
255 + provider = GeminiProvider()
256 + tool = create_mock_tool(
257 + "COMPOSIO_SEARCH_TOOLS",
258 + "composio",
259 + input_parameters={
260 + "type": "object",
261 + "properties": {
262 + "queries": {
263 + "type": "array",
264 + "items": {
265 + "type": "object",
266 + "title": "Query",
267 + "properties": {
268 + "use_case": {"type": "string"},
269 + "known_fields": {"type": "string"},
270 + },
271 + },
272 + },
273 + },
274 + "required": [],
275 + },
276 + )
277 + execute_tool = create_mock_execute_tool()
278 + func = provider.wrap_tool(tool, execute_tool)
279 +
280 + # Simulate what the SDK does: pass Pydantic model instances
281 + func(queries=[FakeQuery(use_case="summarize email")])
282 +
283 + call_args = execute_tool.call_args[0][1]
284 + # The queries value must be a plain list of dicts, not Pydantic models
285 + assert isinstance(call_args["queries"], list)
286 + assert isinstance(call_args["queries"][0], dict)
287 + assert call_args["queries"][0]["use_case"] == "summarize email"
288 +
289 + def test_array_param_has_parameterized_type(self):
290 + """Array parameters must produce List[X], not bare List.
291 +
292 + The google-genai SDK rejects bare List because it generates
293 + {"type": "ARRAY"} without "items".
294 + """
295 + import typing
296 +
297 + from composio_gemini import GeminiProvider
298 +
299 + provider = GeminiProvider()
300 + tool = create_mock_tool(
301 + "TOOL_WITH_ARRAY",
302 + "test",
303 + input_parameters={
304 + "type": "object",
305 + "properties": {
306 + "tags": {"type": "array", "items": {"type": "string"}},
307 + "name": {"type": "string"},
308 + },
309 + "required": ["name"],
310 + },
311 + )
312 + func = provider.wrap_tool(tool, create_mock_execute_tool())
313 +
314 + sig = inspect.signature(func)
315 + tags_annotation = sig.parameters["tags"].annotation
316 + # Must be a parameterized generic like List[str], not bare list
317 + assert typing.get_origin(tags_annotation) is list
318 + assert typing.get_args(tags_annotation) != ()
319 +
320 + def test_reserved_keyword_handling(self):
321 + """Parameters named 'for' or 'async' are substituted and reinstated."""
322 + from composio_gemini import GeminiProvider
323 +
324 + provider = GeminiProvider()
325 + tool = create_mock_tool(
326 + "TOOL_WITH_RESERVED",
327 + "test",
328 + input_parameters={
329 + "type": "object",
330 + "properties": {
331 + "for": {"type": "string"},
332 + "name": {"type": "string"},
333 + },
334 + "required": [],
335 + },
336 + )
337 + execute_tool = create_mock_execute_tool()
338 + func = provider.wrap_tool(tool, execute_tool)
339 +
340 + # The callable's signature should use the cleaned name
341 + sig = inspect.signature(func)
342 + assert "for_rs" in sig.parameters
343 + assert "for" not in sig.parameters
344 +
345 + # When called with the cleaned name, it reinstates the original
346 + func(for_rs="test_value", name="hello")
347 + call_args = execute_tool.call_args
348 + assert call_args[0][1]["for"] == "test_value"
349 + assert call_args[0][1]["name"] == "hello"
350 +
351 +
352 +# ---------------------------------------------------------------------------
353 +# wrap_tools
354 +# ---------------------------------------------------------------------------
355 +
356 +
357 +class TestWrapTools:
358 + def test_returns_list_of_callables(self):
359 + from composio_gemini import GeminiProvider
360 +
361 + provider = GeminiProvider()
362 + tools = [
363 + create_mock_tool("GITHUB_STAR_REPO", "github"),
364 + create_mock_tool("GMAIL_SEND_EMAIL", "gmail"),
365 + ]
366 + result = provider.wrap_tools(tools, create_mock_execute_tool())
367 +
368 + assert len(result) == 2
369 + assert all(inspect.isfunction(f) for f in result)
370 +
371 + def test_stores_all_executors(self):
372 + from composio_gemini import GeminiProvider
373 +
374 + provider = GeminiProvider()
375 + tools = [
376 + create_mock_tool("GITHUB_STAR_REPO", "github"),
377 + create_mock_tool("GMAIL_SEND_EMAIL", "gmail"),
378 + ]
379 + provider.wrap_tools(tools, create_mock_execute_tool())
380 +
381 + assert "GITHUB_STAR_REPO" in provider._executors
382 + assert "GMAIL_SEND_EMAIL" in provider._executors
383 +
384 + def test_empty_list(self):
385 + from composio_gemini import GeminiProvider
386 +
387 + provider = GeminiProvider()
388 + result = provider.wrap_tools([], create_mock_execute_tool())
389 + assert result == []
390 +
391 +
392 +# ---------------------------------------------------------------------------
393 +# AFC compatibility (requires google-genai)
394 +# ---------------------------------------------------------------------------
395 +
396 +
397 +@requires_genai
398 +class TestAFCCompatibility:
399 + """Verify callables work with google-genai's AFC pipeline."""
400 +
401 + def _wrap_one_tool(self):
402 + from composio_gemini import GeminiProvider
403 +
404 + provider = GeminiProvider()
405 + tool = create_mock_tool(
406 + "GITHUB_STAR_REPO",
407 + "github",
408 + input_parameters={
409 + "type": "object",
410 + "properties": {
411 + "owner": {"type": "string"},
412 + "repo": {"type": "string"},
413 + },
414 + "required": ["owner", "repo"],
415 + },
416 + description="Star a GitHub repository",
417 + )
418 + func = provider.wrap_tool(tool, create_mock_execute_tool())
419 + return func
420 +
421 + def test_callable_is_function(self):
422 + """inspect.isfunction must be True for t_tool() to call from_callable."""
423 + func = self._wrap_one_tool()
424 + assert inspect.isfunction(func)
425 +
426 + def test_callable_not_afc_incompatible(self):
427 + """Callables should not be flagged as AFC-incompatible."""
428 + func = self._wrap_one_tool()
429 + # The SDK checks: isinstance(tool, types.Tool) and tool.function_declarations
430 + # A callable is not a types.Tool, so it should not be flagged.
431 + assert not isinstance(func, genai_types.Tool)
432 +
433 + def test_callable_enters_function_map(self):
434 + """The callable should appear in the function map built by the SDK."""
435 + func = self._wrap_one_tool()
436 + # Simulate what get_function_map does: callable(tool) -> function_map[tool.__name__]
437 + assert callable(func)
438 + function_map = {}
439 + if callable(func):
440 + function_map[func.__name__] = func
441 + assert "GITHUB_STAR_REPO" in function_map
442 +
443 + def test_callables_in_generate_content_config(self):
444 + """Wrapped callables can be passed to GenerateContentConfig without error."""
445 + from composio_gemini import GeminiProvider
446 +
447 + provider = GeminiProvider()
448 + tools = [
449 + create_mock_tool(
450 + "GITHUB_STAR_REPO",
451 + "github",
452 + input_parameters={
453 + "type": "object",
454 + "properties": {
455 + "owner": {"type": "string"},
456 + "repo": {"type": "string"},
457 + },
458 + "required": ["owner", "repo"],
459 + },
460 + ),
461 + ]
462 + wrapped = provider.wrap_tools(tools, create_mock_execute_tool())
463 +
464 + # This should not raise
465 + config = genai_types.GenerateContentConfig(tools=wrapped)
466 + assert config.tools is not None
467 + assert len(config.tools) == 1
468 +
469 +
470 +# ---------------------------------------------------------------------------
471 +# handle_response (backward compat)
472 +# ---------------------------------------------------------------------------
473 +
474 +
475 +@requires_genai
476 +class TestHandleResponse:
477 + def _create_mock_response(self, function_calls: list[tuple[str, dict]]):
478 + parts = []
479 + for name, args in function_calls:
480 + part = MagicMock()
481 + part.function_call = MagicMock()
482 + part.function_call.name = name
483 + part.function_call.args = args
484 + parts.append(part)
485 +
486 + response = MagicMock()
487 + response.candidates = [MagicMock()]
488 + response.candidates[0].content = MagicMock()
489 + response.candidates[0].content.parts = parts
490 + return response
491 +
492 + def test_executes_function_call(self):
493 + from composio_gemini import GeminiProvider
494 +
495 + provider = GeminiProvider()
496 + tool = create_mock_tool("GITHUB_STAR_REPO", "github")
497 + execute_tool = create_mock_execute_tool()
498 + provider.wrap_tools([tool], execute_tool)
499 +
500 + response = self._create_mock_response(
501 + [("GITHUB_STAR_REPO", {"repo": "composio/composio"})]
502 + )
503 + function_responses, executed = provider.handle_response(response)
504 +
505 + assert executed is True
506 + assert len(function_responses) == 1
507 + execute_tool.assert_called_once_with(
508 + slug="GITHUB_STAR_REPO",
509 + arguments={"repo": "composio/composio"},
510 + )
511 +
512 + def test_no_function_calls(self):
513 + from composio_gemini import GeminiProvider
514 +
515 + provider = GeminiProvider()
516 + response = MagicMock()
517 + response.candidates = [MagicMock()]
518 + text_part = MagicMock()
519 + text_part.function_call = None
520 + response.candidates[0].content = MagicMock()
521 + response.candidates[0].content.parts = [text_part]
522 +
523 + function_responses, executed = provider.handle_response(response)
524 + assert executed is False
525 + assert function_responses == []
526 +
527 + def test_unknown_function_name(self):
528 + from composio_gemini import GeminiProvider
529 +
530 + provider = GeminiProvider()
531 + response = self._create_mock_response([("UNKNOWN_TOOL", {"param": "value"})])
532 + function_responses, executed = provider.handle_response(response)
533 + assert executed is False
534 + assert function_responses == []
535 +
536 + def test_no_candidates(self):
537 + from composio_gemini import GeminiProvider
538 +
539 + provider = GeminiProvider()
540 + response = MagicMock()
541 + response.candidates = []
542 + function_responses, executed = provider.handle_response(response)
543 + assert executed is False
544 + assert function_responses == []
545 +
546 +
547 +# ---------------------------------------------------------------------------
548 +# _process_execution_result
549 +# ---------------------------------------------------------------------------
550 +
551 +
552 +class TestProcessExecutionResult:
553 + def test_non_dict_result(self):
554 + from composio_gemini.provider import _process_execution_result
555 +
556 + assert _process_execution_result("hello") == {"result": "hello"}
557 + assert _process_execution_result(42) == {"result": 42}
558 +
559 + def test_successful_with_dict_data(self):
560 + from composio_gemini.provider import _process_execution_result
561 +
562 + result = _process_execution_result(
563 + {"data": {"key": "value"}, "error": None, "successful": True}
564 + )
565 + assert result == {"key": "value"}
566 +
567 + def test_successful_with_non_dict_data(self):
568 + from composio_gemini.provider import _process_execution_result
569 +
570 + result = _process_execution_result(
571 + {"data": "plain text", "error": None, "successful": True}
572 + )
573 + assert result == {"result": "plain text"}
574 +
575 + def test_failed_result(self):
576 + from composio_gemini.provider import _process_execution_result
577 +
578 + result = _process_execution_result(
579 + {"data": {}, "error": "Something went wrong", "successful": False}
580 + )
581 + assert result["error"] == "Something went wrong"
582 +
583 + def test_passthrough_dict(self):
584 + from composio_gemini.provider import _process_execution_result
585 +
586 + result = _process_execution_result({"custom": "response"})
587 + assert result == {"custom": "response"}