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
| 1 | """ |
| 2 | Google AI Python Gemini tool spec. |
| 3 | """ |
| 4 | |
| 5 | import json |
| 6 | import typing as t |
| 7 | |
| 8 | from proto.marshal.collections.maps import MapComposite |
| 9 | from vertexai.generative_models import ( |
| 10 | Content, |
| 11 | FunctionDeclaration, |
| 12 | GenerationResponse, |
| 13 | Part, |
| 14 | ) |
| 15 | |
| 16 | from composio.core.provider import NonAgenticProvider, ToolCallSession |
| 17 | from composio.types import Modifiers, Tool, ToolExecutionResponse |
| 18 | from composio.utils.json_schema import dereference_json_schema |
| 19 | from composio.utils.shared import normalize_tool_arguments |
| 20 | |
| 21 | # Fields of the Vertex AI ``Schema`` message. ``FunctionDeclaration`` raises a |
| 22 | # ``ParseError`` for any other keyword, and Composio schemas carry several, such |
| 23 | # as ``examples``, ``const``, and ``human_parameter_name``. |
| 24 | _VERTEX_SCHEMA_FIELDS = frozenset( |
| 25 | "type format title description nullable default items minItems maxItems enum" |
| 26 | " properties propertyOrdering required minProperties maxProperties minimum" |
| 27 | " maximum minLength maxLength pattern example anyOf additionalProperties".split() |
| 28 | ) |
| 29 | |
| 30 | |
| 31 | def _merge(base: t.Dict[str, t.Any], over: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: |
| 32 | """Merge two schema nodes; ``over`` wins, but property maps and required lists combine.""" |
| 33 | merged = {**base, **over} |
| 34 | if isinstance(base.get("properties"), dict) and isinstance( |
| 35 | over.get("properties"), dict |
| 36 | ): |
| 37 | merged["properties"] = {**base["properties"], **over["properties"]} |
| 38 | if isinstance(base.get("required"), list) and isinstance( |
| 39 | over.get("required"), list |
| 40 | ): |
| 41 | names = base["required"] + over["required"] |
| 42 | merged["required"] = list(dict.fromkeys(n for n in names if isinstance(n, str))) |
| 43 | return merged |
| 44 | |
| 45 | |
| 46 | def _to_vertex_schema(schema: t.Any) -> t.Any: |
| 47 | """Reduce a JSON Schema node to the subset the Vertex AI ``Schema`` accepts. |
| 48 | |
| 49 | Unsupported keywords are dropped, ``oneOf`` becomes ``anyOf``, a string |
| 50 | ``const`` becomes a one-value ``enum``, ``null`` in ``type`` or ``enum`` becomes |
| 51 | ``nullable``, several types become ``anyOf``, and the values of a |
| 52 | non-string ``enum`` move into the description because Vertex only accepts |
| 53 | string enums. ``anyOf`` is left as the only field of its node, as Vertex |
| 54 | requires. Property names are kept as-is. |
| 55 | |
| 56 | Explicit loops keep each nesting level to one stack frame, so the depth cap |
| 57 | in ``dereference_json_schema`` stays the binding limit. |
| 58 | """ |
| 59 | if isinstance(schema, list): |
| 60 | items = [] |
| 61 | for item in schema: |
| 62 | items.append(_to_vertex_schema(item)) |
| 63 | return items |
| 64 | if isinstance(schema, bool): |
| 65 | # A boolean schema node (``items: true``, which MCP toolkits emit) has no |
| 66 | # Vertex equivalent. ``{}`` keeps ``true``; ``false`` loosens to it too, |
| 67 | # since Vertex cannot express "no value is valid". |
| 68 | return {} |
| 69 | if not isinstance(schema, dict): |
| 70 | return schema |
| 71 | node = dict(schema) |
| 72 | if "oneOf" in node and "anyOf" not in node: |
| 73 | node["anyOf"] = node.pop("oneOf") |
| 74 | if isinstance(node.get("const"), str) and "enum" not in node: |
| 75 | node["enum"] = [node["const"]] |
| 76 | if "type" in node: |
| 77 | types = node.pop("type") |
| 78 | types = types if isinstance(types, list) else [types] |
| 79 | non_null = [name for name in types if name != "null"] |
| 80 | if len(non_null) < len(types): |
| 81 | node["nullable"] = True |
| 82 | if "anyOf" in node: |
| 83 | # Vertex has no allOf: drop the branches whose single type the list |
| 84 | # rules out, and keep the rest as they are. |
| 85 | node["anyOf"] = [ |
| 86 | branch |
| 87 | for branch in node["anyOf"] |
| 88 | if not isinstance(branch, dict) |
| 89 | or not isinstance(branch.get("type"), str) |
| 90 | or branch["type"] in types |
| 91 | ] or node["anyOf"] |
| 92 | if len(non_null) == 1: |
| 93 | node["type"] = non_null[0] |
| 94 | elif non_null and "anyOf" not in node: |
| 95 | node["anyOf"] = [{"type": name} for name in non_null] |
| 96 | enum = node.get("enum") |
| 97 | if isinstance(enum, list) and None in enum: |
| 98 | node["nullable"] = True |
| 99 | enum = node["enum"] = [v for v in enum if v is not None] |
| 100 | if isinstance(enum, list) and not all(isinstance(v, str) for v in enum): |
| 101 | del node["enum"] |
| 102 | allowed = ", ".join(json.dumps(v) for v in enum) |
| 103 | node["description"] = ( |
| 104 | f"{node.get('description', '')} Allowed values: {allowed}.".strip() |
| 105 | ) |
| 106 | if "anyOf" in node: |
| 107 | # Vertex rejects anyOf next to any other field: fold a single option |
| 108 | # into the node, or copy the node's other fields into each option. |
| 109 | options = [] |
| 110 | for option in node.pop("anyOf"): |
| 111 | if isinstance(option, dict) and option.get("type") == "null": |
| 112 | node["nullable"] = True |
| 113 | elif isinstance(option, dict): |
| 114 | options.append(option) |
| 115 | if len(options) == 1: |
| 116 | return _to_vertex_schema(_merge(options[0], node)) |
| 117 | if options: |
| 118 | rest = _to_vertex_schema(node) |
| 119 | flat = [] # a converted option may itself be a lone anyOf: inline it |
| 120 | for option in _to_vertex_schema(options): |
| 121 | flat.extend(option.get("anyOf", [option])) |
| 122 | return {"anyOf": [_merge(rest, option) for option in flat]} |
| 123 | |
| 124 | result: t.Dict[str, t.Any] = {} |
| 125 | for key, value in node.items(): |
| 126 | if key not in _VERTEX_SCHEMA_FIELDS: |
| 127 | continue |
| 128 | if key == "properties" and isinstance(value, dict): |
| 129 | properties = {} |
| 130 | for name, prop in value.items(): |
| 131 | properties[name] = _to_vertex_schema(prop) |
| 132 | value = properties |
| 133 | elif key in ("items", "anyOf") or ( |
| 134 | key == "additionalProperties" and not isinstance(value, bool) |
| 135 | ): |
| 136 | value = _to_vertex_schema(value) |
| 137 | result[key] = value |
| 138 | return result |
| 139 | |
| 140 | |
| 141 | def _convert_map_composite(obj): |
| 142 | if isinstance(obj, MapComposite): |
| 143 | return {k: _convert_map_composite(v) for k, v in obj.items()} |
| 144 | if isinstance(obj, (list, tuple)): |
| 145 | return [_convert_map_composite(item) for item in obj] |
| 146 | return obj |
| 147 | |
| 148 | |
| 149 | class GoogleProvider( |
| 150 | NonAgenticProvider[FunctionDeclaration, list[FunctionDeclaration]], |
| 151 | name="google", |
| 152 | ): |
| 153 | """ |
| 154 | Composio toolset for Google AI Python Gemini framework. |
| 155 | """ |
| 156 | |
| 157 | def wrap_tool(self, tool: Tool) -> FunctionDeclaration: |
| 158 | """Wraps composio tool as Google AI Python Gemini FunctionDeclaration object.""" |
| 159 | input_parameters = dereference_json_schema( |
| 160 | tool.input_parameters, |
| 161 | on_unresolved="sentinel", |
| 162 | ) |
| 163 | return FunctionDeclaration( |
| 164 | name=tool.slug, |
| 165 | description=tool.description, |
| 166 | parameters=_to_vertex_schema( |
| 167 | { |
| 168 | "type": "object", |
| 169 | "properties": input_parameters.get("properties", {}), |
| 170 | "required": input_parameters.get("required", []), |
| 171 | } |
| 172 | ), |
| 173 | ) |
| 174 | |
| 175 | def wrap_tools(self, tools: t.Sequence[Tool]) -> list[FunctionDeclaration]: |
| 176 | return [self.wrap_tool(tool) for tool in tools] |
| 177 | |
| 178 | @t.overload |
| 179 | def execute_tool_call( |
| 180 | self, |
| 181 | user_id: str, |
| 182 | function_call: t.Any, |
| 183 | modifiers: t.Optional[Modifiers] = None, |
| 184 | ) -> ToolExecutionResponse: ... |
| 185 | |
| 186 | @t.overload |
| 187 | def execute_tool_call( |
| 188 | self, |
| 189 | *, |
| 190 | session: ToolCallSession, |
| 191 | function_call: t.Any, |
| 192 | ) -> ToolExecutionResponse: ... |
| 193 | |
| 194 | def execute_tool_call( |
| 195 | self, |
| 196 | user_id: t.Optional[str] = None, |
| 197 | function_call: t.Any = None, |
| 198 | modifiers: t.Optional[Modifiers] = None, |
| 199 | *, |
| 200 | session: t.Optional[ToolCallSession] = None, |
| 201 | ) -> ToolExecutionResponse: |
| 202 | """ |
| 203 | Execute a function call. |
| 204 | |
| 205 | :param function_call: Function call metadata from Gemini model response. |
| 206 | :param user_id: User ID for direct tool execution. |
| 207 | :param session: Tool Router session that produced session tools. |
| 208 | :param modifiers: Modifiers to use for direct execution. |
| 209 | :return: Object containing output data from the function call. |
| 210 | """ |
| 211 | if function_call is None: |
| 212 | raise TypeError("function_call is required") |
| 213 | # Gemini returns args as a MapComposite; normalize after converting to a |
| 214 | # plain dict so a stringified payload is handled uniformly too (issue #2406). |
| 215 | arguments = normalize_tool_arguments(_convert_map_composite(function_call.args)) |
| 216 | return self.execute_tool_for_target( |
| 217 | target=self.resolve_tool_call_execution_target( |
| 218 | user_id=user_id, session=session |
| 219 | ), |
| 220 | slug=function_call.name, |
| 221 | arguments=arguments, |
| 222 | modifiers=modifiers, |
| 223 | ) |
| 224 | |
| 225 | @t.overload |
| 226 | def handle_response( |
| 227 | self, |
| 228 | user_id: str, |
| 229 | response: GenerationResponse, |
| 230 | modifiers: t.Optional[Modifiers] = None, |
| 231 | ) -> t.List[ToolExecutionResponse]: ... |
| 232 | |
| 233 | @t.overload |
| 234 | def handle_response( |
| 235 | self, |
| 236 | *, |
| 237 | session: ToolCallSession, |
| 238 | response: GenerationResponse, |
| 239 | ) -> t.List[ToolExecutionResponse]: ... |
| 240 | |
| 241 | def handle_response( |
| 242 | self, |
| 243 | user_id: t.Optional[str] = None, |
| 244 | response: t.Optional[GenerationResponse] = None, |
| 245 | modifiers: t.Optional[Modifiers] = None, |
| 246 | *, |
| 247 | session: t.Optional[ToolCallSession] = None, |
| 248 | ) -> t.List[ToolExecutionResponse]: |
| 249 | """ |
| 250 | Handle response from Google AI Python Gemini model. |
| 251 | |
| 252 | :param response: Generation response from the Gemini model. |
| 253 | :param user_id: User ID for direct tool execution. |
| 254 | :param session: Tool Router session that produced session tools. |
| 255 | :param modifiers: Modifiers to use for direct execution. |
| 256 | :return: A list of output objects from the function calls. |
| 257 | """ |
| 258 | if response is None: |
| 259 | raise TypeError("response is required") |
| 260 | self.resolve_tool_call_execution_target(user_id=user_id, session=session) |
| 261 | if session is not None and modifiers is not None: |
| 262 | raise ValueError( |
| 263 | "Direct execution modifiers cannot be used with a Tool Router session" |
| 264 | ) |
| 265 | outputs = [] |
| 266 | for candidate in response.candidates: |
| 267 | if isinstance(candidate.content, Content) and candidate.content.parts: |
| 268 | for part in candidate.content.parts: |
| 269 | if isinstance(part, Part) and part.function_call: |
| 270 | outputs.append( |
| 271 | self.execute_tool_call( |
| 272 | session=session, |
| 273 | function_call=part.function_call, |
| 274 | ) |
| 275 | if session is not None |
| 276 | else self.execute_tool_call( |
| 277 | user_id=t.cast(str, user_id), |
| 278 | function_call=part.function_call, |
| 279 | modifiers=modifiers, |
| 280 | ) |
| 281 | ) |
| 282 | return outputs |