Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(py): gemini for Tool Router
jkomyno2665be5b6a1d
diff --git a/python/config/pytest.ini b/python/config/pytest.iniindex 9e86b72c8..8c79fc5c9 100644--- a/python/config/pytest.ini+++ b/python/config/pytest.ini@@ -5,3 +5,4 @@ markers =openai: marks tests that check the OpenAIProviderlangchain: marks tests that check the LangChainProvideragno: marks tests that check the AgnoProvider+ gemini: marks tests that check the GeminiProviderdiff --git a/python/providers/gemini/composio_gemini/provider.py b/python/providers/gemini/composio_gemini/provider.pyindex 6cfa1a8af..250777501 100644--- a/python/providers/gemini/composio_gemini/provider.py+++ b/python/providers/gemini/composio_gemini/provider.py@@ -1,12 +1,20 @@-"""Gemini provider for Composio SDK."""+"""Gemini provider for Composio SDK.+Returns Python callables compatible with google-genai's Automatic Function+Calling (AFC). The SDK can introspect the callable's signature to derive+FunctionDeclaration schemas and auto-execute tool calls in the chat loop.+"""++import types as pytypesimport typing as t+from inspect import Parameter, Signaturefrom composio.client.types import Toolfrom composio.core.provider import AgenticProviderfrom composio.core.provider.agentic import AgenticProviderExecuteFn+from composio.utils.shared import get_pydantic_signature_format_from_schema_params-# Try to import Google GenAI types+# google-genai is only needed for handle_response (backward compat)try:from google.genai import types as genai_types@@ -15,219 +23,180 @@ except ImportError:genai_types = None # type: ignoreHAS_GENAI = False+_python_reserved = {"for", "async"}-class GeminiTool:- """- Enhanced Gemini Tool wrapper that handles automatic function execution.- Acts as a drop-in replacement for genai_types.Tool with execution support.- """- def __init__(- self,- tool: Tool,- execute_tool: AgenticProviderExecuteFn,- function_declaration: t.Optional[t.Any] = None,- ):- self.tool = tool- self.execute_tool = execute_tool- self.function_declaration = function_declaration-- # Create the actual Gemini Tool if we have genai support- self._genai_tool = None- if HAS_GENAI and function_declaration:- self._genai_tool = genai_types.Tool(- function_declarations=[function_declaration]- )-- # Store executor for easy access- self._executors = {tool.slug: self}+def _clean_reserved_keyword(keyword: str) -> str:+ return f"{keyword}_rs"- # Copy function attributes for compatibility- self.__name__ = tool.slug- self.__module__ = "composio_gemini"- self.__doc__ = tool.description- def __call__(self, **kwargs: t.Any) -> t.Dict:- """Execute the tool when called."""- result = self.execute_tool(slug=self.tool.slug, arguments=kwargs)+def _substitute_reserved_python_keywords(schema: t.Dict) -> t.Tuple[dict, dict]:+ if "properties" not in schema:+ return schema, {}- # Process the result for Gemini- if not isinstance(result, dict):- return {"result": result}+ keywords: t.Dict[str, str] = {}+ for p_name in list(schema["properties"]):+ if p_name not in _python_reserved:+ continue- # Extract data field if present and successful- if result.get("successful", True) and "data" in result:- data = result["data"]- return data if isinstance(data, dict) else {"result": data}+ p_val = schema["properties"].pop(p_name)+ p_name_clean = _clean_reserved_keyword(keyword=p_name)+ schema["properties"][p_name_clean] = p_val+ keywords[p_name_clean] = p_name- # Return error info if failed- if not result.get("successful", True):- return {- "error": result.get("error", "Tool execution failed"),- "details": result,- }+ return schema, keywords- return result- @property- def function_declarations(self):- """Pass through to the underlying Gemini tool."""- return self._genai_tool.function_declarations if self._genai_tool else []+def _reinstate_reserved_python_keywords(request: dict, keywords: dict) -> dict:+ for clean_key, original_key in keywords.items():+ if clean_key not in request:+ continue+ request[original_key] = request.pop(clean_key)+ return request- def to_dict(self):- """Convert to dict for Gemini API."""- return self._genai_tool.to_dict() if self._genai_tool else {}+def _to_serializable(value: t.Any) -> t.Any:+ """Recursively convert Pydantic models (and other non-JSON types) to plain dicts/lists.-class GeminiProvider(AgenticProvider[t.Any, list[t.Any]], name="gemini"):- """- Composio toolset for Google AI Python Gemini framework.- Supports automatic function calling with native Gemini tools.+ The google-genai SDK's AFC pipeline calls ``convert_if_exist_pydantic_model``+ on function arguments, turning nested dicts into dynamically-generated+ Pydantic ``GeneratedModel`` instances. These are not JSON-serializable, so+ the Composio ``execute_tool`` call fails. This helper normalises them back+ to plain Python primitives before handing off to the API."""+ # Pydantic v2 BaseModel+ if hasattr(value, "model_dump"):+ return value.model_dump()+ # Pydantic v1 BaseModel+ if hasattr(value, "dict") and hasattr(value, "__fields__"):+ return value.dict()+ if isinstance(value, dict):+ return {k: _to_serializable(v) for k, v in value.items()}+ if isinstance(value, (list, tuple)):+ return [_to_serializable(v) for v in value]+ return value+++def _process_execution_result(result: t.Any) -> t.Dict:+ """Process a tool execution result into a dict suitable for Gemini function responses."""+ if not isinstance(result, dict):+ return {"result": result}++ if result.get("successful", True) and "data" in result:+ data = result["data"]+ return data if isinstance(data, dict) else {"result": data}++ if not result.get("successful", True):+ return {+ "error": result.get("error", "Tool execution failed"),+ "details": result,+ }- __schema_skip_defaults__ = True+ return result- def _json_to_genai_schema(self, json_schema: dict) -> t.Optional[t.Any]:- """Convert JSON Schema to GenAI Schema format, handling composite types."""- if not HAS_GENAI:- return None-- # Handle composite types (patterns from openapi.py)- if "oneOf" in json_schema:- # Gemini doesn't support unions directly, use first valid schema- # This is a limitation but better than failing- return self._json_to_genai_schema(json_schema["oneOf"][0])-- if "anyOf" in json_schema:- # Similar to oneOf- return self._json_to_genai_schema(json_schema["anyOf"][0])-- if "allOf" in json_schema:- # Merge all schemas (pattern from openapi.py's _all_of_to_parameter)- merged = {}- for subschema in json_schema["allOf"]:- merged.update(subschema)- return self._json_to_genai_schema(merged)-- # Handle enum independently (can appear with or without type)- if "enum" in json_schema:- return self._handle_enum_schema(json_schema)-- schema_type = json_schema.get("type", "string")-- # Map type handlers- type_handlers = {- "array": self._handle_array_schema,- "object": self._handle_object_schema,- "string": self._handle_string_schema,- "number": lambda _: genai_types.Schema(type=genai_types.Type.NUMBER),- "integer": lambda _: genai_types.Schema(type=genai_types.Type.INTEGER),- "boolean": lambda _: genai_types.Schema(type=genai_types.Type.BOOLEAN),- "null": lambda _: genai_types.Schema(- type=genai_types.Type.STRING- ), # Gemini doesn't have null type- }- handler = type_handlers.get(- schema_type, lambda _: genai_types.Schema(type=genai_types.Type.STRING)- )- return handler(json_schema)-- def _handle_array_schema(self, json_schema: dict) -> t.Any:- """Handle array type schema conversion."""- items = json_schema.get("items", {})- return genai_types.Schema(- type=genai_types.Type.ARRAY,- items=self._json_to_genai_schema(items)- if items- else genai_types.Schema(type=genai_types.Type.STRING),- )+class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini"):+ """Composio toolset for Google AI Python Gemini framework.- def _handle_object_schema(self, json_schema: dict) -> t.Any:- """Handle object type schema conversion."""- properties = {- name: schema_obj- for name, schema in json_schema.get("properties", {}).items()- if (schema_obj := self._json_to_genai_schema(schema)) is not None- }- return genai_types.Schema(- type=genai_types.Type.OBJECT,- properties=properties,- required=json_schema.get("required", []),- )+ Returns Python callables compatible with google-genai's Automatic Function+ Calling (AFC). Pass the result of ``wrap_tools()`` directly to+ ``GenerateContentConfig(tools=...)`` and the SDK will auto-execute tool+ calls in the ``chat.send_message()`` loop.+ """- def _handle_string_schema(self, json_schema: dict) -> t.Any:- """Handle string type schema conversion."""- if enum_values := json_schema.get("enum"):- return genai_types.Schema(type=genai_types.Type.STRING, enum=enum_values)- return genai_types.Schema(type=genai_types.Type.STRING)-- def _handle_enum_schema(self, json_schema: dict) -> t.Any:- """Handle enum schema conversion (pattern from openapi.py)."""- # Enum can be of any type, default to string if no type specified- base_type = json_schema.get("type", "string")- type_map = {- "string": genai_types.Type.STRING,- "integer": genai_types.Type.INTEGER,- "number": genai_types.Type.NUMBER,- }- schema_type = type_map.get(base_type, genai_types.Type.STRING)- return genai_types.Schema(type=schema_type, enum=json_schema["enum"])+ __schema_skip_defaults__ = True- def _create_function_declaration(self, tool: Tool) -> t.Optional[t.Any]:- """Create a native Gemini FunctionDeclaration if possible."""- if not HAS_GENAI:- return None-- try:- genai_schema = self._json_to_genai_schema(tool.input_parameters)- return genai_types.FunctionDeclaration(- name=tool.slug,- description=tool.description or f"Execute {tool.slug}",- parameters=genai_schema,- )- except Exception as e:- print(f"Warning: Could not create FunctionDeclaration for {tool.slug}: {e}")- return None+ def __init__(self, **kwargs: t.Any):+ super().__init__(**kwargs)+ self._executors: t.Dict[str, AgenticProviderExecuteFn] = {}def wrap_tool(self,tool: Tool,execute_tool: AgenticProviderExecuteFn,- ) -> GeminiTool:- """Wrap a Composio tool for Gemini compatibility."""- # Create native FunctionDeclaration- function_declaration = self._create_function_declaration(tool)-- # Return the GeminiTool wrapper- return GeminiTool(- tool=tool,- execute_tool=execute_tool,- function_declaration=function_declaration,+ ) -> t.Callable:+ """Wrap a Composio tool as a Python callable for google-genai AFC.++ The returned function has ``__name__``, ``__doc__``, ``__signature__``+ and ``__annotations__`` set so the google-genai SDK can:++ 1. Derive a ``FunctionDeclaration`` schema via ``from_callable()``+ 2. Store it in the AFC ``function_map`` for automatic execution+ """+ self._executors[tool.slug] = execute_tool++ # Handle reserved Python keywords in parameter names+ schema_params, keywords = _substitute_reserved_python_keywords(+ schema=tool.input_parameters+ )++ def function(**kwargs: t.Any) -> t.Dict:+ """Composio tool execution wrapper."""+ kwargs = _to_serializable(kwargs)+ kwargs = _reinstate_reserved_python_keywords(+ request=kwargs, keywords=keywords+ )+ result = execute_tool(tool.slug, kwargs)+ return _process_execution_result(result)++ # Create a real function object (passes inspect.isfunction)+ action_func = pytypes.FunctionType(+ function.__code__,+ globals=globals(),+ name=tool.slug,+ closure=function.__closure__,+ )++ # Build typed signature from JSON schema.+ # Uses get_pydantic_signature_format_from_schema_params (not+ # get_signature_format_from_schema_params) because the pydantic variant+ # goes through json_schema_to_pydantic_type() which produces+ # parameterized generics (e.g. List[str] instead of bare List).+ # The google-genai SDK requires parameterized array types — bare List+ # generates {"type": "ARRAY"} without "items", which the API rejects.+ sig_params = get_pydantic_signature_format_from_schema_params(+ schema_params=schema_params,+ skip_default=True,)+ action_func.__signature__ = Signature(parameters=sig_params) # type: ignore+ action_func.__doc__ = tool.description or f"Execute {tool.slug}"++ # Build __annotations__ for typing.get_type_hints() compatibility+ annotations: t.Dict[str, t.Any] = {}+ for param in sig_params:+ if param.annotation is not Parameter.empty:+ annotations[param.name] = param.annotation+ annotations["return"] = dict+ action_func.__annotations__ = annotations++ return action_funcdef wrap_tools(self,tools: t.Sequence[Tool],execute_tool: AgenticProviderExecuteFn,- ) -> list[GeminiTool]:- """Wrap multiple tools for Gemini compatibility."""+ ) -> list[t.Callable]:+ """Wrap multiple Composio tools as Python callables for google-genai AFC."""return [self.wrap_tool(tool, execute_tool) for tool in tools]- @staticmethod- def handle_response(response, tools: list[GeminiTool]) -> tuple[list, bool]:- """- Automatically handle function calls in a Gemini response.+ # --- Backward compatibility: manual function calling ---- Args:- response: The response from Gemini chat- tools: The list of GeminiTool objects passed to the chat+ def handle_response(self, response: t.Any) -> tuple[list, bool]:+ """Manually handle function calls in a Gemini response.++ Provided for backward compatibility with code that uses manual function+ calling instead of AFC. For new code, pass the callables from+ ``wrap_tools()`` to ``GenerateContentConfig(tools=...)`` and AFC will+ handle execution automatically.Returns:- tuple: (function_responses, executed) where function_responses are ready- to send back and executed is True if functions were executed+ tuple: ``(function_responses, executed)`` where *function_responses*+ are ``genai_types.Part`` objects ready to send back, and *executed*+ is ``True`` if any functions were executed."""- # Check if we have a valid response with candidates+ if not HAS_GENAI:+ return [], False+if not (hasattr(response, "candidates") and response.candidates):return [], False@@ -235,14 +204,7 @@ class GeminiProvider(AgenticProvider[t.Any, list[t.Any]], name="gemini"):if not (hasattr(candidate, "content") and candidate.content.parts):return [], False- # Build executor map from tools- executors = {}- for tool in tools:- if isinstance(tool, GeminiTool):- executors.update(tool._executors)-- # Process function calls- function_responses = []+ function_responses: list = []executed = Falsefor part in candidate.content.parts:@@ -250,22 +212,19 @@ class GeminiProvider(AgenticProvider[t.Any, list[t.Any]], name="gemini"):continuefc = part.function_call- if fc.name not in executors:+ if fc.name not in self._executors:continue- # Execute the function- executor = executors[fc.name]- result = executor(**fc.args)-- # Create function response- if HAS_GENAI:- function_responses.append(- genai_types.Part(- function_response=genai_types.FunctionResponse(- name=fc.name, response=result- )+ result = self._executors[fc.name](slug=fc.name, arguments=dict(fc.args))+ processed = _process_execution_result(result)++ function_responses.append(+ genai_types.Part(+ function_response=genai_types.FunctionResponse(+ name=fc.name, response=processed))+ )executed = Truereturn function_responses, executeddiff --git a/python/tests/test_gemini_provider.py b/python/tests/test_gemini_provider.pynew file mode 100644index 000000000..000f26e0b--- /dev/null+++ b/python/tests/test_gemini_provider.py@@ -0,0 +1,587 @@+"""Test Gemini provider functionality.++Verifies:+- Provider initialization and attributes+- wrap_tool returns Python callables with correct metadata+- wrap_tools returns list of callables+- Callables are AFC-compatible (work with google-genai's function map)+- handle_response dispatches function calls via stored executors (backward compat)+- _process_execution_result helper+"""++import inspect+from unittest.mock import MagicMock, Mock++import pytest++from composio.client.types import Tool, tool_list_response+from composio.core.models.base import allow_tracking+from composio.core.provider import AgenticProvider++try:+ from google.genai import types as genai_types++ HAS_GENAI = True+except ImportError:+ genai_types = None+ HAS_GENAI = False++pytestmark = pytest.mark.gemini++requires_genai = pytest.mark.skipif(+ not HAS_GENAI, reason="google-genai package not installed"+)++[email protected](autouse=True)+def disable_telemetry():+ """Disable telemetry for all tests to prevent thread issues."""+ token = allow_tracking.set(False)+ yield+ allow_tracking.reset(token)+++def create_mock_tool(+ slug: str,+ toolkit_slug: str,+ version: str = "12012025_00",+ input_parameters: dict | None = None,+ description: str = "Test tool for provider testing",+) -> Tool:+ """Create a mock tool for testing."""+ return Tool(+ name=f"Test {slug}",+ slug=slug,+ description=description,+ input_parameters=input_parameters+ or {"type": "object", "properties": {}, "required": []},+ output_parameters={},+ available_versions=[version],+ version=version,+ scopes=[],+ status="active",+ toolkit=tool_list_response.ItemToolkit(+ name=toolkit_slug.title(), slug=toolkit_slug, logo=""+ ),+ deprecated=tool_list_response.ItemDeprecated(+ available_versions=[version],+ displayName=f"Test {slug}",+ version=version,+ toolkit=tool_list_response.ItemDeprecatedToolkit(logo=""),+ is_deprecated=False,+ ),+ is_deprecated=False,+ no_auth=False,+ tags=[],+ )+++def create_mock_execute_tool():+ """Create a mock execute_tool function matching AgenticProviderExecuteFn."""+ mock_fn = Mock()+ mock_fn.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ return mock_fn+++# ---------------------------------------------------------------------------+# Initialization+# ---------------------------------------------------------------------------+++class TestGeminiProviderInitialization:+ def test_initialization(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ assert provider is not None+ assert provider.name == "gemini"+ assert isinstance(provider, AgenticProvider)++ def test_has_empty_executors_on_init(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ assert provider._executors == {}+++# ---------------------------------------------------------------------------+# wrap_tool – callable creation+# ---------------------------------------------------------------------------+++class TestWrapTool:+ def test_returns_callable(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool("GITHUB_STAR_REPO", "github")+ result = provider.wrap_tool(tool, create_mock_execute_tool())+ assert callable(result)+ assert inspect.isfunction(result)++ def test_callable_has_correct_name(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool("GITHUB_STAR_REPO", "github")+ result = provider.wrap_tool(tool, create_mock_execute_tool())+ assert result.__name__ == "GITHUB_STAR_REPO"++ def test_callable_has_correct_doc(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "GITHUB_STAR_REPO", "github", description="Star a GitHub repository"+ )+ result = provider.wrap_tool(tool, create_mock_execute_tool())+ assert result.__doc__ == "Star a GitHub repository"++ def test_callable_has_typed_signature(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "GITHUB_CREATE_ISSUE",+ "github",+ input_parameters={+ "type": "object",+ "properties": {+ "title": {"type": "string"},+ "body": {"type": "string"},+ },+ "required": ["title"],+ },+ )+ result = provider.wrap_tool(tool, create_mock_execute_tool())++ sig = inspect.signature(result)+ assert "title" in sig.parameters+ assert "body" in sig.parameters+ assert sig.parameters["title"].annotation is str+ assert sig.parameters["body"].annotation is str++ def test_callable_has_annotations(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "TEST_TOOL",+ "test",+ input_parameters={+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "required": ["name"],+ },+ )+ result = provider.wrap_tool(tool, create_mock_execute_tool())++ assert "name" in result.__annotations__+ assert result.__annotations__["name"] is str+ assert result.__annotations__["return"] is dict++ def test_stores_executor(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool("GITHUB_STAR_REPO", "github")+ execute_tool = create_mock_execute_tool()+ provider.wrap_tool(tool, execute_tool)++ assert "GITHUB_STAR_REPO" in provider._executors+ assert provider._executors["GITHUB_STAR_REPO"] is execute_tool++ def test_callable_executes_correctly(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "MY_TOOL",+ "test",+ input_parameters={+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ )+ execute_tool = create_mock_execute_tool()+ func = provider.wrap_tool(tool, execute_tool)++ result = func(query="hello")+ execute_tool.assert_called_once_with("MY_TOOL", {"query": "hello"})+ # _process_execution_result extracts data when successful+ assert result == {"result": "success"}++ def test_callable_processes_error_result(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "MY_TOOL",+ "test",+ input_parameters={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ "required": [],+ },+ )+ execute_tool = Mock()+ execute_tool.return_value = {+ "data": {},+ "error": "Auth failed",+ "successful": False,+ }+ func = provider.wrap_tool(tool, execute_tool)+ result = func(q="test")+ assert result["error"] == "Auth failed"++ def test_callable_converts_pydantic_args_to_dicts(self):+ """AFC may pass Pydantic GeneratedModel instances as kwargs; they must be+ converted to plain dicts before reaching execute_tool so the Composio+ API can JSON-serialize them.+ """+ from pydantic import BaseModel++ from composio_gemini import GeminiProvider++ class FakeQuery(BaseModel):+ use_case: str = ""+ known_fields: str = ""++ provider = GeminiProvider()+ tool = create_mock_tool(+ "COMPOSIO_SEARCH_TOOLS",+ "composio",+ input_parameters={+ "type": "object",+ "properties": {+ "queries": {+ "type": "array",+ "items": {+ "type": "object",+ "title": "Query",+ "properties": {+ "use_case": {"type": "string"},+ "known_fields": {"type": "string"},+ },+ },+ },+ },+ "required": [],+ },+ )+ execute_tool = create_mock_execute_tool()+ func = provider.wrap_tool(tool, execute_tool)++ # Simulate what the SDK does: pass Pydantic model instances+ func(queries=[FakeQuery(use_case="summarize email")])++ call_args = execute_tool.call_args[0][1]+ # The queries value must be a plain list of dicts, not Pydantic models+ assert isinstance(call_args["queries"], list)+ assert isinstance(call_args["queries"][0], dict)+ assert call_args["queries"][0]["use_case"] == "summarize email"++ def test_array_param_has_parameterized_type(self):+ """Array parameters must produce List[X], not bare List.++ The google-genai SDK rejects bare List because it generates+ {"type": "ARRAY"} without "items".+ """+ import typing++ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "TOOL_WITH_ARRAY",+ "test",+ input_parameters={+ "type": "object",+ "properties": {+ "tags": {"type": "array", "items": {"type": "string"}},+ "name": {"type": "string"},+ },+ "required": ["name"],+ },+ )+ func = provider.wrap_tool(tool, create_mock_execute_tool())++ sig = inspect.signature(func)+ tags_annotation = sig.parameters["tags"].annotation+ # Must be a parameterized generic like List[str], not bare list+ assert typing.get_origin(tags_annotation) is list+ assert typing.get_args(tags_annotation) != ()++ def test_reserved_keyword_handling(self):+ """Parameters named 'for' or 'async' are substituted and reinstated."""+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "TOOL_WITH_RESERVED",+ "test",+ input_parameters={+ "type": "object",+ "properties": {+ "for": {"type": "string"},+ "name": {"type": "string"},+ },+ "required": [],+ },+ )+ execute_tool = create_mock_execute_tool()+ func = provider.wrap_tool(tool, execute_tool)++ # The callable's signature should use the cleaned name+ sig = inspect.signature(func)+ assert "for_rs" in sig.parameters+ assert "for" not in sig.parameters++ # When called with the cleaned name, it reinstates the original+ func(for_rs="test_value", name="hello")+ call_args = execute_tool.call_args+ assert call_args[0][1]["for"] == "test_value"+ assert call_args[0][1]["name"] == "hello"+++# ---------------------------------------------------------------------------+# wrap_tools+# ---------------------------------------------------------------------------+++class TestWrapTools:+ def test_returns_list_of_callables(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tools = [+ create_mock_tool("GITHUB_STAR_REPO", "github"),+ create_mock_tool("GMAIL_SEND_EMAIL", "gmail"),+ ]+ result = provider.wrap_tools(tools, create_mock_execute_tool())++ assert len(result) == 2+ assert all(inspect.isfunction(f) for f in result)++ def test_stores_all_executors(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tools = [+ create_mock_tool("GITHUB_STAR_REPO", "github"),+ create_mock_tool("GMAIL_SEND_EMAIL", "gmail"),+ ]+ provider.wrap_tools(tools, create_mock_execute_tool())++ assert "GITHUB_STAR_REPO" in provider._executors+ assert "GMAIL_SEND_EMAIL" in provider._executors++ def test_empty_list(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ result = provider.wrap_tools([], create_mock_execute_tool())+ assert result == []+++# ---------------------------------------------------------------------------+# AFC compatibility (requires google-genai)+# ---------------------------------------------------------------------------+++@requires_genai+class TestAFCCompatibility:+ """Verify callables work with google-genai's AFC pipeline."""++ def _wrap_one_tool(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool(+ "GITHUB_STAR_REPO",+ "github",+ input_parameters={+ "type": "object",+ "properties": {+ "owner": {"type": "string"},+ "repo": {"type": "string"},+ },+ "required": ["owner", "repo"],+ },+ description="Star a GitHub repository",+ )+ func = provider.wrap_tool(tool, create_mock_execute_tool())+ return func++ def test_callable_is_function(self):+ """inspect.isfunction must be True for t_tool() to call from_callable."""+ func = self._wrap_one_tool()+ assert inspect.isfunction(func)++ def test_callable_not_afc_incompatible(self):+ """Callables should not be flagged as AFC-incompatible."""+ func = self._wrap_one_tool()+ # The SDK checks: isinstance(tool, types.Tool) and tool.function_declarations+ # A callable is not a types.Tool, so it should not be flagged.+ assert not isinstance(func, genai_types.Tool)++ def test_callable_enters_function_map(self):+ """The callable should appear in the function map built by the SDK."""+ func = self._wrap_one_tool()+ # Simulate what get_function_map does: callable(tool) -> function_map[tool.__name__]+ assert callable(func)+ function_map = {}+ if callable(func):+ function_map[func.__name__] = func+ assert "GITHUB_STAR_REPO" in function_map++ def test_callables_in_generate_content_config(self):+ """Wrapped callables can be passed to GenerateContentConfig without error."""+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tools = [+ create_mock_tool(+ "GITHUB_STAR_REPO",+ "github",+ input_parameters={+ "type": "object",+ "properties": {+ "owner": {"type": "string"},+ "repo": {"type": "string"},+ },+ "required": ["owner", "repo"],+ },+ ),+ ]+ wrapped = provider.wrap_tools(tools, create_mock_execute_tool())++ # This should not raise+ config = genai_types.GenerateContentConfig(tools=wrapped)+ assert config.tools is not None+ assert len(config.tools) == 1+++# ---------------------------------------------------------------------------+# handle_response (backward compat)+# ---------------------------------------------------------------------------+++@requires_genai+class TestHandleResponse:+ def _create_mock_response(self, function_calls: list[tuple[str, dict]]):+ parts = []+ for name, args in function_calls:+ part = MagicMock()+ part.function_call = MagicMock()+ part.function_call.name = name+ part.function_call.args = args+ parts.append(part)++ response = MagicMock()+ response.candidates = [MagicMock()]+ response.candidates[0].content = MagicMock()+ response.candidates[0].content.parts = parts+ return response++ def test_executes_function_call(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ tool = create_mock_tool("GITHUB_STAR_REPO", "github")+ execute_tool = create_mock_execute_tool()+ provider.wrap_tools([tool], execute_tool)++ response = self._create_mock_response(+ [("GITHUB_STAR_REPO", {"repo": "composio/composio"})]+ )+ function_responses, executed = provider.handle_response(response)++ assert executed is True+ assert len(function_responses) == 1+ execute_tool.assert_called_once_with(+ slug="GITHUB_STAR_REPO",+ arguments={"repo": "composio/composio"},+ )++ def test_no_function_calls(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ response = MagicMock()+ response.candidates = [MagicMock()]+ text_part = MagicMock()+ text_part.function_call = None+ response.candidates[0].content = MagicMock()+ response.candidates[0].content.parts = [text_part]++ function_responses, executed = provider.handle_response(response)+ assert executed is False+ assert function_responses == []++ def test_unknown_function_name(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ response = self._create_mock_response([("UNKNOWN_TOOL", {"param": "value"})])+ function_responses, executed = provider.handle_response(response)+ assert executed is False+ assert function_responses == []++ def test_no_candidates(self):+ from composio_gemini import GeminiProvider++ provider = GeminiProvider()+ response = MagicMock()+ response.candidates = []+ function_responses, executed = provider.handle_response(response)+ assert executed is False+ assert function_responses == []+++# ---------------------------------------------------------------------------+# _process_execution_result+# ---------------------------------------------------------------------------+++class TestProcessExecutionResult:+ def test_non_dict_result(self):+ from composio_gemini.provider import _process_execution_result++ assert _process_execution_result("hello") == {"result": "hello"}+ assert _process_execution_result(42) == {"result": 42}++ def test_successful_with_dict_data(self):+ from composio_gemini.provider import _process_execution_result++ result = _process_execution_result(+ {"data": {"key": "value"}, "error": None, "successful": True}+ )+ assert result == {"key": "value"}++ def test_successful_with_non_dict_data(self):+ from composio_gemini.provider import _process_execution_result++ result = _process_execution_result(+ {"data": "plain text", "error": None, "successful": True}+ )+ assert result == {"result": "plain text"}++ def test_failed_result(self):+ from composio_gemini.provider import _process_execution_result++ result = _process_execution_result(+ {"data": {}, "error": "Something went wrong", "successful": False}+ )+ assert result["error"] == "Something went wrong"++ def test_passthrough_dict(self):+ from composio_gemini.provider import _process_execution_result++ result = _process_execution_result({"custom": "response"})+ assert result == {"custom": "response"}