@devries-cameron20 / composio Mirror · read-only
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
py 374 lines 14.7 KB
Raw
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 threading
9 import types as pytypes
10 import typing as t
11 from inspect import Parameter, Signature
12
13 from pydantic import BaseModel
14
15 from composio.client.types import Tool
16 from composio.core.provider import (
17 AgenticProvider,
18 ToolCallExecutionTarget,
19 ToolCallSession,
20 get_execution_target,
21 )
22 from composio.core.provider.agentic import AgenticProviderExecuteFn
23 from composio.utils.shared import (
24 ToolSchemaAliases,
25 alias_tool_input_schema,
26 get_pydantic_signature_format_from_schema_params,
27 json_schema_to_model,
28 normalize_tool_arguments,
29 validate_and_serialize_tool_arguments,
30 )
31
32 # google-genai is only needed for handle_response (backward compat)
33 try:
34 from google.genai import types as genai_types
35
36 HAS_GENAI = True
37 except ImportError:
38 genai_types = None # type: ignore
39 HAS_GENAI = False
40
41
42 def _to_serializable(value: t.Any) -> t.Any:
43 """Recursively convert Pydantic models (and other non-JSON types) to plain dicts/lists.
44
45 The google-genai SDK's AFC pipeline calls ``convert_if_exist_pydantic_model``
46 on function arguments, turning nested dicts into dynamically-generated
47 Pydantic ``GeneratedModel`` instances. These are not JSON-serializable, so
48 the Composio ``execute_tool`` call fails. This helper normalises them back
49 to plain Python primitives before handing off to the API.
50 """
51 # Only fields the model returned: AFC fills omitted optional fields with
52 # ``None``, which the tool schema may not allow. Aliases restore reserved
53 # names such as ``from``.
54 # Pydantic v2 BaseModel
55 if hasattr(value, "model_dump"):
56 return value.model_dump(exclude_unset=True, by_alias=True)
57 # Pydantic v1 BaseModel
58 if hasattr(value, "dict") and hasattr(value, "__fields__"):
59 return value.dict(exclude_unset=True, by_alias=True)
60 if isinstance(value, dict):
61 return {k: _to_serializable(v) for k, v in value.items()}
62 if isinstance(value, (list, tuple)):
63 return [_to_serializable(v) for v in value]
64 return value
65
66
67 def _literal_type(schema: t.Any) -> type:
68 """The Python type shared by a typeless property's ``const``/``enum``
69 values, or ``object`` when there is none."""
70 if not isinstance(schema, dict):
71 return object
72 if "const" in schema:
73 values = [schema["const"]]
74 elif isinstance(schema.get("enum"), list) and schema["enum"]:
75 values = schema["enum"]
76 else:
77 return object
78 # ``bool`` first: it is a subclass of ``int``.
79 for literal_type in (bool, str, int, float):
80 if all(type(value) is literal_type for value in values):
81 return literal_type
82 return object
83
84
85 def _afc_annotation(annotation: t.Any, schema: t.Any = None) -> t.Any:
86 """Return an annotation google-genai AFC can convert arguments with.
87
88 AFC reads the callable's signature both to declare the function and to
89 convert the arguments the model returns, and the conversion calls
90 ``isinstance`` with the annotation. That raises on ``Annotated[...]``,
91 parameterized ``Dict`` and ``typing.Any``, so any tool using them failed
92 before it ran. The plain annotations declare the same function; the source
93 schema is still enforced by ``args_schema``.
94
95 A property without a ``type`` is ``typing.Any``. A bare ``const`` or
96 ``enum`` is declared with the type of its values, so ``{"enum": ["asc",
97 "desc"]}`` stays a string as it was before the signature carried
98 validators. Anything else becomes ``object``, which declares no type and
99 lets the conversion accept any value.
100 """
101 origin = t.get_origin(annotation)
102 args = t.get_args(annotation)
103 if origin is t.Annotated:
104 return _afc_annotation(args[0], schema)
105 if origin is list and args:
106 return t.List[_afc_annotation(args[0])] # type: ignore[misc]
107 if origin is dict:
108 return dict
109 if origin in (t.Union, pytypes.UnionType):
110 return t.Union[tuple(_afc_annotation(arg) for arg in args)]
111 if annotation is t.Any:
112 return _literal_type(schema)
113 return annotation
114
115
116 def _execution_context(execute_tool: AgenticProviderExecuteFn) -> object:
117 """Identify who a wrapped tool executes as.
118
119 ``tools.get(user_id=...)`` and ``session.tools()`` record their user ID or
120 session on the execute function, so two fetches for the same user share a
121 context. Any other execute function is its own context.
122 """
123 target = get_execution_target(execute_tool)
124 return execute_tool if target is None else target
125
126
127 class _WrappedTool(t.NamedTuple):
128 """How one fetch wrapped a tool: the argument schema it built and the
129 execute function of the user or session it was fetched for.
130
131 They are stored together because schema modifiers can differ per fetch, so
132 a call must be validated with the schema of the fetch whose executor runs it.
133 """
134
135 execute_tool: AgenticProviderExecuteFn
136 aliases: ToolSchemaAliases
137 args_schema: t.Type[BaseModel]
138
139
140 def _process_execution_result(result: t.Any) -> t.Dict:
141 """Process a tool execution result into a dict suitable for Gemini function responses."""
142 if not isinstance(result, dict):
143 return {"result": result}
144
145 if result.get("successful", True) and "data" in result:
146 data = result["data"]
147 return data if isinstance(data, dict) else {"result": data}
148
149 if not result.get("successful", True):
150 return {
151 "error": result.get("error", "Tool execution failed"),
152 "details": result,
153 }
154
155 return result
156
157
158 class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini"):
159 """Composio toolset for Google AI Python Gemini framework.
160
161 Returns Python callables compatible with google-genai's Automatic Function
162 Calling (AFC). Pass the result of ``wrap_tools()`` directly to
163 ``GenerateContentConfig(tools=...)`` and the SDK will auto-execute tool
164 calls in the ``chat.send_message()`` loop.
165 """
166
167 __schema_skip_defaults__ = True
168
169 def __init__(self, **kwargs: t.Any):
170 super().__init__(**kwargs)
171 # Guards the registries below: tools can be fetched on one thread while
172 # ``handle_response`` reads them on another.
173 self._lock = threading.Lock()
174 # Wrapped tool per slug, for each user ID or session the tools were
175 # fetched for, so ``handle_response`` runs a call as the caller's user,
176 # with the caller's schema, rather than whoever fetched the tool last.
177 self._wrapped_tools: t.Dict[object, t.Dict[str, _WrappedTool]] = {}
178
179 def wrap_tool(
180 self,
181 tool: Tool,
182 execute_tool: AgenticProviderExecuteFn,
183 ) -> t.Callable:
184 """Wrap a Composio tool as a Python callable for google-genai AFC.
185
186 The returned function has ``__name__``, ``__doc__``, ``__signature__``
187 and ``__annotations__`` set so the google-genai SDK can:
188
189 1. Derive a ``FunctionDeclaration`` schema via ``from_callable()``
190 2. Store it in the AFC ``function_map`` for automatic execution
191 """
192 aliases = alias_tool_input_schema(schema=tool.input_parameters)
193 # Defaults stay out of the function declaration (see below), but the
194 # validation model needs them: without a default every optional field
195 # would be required.
196 args_schema = json_schema_to_model(aliases.schema, skip_default=False)
197 context = _execution_context(execute_tool)
198 with self._lock:
199 self._wrapped_tools.setdefault(context, {})[tool.slug] = _WrappedTool(
200 execute_tool, aliases, args_schema
201 )
202
203 def function(**kwargs: t.Any) -> t.Dict:
204 """Composio tool execution wrapper."""
205 kwargs = _to_serializable(kwargs)
206 kwargs = validate_and_serialize_tool_arguments(
207 args_schema,
208 normalize_tool_arguments(kwargs),
209 )
210 kwargs = aliases.restore_arguments(kwargs)
211 result = execute_tool(tool.slug, kwargs)
212 return _process_execution_result(result)
213
214 # Create a real function object (passes inspect.isfunction)
215 action_func = pytypes.FunctionType(
216 function.__code__,
217 globals=globals(),
218 name=tool.slug,
219 closure=function.__closure__,
220 )
221
222 # Build typed signature from JSON schema.
223 # Uses get_pydantic_signature_format_from_schema_params (not
224 # get_signature_format_from_schema_params) because the pydantic variant
225 # goes through json_schema_to_pydantic_type() which produces
226 # parameterized generics (e.g. List[str] instead of bare List).
227 # The google-genai SDK requires parameterized array types — bare List
228 # generates {"type": "ARRAY"} without "items", which the API rejects.
229 properties = aliases.schema.get("properties") or {}
230 sig_params = [
231 param.replace(
232 annotation=_afc_annotation(param.annotation, properties.get(param.name))
233 )
234 for param in get_pydantic_signature_format_from_schema_params(
235 schema_params=aliases.schema,
236 skip_default=True,
237 )
238 ]
239 action_func.__signature__ = Signature(parameters=sig_params) # type: ignore
240 action_func.__doc__ = tool.description or f"Execute {tool.slug}"
241
242 # Build __annotations__ for typing.get_type_hints() compatibility
243 annotations: t.Dict[str, t.Any] = {}
244 for param in sig_params:
245 if param.annotation is not Parameter.empty:
246 annotations[param.name] = param.annotation
247 annotations["return"] = dict
248 action_func.__annotations__ = annotations
249
250 return action_func
251
252 def wrap_tools(
253 self,
254 tools: t.Sequence[Tool],
255 execute_tool: AgenticProviderExecuteFn,
256 ) -> list[t.Callable]:
257 """Wrap multiple Composio tools as Python callables for google-genai AFC."""
258 return [self.wrap_tool(tool, execute_tool) for tool in tools]
259
260 # --- Backward compatibility: manual function calling ---
261
262 def handle_response(
263 self,
264 response: t.Any,
265 *,
266 user_id: t.Optional[str] = None,
267 session: t.Optional[ToolCallSession] = None,
268 ) -> tuple[list, bool]:
269 """Manually handle function calls in a Gemini response.
270
271 Provided for backward compatibility with code that uses manual function
272 calling instead of AFC. For new code, pass the callables from
273 ``wrap_tools()`` to ``GenerateContentConfig(tools=...)`` and AFC will
274 handle execution automatically.
275
276 A Gemini response does not say which user it belongs to. Pass the
277 ``user_id`` given to ``tools.get()``, or the Tool Router ``session``
278 whose ``tools()`` produced the tools, and each call runs exactly as
279 the matching wrapped tool would, with the same modifiers and session
280 routing. Without either, the provider must have wrapped tools for a
281 single user or session only; otherwise this raises ``ValueError``.
282
283 Returns:
284 tuple: ``(function_responses, executed)`` where *function_responses*
285 are ``genai_types.Part`` objects ready to send back, and *executed*
286 is ``True`` if any functions were executed.
287 """
288 target = (
289 None
290 if user_id is None and session is None
291 else self.resolve_tool_call_execution_target(
292 user_id=user_id, session=session
293 )
294 )
295
296 if not HAS_GENAI:
297 return [], False
298
299 if not (hasattr(response, "candidates") and response.candidates):
300 return [], False
301
302 candidate = response.candidates[0]
303 if not (hasattr(candidate, "content") and candidate.content.parts):
304 return [], False
305
306 function_calls = [
307 part.function_call
308 for part in candidate.content.parts
309 if hasattr(part, "function_call") and part.function_call
310 ]
311
312 # Pick every wrapped tool before running any call, so a concurrent
313 # fetch cannot change who a later call in this response runs as, or
314 # which schema checks it.
315 with self._lock:
316 if not any(
317 fc.name in wrapped
318 for fc in function_calls
319 for wrapped in self._wrapped_tools.values()
320 ):
321 return [], False
322 wrapped_tools = self._wrapped_tools_for(target)
323 calls = [
324 (fc, *wrapped_tools[fc.name])
325 for fc in function_calls
326 if fc.name in wrapped_tools
327 ]
328
329 function_responses: list = []
330 for fc, execute_tool, aliases, args_schema in calls:
331 # Same validate -> serialize -> alias sequence as the AFC callable.
332 arguments = validate_and_serialize_tool_arguments(
333 args_schema,
334 normalize_tool_arguments(_to_serializable(dict(fc.args))),
335 )
336 arguments = aliases.restore_arguments(arguments)
337 result = execute_tool(slug=fc.name, arguments=arguments)
338 processed = _process_execution_result(result)
339
340 function_responses.append(
341 genai_types.Part(
342 function_response=genai_types.FunctionResponse(
343 name=fc.name, response=processed
344 )
345 )
346 )
347
348 return function_responses, bool(function_responses)
349
350 def _wrapped_tools_for(
351 self,
352 target: t.Optional[ToolCallExecutionTarget],
353 ) -> t.Dict[str, _WrappedTool]:
354 """Return the tools wrapped for *target*. Call with the lock held."""
355 if target is None:
356 if len(self._wrapped_tools) > 1:
357 raise ValueError(
358 "This provider has wrapped tools for more than one user or "
359 "session, so the user to execute the response as is "
360 "ambiguous. Pass the user the response belongs to: "
361 "handle_response(response, user_id=...) or "
362 "handle_response(response, session=...)."
363 )
364 return next(iter(self._wrapped_tools.values()), {})
365
366 wrapped_tools = self._wrapped_tools.get(target)
367 if wrapped_tools is None:
368 source = (
369 "composio.tools.get() for this user_id"
370 if isinstance(target, str)
371 else "this session's tools()"
372 )
373 raise ValueError(f"This provider has not wrapped any tools from {source}.")
374 return wrapped_tools