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
+ and runs each call for the user or session the caller passes
10
- _process_execution_result helper
11
"""
12
13
import inspect
13
-from unittest.mock import MagicMock, Mock
14
+from unittest.mock import MagicMock, Mock, PropertyMock, patch
15
16
import pytest
17
113
assert provider.name == "gemini"
114
assert isinstance(provider, AgenticProvider)
115
115
- def test_has_empty_executors_on_init(self):
116
+ def test_has_no_wrapped_tools_on_init(self):
117
from composio_gemini import GeminiProvider
118
119
provider = GeminiProvider()
119
- assert provider._executors == {}
120
+ assert provider._wrapped_tools == {}
121
122
123
# ---------------------------------------------------------------------------
226
execute_tool = create_mock_execute_tool()
227
provider.wrap_tool(tool, execute_tool)
228
228
- assert "GITHUB_STAR_REPO" in provider._executors
229
- stored_execute_tool, _aliases, _args_schema = provider._executors[
230
- "GITHUB_STAR_REPO"
231
- ]
232
- assert stored_execute_tool is execute_tool
229
+ assert list(provider._wrapped_tools) == [execute_tool]
230
+ wrapped = provider._wrapped_tools[execute_tool]["GITHUB_STAR_REPO"]
231
+ assert wrapped.execute_tool is execute_tool
232
233
def test_callable_executes_correctly(self):
234
from composio_gemini import GeminiProvider
521
create_mock_tool("GITHUB_STAR_REPO", "github"),
522
create_mock_tool("GMAIL_SEND_EMAIL", "gmail"),
523
]
525
- provider.wrap_tools(tools, create_mock_execute_tool())
524
+ execute_tool = create_mock_execute_tool()
525
+ provider.wrap_tools(tools, execute_tool)
526
527
- assert "GITHUB_STAR_REPO" in provider._executors
528
- assert "GMAIL_SEND_EMAIL" in provider._executors
527
+ assert set(provider._wrapped_tools[execute_tool]) == {
528
+ "GITHUB_STAR_REPO",
529
+ "GMAIL_SEND_EMAIL",
530
+ }
531
532
def test_empty_list(self):
533
from composio_gemini import GeminiProvider
925
assert function_responses == []
926
927
928
+@requires_genai
929
+class TestHandleResponseUser:
930
+ """A function call runs for the user its tools were fetched for (#5112).
931
+
932
+ These go through ``Composio.tools.get()`` so the execute function each
933
+ fetch binds is the one the SDK really builds.
934
+ """
935
+
936
+ GMAIL = "GMAIL_FETCH_EMAILS"
937
+ NOTION = "NOTION_CREATE_PAGE"
938
+ SCHEMA = {
939
+ "type": "object",
940
+ "properties": {"query": {"type": "string"}},
941
+ "required": ["query"],
942
+ }
943
+
944
+ def _tool(self, slug: str) -> Tool:
945
+ return create_mock_tool(
946
+ slug, slug.split("_")[0].lower(), input_parameters=self.SCHEMA
947
+ )
948
+
949
+ @pytest.fixture
950
+ def composio(self):
951
+ from composio import Composio
952
+ from composio_gemini import GeminiProvider
953
+
954
+ composio = Composio(
955
+ provider=GeminiProvider(), api_key="test-key", allow_tracking=False
956
+ )
957
+ tools = {slug: self._tool(slug) for slug in (self.GMAIL, self.NOTION)}
958
+
959
+ def execute(*, tool_slug, arguments, user_id, **_kwargs):
960
+ return MagicMock(
961
+ **{
962
+ "model_dump.return_value": {
963
+ "data": {"user_id": user_id},
964
+ "error": None,
965
+ "successful": True,
966
+ }
967
+ }
968
+ )
969
+
970
+ with (
971
+ patch.object(
972
+ composio.tools,
973
+ "get_raw_composio_tools",
974
+ side_effect=lambda **kwargs: [tools[s] for s in kwargs["tools"]],
975
+ ),
976
+ patch.object(
977
+ type(composio.tools._client),
978
+ "without_retries",
979
+ new_callable=PropertyMock,
980
+ ) as without_retries,
981
+ ):
982
+ without_retries.return_value.tools.execute.side_effect = execute
983
+ yield composio
984
+
985
+ @staticmethod
986
+ def _response(*slugs: str):
987
+ return genai_types.GenerateContentResponse(
988
+ candidates=[
989
+ genai_types.Candidate(
990
+ content=genai_types.Content(
991
+ role="model",
992
+ parts=[
993
+ genai_types.Part(
994
+ function_call=genai_types.FunctionCall(
995
+ name=slug, args={"query": "is:unread"}
996
+ )
997
+ )
998
+ for slug in slugs
999
+ ],
1000
+ )
1001
+ )
1002
+ ]
1003
+ )
1004
+
1005
+ def _executed_for(self, composio, *slugs: str, **kwargs) -> list[str]:
1006
+ parts, executed = composio.provider.handle_response(
1007
+ self._response(*slugs), **kwargs
1008
+ )
1009
+ assert executed is True
1010
+ return [part.function_response.response["user_id"] for part in parts]
1011
+
1012
+ def test_explicit_user_wins_over_last_fetch(self, composio):
1013
+ composio.tools.get(user_id="alice", tools=[self.GMAIL])
1014
+ composio.tools.get(user_id="bob", tools=[self.GMAIL])
1015
+
1016
+ assert self._executed_for(composio, self.GMAIL, user_id="alice") == ["alice"]
1017
+ assert self._executed_for(composio, self.GMAIL, user_id="bob") == ["bob"]
1018
+
1019
+ @pytest.mark.parametrize(
1020
+ "bob_slug",
1021
+ [GMAIL, NOTION],
1022
+ ids=["same-slug", "disjoint-slugs"],
1023
+ )
1024
+ def test_rejects_call_without_user_once_two_users_fetched(self, composio, bob_slug):
1025
+ composio.tools.get(user_id="alice", tools=[self.GMAIL])
1026
+ composio.tools.get(user_id="bob", tools=[bob_slug])
1027
+ execute = composio.tools._client.without_retries.tools.execute
1028
+
1029
+ with pytest.raises(ValueError, match="user_id="):
1030
+ composio.provider.handle_response(self._response(self.GMAIL))
1031
+ execute.assert_not_called()
1032
+
1033
+ def test_single_user_without_user_still_works(self, composio):
1034
+ composio.tools.get(user_id="alice", tools=[self.GMAIL])
1035
+ composio.tools.get(user_id="alice", tools=[self.NOTION])
1036
+
1037
+ assert self._executed_for(composio, self.GMAIL, self.NOTION) == [
1038
+ "alice",
1039
+ "alice",
1040
+ ]
1041
+
1042
+ def test_rejects_user_with_no_fetched_tools(self, composio):
1043
+ composio.tools.get(user_id="alice", tools=[self.GMAIL])
1044
+
1045
+ with pytest.raises(ValueError, match="user_id"):
1046
+ composio.provider.handle_response(
1047
+ self._response(self.GMAIL), user_id="carol"
1048
+ )
1049
+
1050
+ def test_fetch_during_execution_does_not_switch_user(self, composio):
1051
+ """Executors are picked before any call runs (review of #5120)."""
1052
+ composio.tools.get(user_id="alice", tools=[self.GMAIL, self.NOTION])
1053
+ execute = composio.tools._client.without_retries.tools.execute
1054
+ alice_execute = execute.side_effect
1055
+
1056
+ def fetch_for_bob_then_execute(**kwargs):
1057
+ execute.side_effect = alice_execute
1058
+ composio.tools.get(user_id="bob", tools=[self.NOTION])
1059
+ return alice_execute(**kwargs)
1060
+
1061
+ execute.side_effect = fetch_for_bob_then_execute
1062
+
1063
+ # Without a user: Bob's fetch mid-response would make a later lookup
1064
+ # ambiguous, but the response was resolved before it.
1065
+ assert self._executed_for(composio, self.GMAIL, self.NOTION) == [
1066
+ "alice",
1067
+ "alice",
1068
+ ]
1069
+ with pytest.raises(ValueError, match="user_id="):
1070
+ composio.provider.handle_response(self._response(self.GMAIL))
1071
+
1072
+ def test_call_is_validated_with_its_own_users_schema(self, composio):
1073
+ """Each user's schema modifiers check that user's calls (review of #5120)."""
1074
+ from composio import schema_modifier
1075
+
1076
+ @schema_modifier(tools=[self.GMAIL])
1077
+ def starred_only(tool: str, toolkit: str, schema: Tool) -> Tool:
1078
+ schema.input_parameters = {
1079
+ **self.SCHEMA,
1080
+ "properties": {"query": {"type": "string", "enum": ["is:starred"]}},
1081
+ }
1082
+ return schema
1083
+
1084
+ composio.tools.get(user_id="alice", tools=[self.GMAIL])
1085
+ composio.tools.get(user_id="bob", tools=[self.GMAIL], modifiers=[starred_only])
1086
+
1087
+ assert self._executed_for(composio, self.GMAIL, user_id="alice") == ["alice"]
1088
+ with pytest.raises(ValueError, match="is:starred"):
1089
+ composio.provider.handle_response(self._response(self.GMAIL), user_id="bob")
1090
+
1091
+ def test_session_runs_through_its_own_executor(self, composio):
1092
+ """``session=`` keeps the routing ``session.tools()`` installed, which
1093
+ runs local custom tools in a batch in process."""
1094
+ from composio.core.provider import bind_execution_target
1095
+
1096
+ composio.tools.get(user_id="alice", tools=[self.GMAIL])
1097
+ session = Mock()
1098
+ routing_execute = bind_execution_target(
1099
+ Mock(return_value={"data": {"user_id": "session"}, "successful": True}),
1100
+ session,
1101
+ )
1102
+ composio.provider.wrap_tools([self._tool(self.GMAIL)], routing_execute)
1103
+
1104
+ assert self._executed_for(composio, self.GMAIL, session=session) == ["session"]
1105
+ routing_execute.assert_called_once_with(
1106
+ slug=self.GMAIL, arguments={"query": "is:unread"}
1107
+ )
1108
+ session.execute.assert_not_called()
1109
+
1110
+
1111
# ---------------------------------------------------------------------------
1112
# _process_execution_result
1113
# ---------------------------------------------------------------------------