Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import asyncio |
| 2 | import functools |
| 3 | import hashlib |
| 4 | import logging |
| 5 | import types |
| 6 | import typing as t |
| 7 | from inspect import Signature |
| 8 | |
| 9 | import pydantic |
| 10 | from autogen.agentchat.conversable_agent import ConversableAgent |
| 11 | from autogen.runtime_logging import log_function_use, logging_enabled |
| 12 | from autogen.tools import serialize_to_str |
| 13 | from autogen_core import EVENT_LOGGER_NAME, CancellationToken, trace_tool_span |
| 14 | from autogen_core.logging import ToolCallEvent |
| 15 | from autogen_core.tools import FunctionTool, ToolSchema |
| 16 | |
| 17 | from composio.client.types import Tool |
| 18 | from composio.core.provider import AgenticProvider |
| 19 | from composio.core.provider.agentic import AgenticProviderExecuteFn |
| 20 | from composio.utils.pydantic import parse_pydantic_error |
| 21 | from composio.utils.schema_converter import object_is_open |
| 22 | from composio.utils.shared import ( |
| 23 | alias_tool_input_schema, |
| 24 | get_signature_format_from_schema_params, |
| 25 | json_schema_to_model, |
| 26 | normalize_tool_arguments, |
| 27 | validate_and_serialize_tool_arguments, |
| 28 | ) |
| 29 | |
| 30 | _event_logger = logging.getLogger(EVENT_LOGGER_NAME) |
| 31 | |
| 32 | |
| 33 | class ComposioFunctionTool(FunctionTool): |
| 34 | """A ``FunctionTool`` that runs a Composio tool on the model's raw arguments. |
| 35 | |
| 36 | ``FunctionTool.run_json`` validates the arguments against a model built |
| 37 | from the function signature, which drops every key the signature does not |
| 38 | name and fills omitted ones with fallback defaults. This tool hands the |
| 39 | raw mapping to the wrapped function instead, which validates it against |
| 40 | the source schema, and advertises the source root's openness so the model |
| 41 | can send the keys that schema admits. |
| 42 | """ |
| 43 | |
| 44 | def __init__( |
| 45 | self, |
| 46 | func: t.Callable[..., t.Any], |
| 47 | description: str, |
| 48 | name: str, |
| 49 | root_schema: t.Dict[str, t.Any], |
| 50 | ) -> None: |
| 51 | super().__init__(func=func, description=description, name=name) |
| 52 | self._root_schema = root_schema |
| 53 | |
| 54 | @property |
| 55 | def schema(self) -> ToolSchema: |
| 56 | schema = super().schema |
| 57 | parameters = t.cast(t.Dict[str, t.Any], schema["parameters"]) |
| 58 | root = self._root_schema |
| 59 | parameters["additionalProperties"] = root.get( |
| 60 | "additionalProperties", object_is_open(root) |
| 61 | ) |
| 62 | if "patternProperties" in root: |
| 63 | parameters["patternProperties"] = root["patternProperties"] |
| 64 | return schema |
| 65 | |
| 66 | async def run_json( |
| 67 | self, |
| 68 | args: t.Mapping[str, t.Any], |
| 69 | cancellation_token: CancellationToken, |
| 70 | call_id: t.Optional[str] = None, |
| 71 | ) -> t.Any: |
| 72 | arguments = normalize_tool_arguments(args) |
| 73 | # Same span and event as `BaseTool.run_json`, which this does not call |
| 74 | # because it re-runs the signature model that drops keys. |
| 75 | with trace_tool_span( |
| 76 | tool_name=self._name, |
| 77 | tool_description=self._description, |
| 78 | tool_call_id=call_id, |
| 79 | ): |
| 80 | future = asyncio.get_running_loop().run_in_executor( |
| 81 | None, functools.partial(self._func, **arguments) |
| 82 | ) |
| 83 | cancellation_token.link_future(future) |
| 84 | result = await future |
| 85 | _event_logger.info( |
| 86 | ToolCallEvent( |
| 87 | tool_name=self.name, |
| 88 | arguments=arguments, |
| 89 | result=self.return_value_as_string(result), |
| 90 | ) |
| 91 | ) |
| 92 | return result |
| 93 | |
| 94 | |
| 95 | class AutogenProvider( |
| 96 | AgenticProvider[FunctionTool, list[FunctionTool]], |
| 97 | name="autogen", |
| 98 | ): |
| 99 | """ |
| 100 | Composio toolset for Autogen framework. |
| 101 | """ |
| 102 | |
| 103 | def _process_function_name_for_registration( |
| 104 | self, |
| 105 | input_string: str, |
| 106 | max_allowed_length: int = 64, |
| 107 | num_hash_char: int = 10, |
| 108 | ): |
| 109 | """ |
| 110 | Process function name for proxy registration under given character length limitation. |
| 111 | """ |
| 112 | hash_hex = hashlib.sha256(input_string.encode(encoding="utf-8")).hexdigest() |
| 113 | hash_chars_to_attach = hash_hex[:10] |
| 114 | num_input_str_char = max_allowed_length - (num_hash_char + 1) |
| 115 | input_str_to_attach = input_string[-num_input_str_char:] |
| 116 | processed_name = input_str_to_attach + "_" + hash_chars_to_attach |
| 117 | return processed_name |
| 118 | |
| 119 | def register_tools( |
| 120 | self, |
| 121 | caller: ConversableAgent, |
| 122 | executor: ConversableAgent, |
| 123 | tools: t.List[FunctionTool], |
| 124 | ) -> None: |
| 125 | """ |
| 126 | Register tools to the proxy agents. |
| 127 | |
| 128 | :param executor: Executor agent. |
| 129 | :param caller: Caller agent. |
| 130 | :param tools: List of tools to register. |
| 131 | """ |
| 132 | for tool in tools: |
| 133 | # The model-facing declaration is derived from the function signature. |
| 134 | caller.register_for_llm(name=tool.name, description=tool.description)( |
| 135 | tool._func |
| 136 | ) |
| 137 | # Execution bypasses AG2's signature-based parameter injection, |
| 138 | # which drops keys the signature does not name, so the wrapped |
| 139 | # function validates the model's raw arguments itself. |
| 140 | executor.register_function({tool.name: self._ag2_executor(executor, tool)}) |
| 141 | |
| 142 | @staticmethod |
| 143 | def _ag2_executor( |
| 144 | executor: ConversableAgent, tool: FunctionTool |
| 145 | ) -> t.Callable[..., str]: |
| 146 | func = tool._func |
| 147 | |
| 148 | def execute(**arguments: t.Any) -> str: |
| 149 | result = func(**arguments) |
| 150 | if logging_enabled(): |
| 151 | log_function_use(executor, func, arguments, result) |
| 152 | return serialize_to_str(result) |
| 153 | |
| 154 | return execute |
| 155 | |
| 156 | def wrap_tool( |
| 157 | self, |
| 158 | tool: Tool, |
| 159 | execute_tool: AgenticProviderExecuteFn, |
| 160 | ) -> FunctionTool: |
| 161 | """Wraps a composio tool as an Autogen FunctionTool.""" |
| 162 | aliases = alias_tool_input_schema(schema=tool.input_parameters) |
| 163 | args_schema = json_schema_to_model( |
| 164 | aliases.schema, skip_default=self.skip_default |
| 165 | ) |
| 166 | |
| 167 | def execute_action(**kwargs: t.Any) -> t.Dict: |
| 168 | """Validate the model's arguments and execute the tool.""" |
| 169 | try: |
| 170 | arguments = validate_and_serialize_tool_arguments( |
| 171 | args_schema, normalize_tool_arguments(kwargs) |
| 172 | ) |
| 173 | except pydantic.ValidationError as e: |
| 174 | return { |
| 175 | "successful": False, |
| 176 | "error": parse_pydantic_error(e), |
| 177 | "data": None, |
| 178 | } |
| 179 | return execute_tool( |
| 180 | slug=tool.slug, arguments=aliases.restore_arguments(arguments) |
| 181 | ) |
| 182 | |
| 183 | # Create function with proper signature |
| 184 | function = types.FunctionType( |
| 185 | code=execute_action.__code__, |
| 186 | globals=globals(), |
| 187 | closure=execute_action.__closure__, |
| 188 | name=self._process_function_name_for_registration(input_string=tool.slug), |
| 189 | ) |
| 190 | |
| 191 | # The signature only declares the tool; `execute_action` accepts any |
| 192 | # keys and validates them against the source schema. |
| 193 | params = get_signature_format_from_schema_params( |
| 194 | schema_params=aliases.schema, |
| 195 | skip_default=self.skip_default, |
| 196 | ) |
| 197 | function.__doc__ = tool.description |
| 198 | setattr(function, "__signature__", Signature(parameters=params)) |
| 199 | setattr( |
| 200 | function, |
| 201 | "__annotations__", |
| 202 | {p.name: p.annotation for p in params} | {"return": t.Dict[str, t.Any]}, |
| 203 | ) |
| 204 | return ComposioFunctionTool( |
| 205 | func=function, |
| 206 | description=tool.description, |
| 207 | name=self._process_function_name_for_registration(input_string=tool.slug), |
| 208 | root_schema=aliases.schema, |
| 209 | ) |
| 210 | |
| 211 | def wrap_tools( |
| 212 | self, |
| 213 | tools: t.Sequence[Tool], |
| 214 | execute_tool: AgenticProviderExecuteFn, |
| 215 | ) -> list[FunctionTool]: |
| 216 | """Wraps array of composio tools as an Autogen FunctionTool.""" |
| 217 | return [self.wrap_tool(tool=tool, execute_tool=execute_tool) for tool in tools] |