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 copy |
| 3 | import json |
| 4 | import typing as t |
| 5 | |
| 6 | import pydantic |
| 7 | import typing_extensions as te |
| 8 | from agents import FunctionTool |
| 9 | |
| 10 | from composio.core.provider import AgenticProvider |
| 11 | from composio.core.provider.agentic import AgenticProviderExecuteFn |
| 12 | from composio.core.provider.base import BaseProviderConfig |
| 13 | from composio.types import Tool |
| 14 | from composio.utils.logging import get as get_logger |
| 15 | from composio.utils.pydantic import parse_pydantic_error |
| 16 | from composio.utils.schema_converter import object_is_open |
| 17 | from composio.utils.shared import normalize_tool_arguments |
| 18 | from composio.utils.strict_schema import omit_null_tool_arguments, to_strict_json_schema |
| 19 | |
| 20 | logger = get_logger(__name__) |
| 21 | |
| 22 | # Parameters registered for a tool without input parameters under strict mode. |
| 23 | _EMPTY_OBJECT_SCHEMA: t.Dict[str, t.Any] = { |
| 24 | "type": "object", |
| 25 | "properties": {}, |
| 26 | "required": [], |
| 27 | "additionalProperties": False, |
| 28 | } |
| 29 | |
| 30 | |
| 31 | # Recursively remove unsupported annotation/validation keys from schema properties. |
| 32 | def _remove_examples_from_schema(schema_obj: t.Dict[str, t.Any]) -> None: |
| 33 | """ |
| 34 | Remove 'examples', 'pattern', and 'default' keys from all properties in the |
| 35 | schema, including nested ones. |
| 36 | |
| 37 | Array item schemas are otherwise preserved verbatim. JSON Schema permits |
| 38 | ``items`` to use combiners, references, object keywords, or an empty schema |
| 39 | without declaring a direct ``type``. |
| 40 | """ |
| 41 | # Handle properties directly |
| 42 | if "properties" in schema_obj and isinstance(schema_obj["properties"], dict): |
| 43 | for _, prop_value in schema_obj["properties"].items(): |
| 44 | if isinstance(prop_value, dict): |
| 45 | # Remove examples, pattern, and default from this property |
| 46 | if "examples" in prop_value: |
| 47 | del prop_value["examples"] |
| 48 | if "pattern" in prop_value: |
| 49 | del prop_value["pattern"] |
| 50 | if "default" in prop_value: |
| 51 | del prop_value["default"] |
| 52 | |
| 53 | # Recursively process nested properties |
| 54 | _remove_examples_from_schema(prop_value) |
| 55 | |
| 56 | # Handle array items |
| 57 | if "items" in schema_obj and isinstance(schema_obj["items"], dict): |
| 58 | if "examples" in schema_obj["items"]: |
| 59 | del schema_obj["items"]["examples"] |
| 60 | if "pattern" in schema_obj["items"]: |
| 61 | del schema_obj["items"]["pattern"] |
| 62 | if "default" in schema_obj["items"]: |
| 63 | del schema_obj["items"]["default"] |
| 64 | _remove_examples_from_schema(schema_obj["items"]) |
| 65 | |
| 66 | # Handle any other nested object properties |
| 67 | for _, value in schema_obj.items(): |
| 68 | if isinstance(value, dict): |
| 69 | _remove_examples_from_schema(value) |
| 70 | elif isinstance(value, list): |
| 71 | for item in value: |
| 72 | if isinstance(item, dict): |
| 73 | _remove_examples_from_schema(item) |
| 74 | |
| 75 | |
| 76 | class OpenAIAgentsProvider( |
| 77 | AgenticProvider[FunctionTool, list[FunctionTool]], |
| 78 | name="openai_agents", |
| 79 | ): |
| 80 | """ |
| 81 | Composio toolset for OpenAI Agents framework. |
| 82 | """ |
| 83 | |
| 84 | def __init__( |
| 85 | self, strict: bool = False, **kwargs: te.Unpack[BaseProviderConfig] |
| 86 | ) -> None: |
| 87 | """ |
| 88 | :param strict: Emit wrapped tools with ``strict: true`` and normalize |
| 89 | their parameter schemas for OpenAI structured outputs (every |
| 90 | object fully required and closed, optional properties widened to |
| 91 | accept ``null``, local ``$ref``/``$defs`` kept). Mirrors the |
| 92 | TypeScript ``OpenAIAgentsProvider({ strict })`` option and this |
| 93 | package's own ``OpenAIResponsesProvider({ strict })``. Tools |
| 94 | whose schema strict mode cannot express are registered without |
| 95 | strict mode instead. Defaults to ``False``. |
| 96 | """ |
| 97 | super().__init__(**kwargs) |
| 98 | self.strict = strict |
| 99 | |
| 100 | def wrap_tool( |
| 101 | self, |
| 102 | tool: Tool, |
| 103 | execute_tool: AgenticProviderExecuteFn, |
| 104 | ) -> FunctionTool: |
| 105 | """Wrap a tool as a FunctionTool.""" |
| 106 | |
| 107 | # Under strict mode optional parameters are emitted as |
| 108 | # required-nullable, so a ``null`` the tool's own schema does not |
| 109 | # accept means "omitted". ``strict_source`` is the schema the strict |
| 110 | # rewrite was computed from, or ``None`` when this tool isn't |
| 111 | # registered under strict mode. |
| 112 | strict_source: t.Optional[t.Dict[str, t.Any]] = None |
| 113 | |
| 114 | # Create a function that accepts explicit JSON string for parameters |
| 115 | # This avoids the issue with **kwargs in schema validation |
| 116 | async def execute_tool_wrapper(_ctx, payload): |
| 117 | """Execute Composio action with the given arguments.""" |
| 118 | try: |
| 119 | # Models occasionally emit arguments as a JSON string (issue #2406). |
| 120 | arguments = normalize_tool_arguments(payload) |
| 121 | if strict_source is not None: |
| 122 | arguments = omit_null_tool_arguments(arguments, strict_source) |
| 123 | return json.dumps( |
| 124 | obj=( |
| 125 | await asyncio.to_thread( # Running a thread since `execute_tool` is not async |
| 126 | execute_tool, |
| 127 | slug=tool.slug, |
| 128 | arguments=arguments, |
| 129 | ) |
| 130 | ) |
| 131 | ) |
| 132 | except pydantic.ValidationError as e: |
| 133 | return json.dumps( |
| 134 | { |
| 135 | "successful": False, |
| 136 | "error": parse_pydantic_error(e), |
| 137 | "data": None, |
| 138 | } |
| 139 | ) |
| 140 | except Exception as e: |
| 141 | return json.dumps( |
| 142 | { |
| 143 | "successful": False, |
| 144 | "error": str(e), |
| 145 | "data": None, |
| 146 | } |
| 147 | ) |
| 148 | |
| 149 | if self.strict: |
| 150 | source = ( |
| 151 | tool.input_parameters |
| 152 | if tool.input_parameters is not None |
| 153 | else dict(_EMPTY_OBJECT_SCHEMA) |
| 154 | ) |
| 155 | strict = to_strict_json_schema(source) |
| 156 | if not strict.unsupported: |
| 157 | if strict.total_changes: |
| 158 | logger.debug( |
| 159 | 'OpenAIAgentsProvider: strict mode rewrote %d node(s) of tool "%s": %s', |
| 160 | strict.total_changes, |
| 161 | tool.slug, |
| 162 | "; ".join(f"{c.path}: {c.reason}" for c in strict.changes), |
| 163 | ) |
| 164 | strict_source = strict.source |
| 165 | return FunctionTool( |
| 166 | name=tool.slug, |
| 167 | description=tool.description, |
| 168 | params_json_schema=strict.schema, |
| 169 | on_invoke_tool=execute_tool_wrapper, |
| 170 | strict_json_schema=True, |
| 171 | ) |
| 172 | reasons = "; ".join( |
| 173 | f"{entry.path or '<root>'}: {entry.keyword} ({entry.detail})" |
| 174 | for entry in strict.unsupported |
| 175 | ) |
| 176 | logger.warning( |
| 177 | 'OpenAIAgentsProvider: tool "%s" is registered without strict ' |
| 178 | "mode because its schema cannot be expressed as strict " |
| 179 | "structured outputs: %s", |
| 180 | tool.slug, |
| 181 | reasons, |
| 182 | ) |
| 183 | |
| 184 | # Advertise the root as open or closed exactly as the source schema |
| 185 | # does: an explicit ``additionalProperties`` (true, a schema, or false) |
| 186 | # is kept as-is, and an omitted one follows the shared object policy |
| 187 | # (open only when no properties are declared). Open is written out as |
| 188 | # ``true``, matching the TypeScript provider. |
| 189 | # Deep-copy so the in-place edits below (additionalProperties + the |
| 190 | # examples/pattern/default removal) never mutate the caller's |
| 191 | # Tool.input_parameters, matching the deepcopy contract in |
| 192 | # composio.utils.shared. |
| 193 | modified_schema = copy.deepcopy(tool.input_parameters) |
| 194 | if "additionalProperties" not in modified_schema: |
| 195 | modified_schema["additionalProperties"] = object_is_open(modified_schema) |
| 196 | |
| 197 | # Apply the example removal function. This is done to optimize the |
| 198 | # schema as much as possible for Responses API |
| 199 | _remove_examples_from_schema(modified_schema) |
| 200 | |
| 201 | # Create a custom FunctionTool with the appropriate schema |
| 202 | return FunctionTool( |
| 203 | name=tool.slug, |
| 204 | description=tool.description, |
| 205 | params_json_schema=modified_schema, |
| 206 | on_invoke_tool=execute_tool_wrapper, |
| 207 | # To avoid schema errors due to required flags. Composio tools |
| 208 | # already process to have optimal schemas. |
| 209 | strict_json_schema=False, |
| 210 | ) |
| 211 | |
| 212 | def wrap_tools( |
| 213 | self, |
| 214 | tools: t.Sequence[Tool], |
| 215 | execute_tool: AgenticProviderExecuteFn, |
| 216 | ) -> list[FunctionTool]: |
| 217 | """Wrap a list of tools as a list of FunctionTools.""" |
| 218 | return [self.wrap_tool(tool, execute_tool) for tool in tools] |