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 | """ |
| 2 | OpenAI Responses API provider implementation. |
| 3 | """ |
| 4 | |
| 5 | from __future__ import annotations |
| 6 | |
| 7 | import typing as t |
| 8 | |
| 9 | import typing_extensions as te |
| 10 | |
| 11 | from openai.types.responses.response import Response |
| 12 | from openai.types.responses.response_output_item import ResponseFunctionToolCall |
| 13 | |
| 14 | from composio.core.provider import NonAgenticProvider, ToolCallSession |
| 15 | from composio.core.provider.base import BaseProviderConfig |
| 16 | from composio.types import Modifiers, Tool, ToolExecutionResponse |
| 17 | from composio.utils.logging import get as get_logger |
| 18 | from composio.utils.shared import normalize_tool_arguments |
| 19 | from composio.utils.strict_schema import omit_null_tool_arguments, to_strict_json_schema |
| 20 | |
| 21 | logger = get_logger(__name__) |
| 22 | |
| 23 | # Responses API uses a flattened tool structure |
| 24 | ResponsesTool = dict[str, t.Any] |
| 25 | ResponsesToolCollection = list[ResponsesTool] |
| 26 | |
| 27 | # Parameters emitted for a tool without input parameters under strict mode. |
| 28 | _EMPTY_OBJECT_SCHEMA: dict[str, t.Any] = { |
| 29 | "type": "object", |
| 30 | "properties": {}, |
| 31 | "required": [], |
| 32 | "additionalProperties": False, |
| 33 | } |
| 34 | |
| 35 | |
| 36 | class OpenAIResponsesProvider( |
| 37 | NonAgenticProvider[ResponsesTool, ResponsesToolCollection], name="openai_responses" |
| 38 | ): |
| 39 | """OpenAI Responses API Provider class definition.""" |
| 40 | |
| 41 | def __init__( |
| 42 | self, strict: bool = False, **kwargs: te.Unpack[BaseProviderConfig] |
| 43 | ) -> None: |
| 44 | """ |
| 45 | :param strict: Emit wrapped tools with ``strict: true`` and normalize |
| 46 | their parameter schemas for OpenAI structured outputs (every object |
| 47 | fully required and closed, optional properties widened to accept |
| 48 | ``null``, local ``$ref``/``$defs`` kept). Mirrors the TypeScript |
| 49 | ``OpenAIResponsesProvider({ strict })`` option. Defaults to |
| 50 | ``False``. |
| 51 | """ |
| 52 | super().__init__(**kwargs) |
| 53 | self.strict = strict |
| 54 | # Parameter schemas of the tools wrapped under strict mode, keyed by |
| 55 | # slug, so tool-call arguments can be reconciled against the schema |
| 56 | # the model actually saw. |
| 57 | self._strict_input_schemas: dict[str, dict[str, t.Any]] = {} |
| 58 | |
| 59 | def wrap_tool(self, tool: Tool) -> ResponsesTool: |
| 60 | """Wrap a tool for the Responses API format.""" |
| 61 | parameters: t.Any = ( |
| 62 | tool.input_parameters if tool.input_parameters is not None else {} |
| 63 | ) |
| 64 | wrapped: ResponsesTool = { |
| 65 | "type": "function", |
| 66 | "name": tool.slug, |
| 67 | "description": tool.description, |
| 68 | "parameters": parameters, |
| 69 | "strict": self.strict, |
| 70 | } |
| 71 | if not self.strict: |
| 72 | return wrapped |
| 73 | |
| 74 | # Structured outputs enforce their contract at every depth: all |
| 75 | # properties required, closed objects, no annotation keywords. The |
| 76 | # strict rewrite keeps every parameter (optional ones become nullable) |
| 77 | # and reports constructs it cannot express; such a tool is sent |
| 78 | # without strict mode rather than with a narrower schema. |
| 79 | source = ( |
| 80 | parameters |
| 81 | if tool.input_parameters is not None |
| 82 | else dict(_EMPTY_OBJECT_SCHEMA) |
| 83 | ) |
| 84 | strict = to_strict_json_schema(source) |
| 85 | if strict.unsupported: |
| 86 | reasons = "; ".join( |
| 87 | f"{entry.path or '<root>'}: {entry.keyword} ({entry.detail})" |
| 88 | for entry in strict.unsupported |
| 89 | ) |
| 90 | logger.warning( |
| 91 | 'OpenAIResponsesProvider: tool "%s" is sent without strict mode ' |
| 92 | "because its schema cannot be expressed as strict structured " |
| 93 | "outputs: %s", |
| 94 | tool.slug, |
| 95 | reasons, |
| 96 | ) |
| 97 | self._strict_input_schemas.pop(tool.slug, None) |
| 98 | wrapped["parameters"] = source |
| 99 | wrapped["strict"] = False |
| 100 | return wrapped |
| 101 | if strict.total_changes: |
| 102 | logger.debug( |
| 103 | 'OpenAIResponsesProvider: strict mode rewrote %d node(s) of tool "%s": %s', |
| 104 | strict.total_changes, |
| 105 | tool.slug, |
| 106 | "; ".join(f"{c.path}: {c.reason}" for c in strict.changes), |
| 107 | ) |
| 108 | self._strict_input_schemas[tool.slug] = strict.source |
| 109 | wrapped["parameters"] = strict.schema |
| 110 | wrapped["strict"] = True |
| 111 | return wrapped |
| 112 | |
| 113 | def wrap_tools(self, tools: t.Sequence[Tool]) -> ResponsesToolCollection: |
| 114 | """Wrap multiple tools for the Responses API format.""" |
| 115 | return [self.wrap_tool(tool) for tool in tools] |
| 116 | |
| 117 | @t.overload |
| 118 | def execute_tool_call( |
| 119 | self, |
| 120 | user_id: str, |
| 121 | tool_call: ResponseFunctionToolCall, |
| 122 | modifiers: Modifiers | None = None, |
| 123 | ) -> ToolExecutionResponse: ... |
| 124 | |
| 125 | @t.overload |
| 126 | def execute_tool_call( |
| 127 | self, |
| 128 | *, |
| 129 | session: ToolCallSession, |
| 130 | tool_call: ResponseFunctionToolCall, |
| 131 | ) -> ToolExecutionResponse: ... |
| 132 | |
| 133 | def execute_tool_call( |
| 134 | self, |
| 135 | user_id: str | None = None, |
| 136 | tool_call: ResponseFunctionToolCall | None = None, |
| 137 | modifiers: Modifiers | None = None, |
| 138 | *, |
| 139 | session: ToolCallSession | None = None, |
| 140 | ) -> ToolExecutionResponse: |
| 141 | """Execute a tool call from the Responses API. |
| 142 | |
| 143 | :param tool_call: Tool call metadata from Responses API. |
| 144 | :param user_id: User ID for direct tool execution. |
| 145 | :param session: Tool Router session that produced session tools. |
| 146 | :param modifiers: Optional modifiers for tool execution. |
| 147 | :return: Object containing output data from the tool call. |
| 148 | """ |
| 149 | if tool_call is None: |
| 150 | raise TypeError("tool_call is required") |
| 151 | target = self.resolve_tool_call_execution_target( |
| 152 | user_id=user_id, session=session |
| 153 | ) |
| 154 | |
| 155 | # OpenAI always serializes tool arguments as a JSON string; normalize |
| 156 | # tolerates empty / object-shaped payloads too (issue #2406). |
| 157 | slug = tool_call.name |
| 158 | arguments = normalize_tool_arguments(tool_call.arguments) |
| 159 | strict_schema = self._strict_input_schemas.get(slug) |
| 160 | if strict_schema is not None: |
| 161 | # Under strict mode optional parameters are emitted as |
| 162 | # required-nullable, so a ``null`` the tool's own schema does not |
| 163 | # accept means "omitted". |
| 164 | arguments = omit_null_tool_arguments(arguments, strict_schema) |
| 165 | |
| 166 | return self.execute_tool_for_target( |
| 167 | target=target, |
| 168 | slug=slug, |
| 169 | arguments=arguments, |
| 170 | modifiers=modifiers, |
| 171 | ) |
| 172 | |
| 173 | @t.overload |
| 174 | def handle_tool_calls( |
| 175 | self, |
| 176 | user_id: str, |
| 177 | response: Response, |
| 178 | modifiers: Modifiers | None = None, |
| 179 | ) -> list[ToolExecutionResponse]: ... |
| 180 | |
| 181 | @t.overload |
| 182 | def handle_tool_calls( |
| 183 | self, |
| 184 | *, |
| 185 | session: ToolCallSession, |
| 186 | response: Response, |
| 187 | ) -> list[ToolExecutionResponse]: ... |
| 188 | |
| 189 | def handle_tool_calls( |
| 190 | self, |
| 191 | user_id: str | None = None, |
| 192 | response: Response | None = None, |
| 193 | modifiers: Modifiers | None = None, |
| 194 | *, |
| 195 | session: ToolCallSession | None = None, |
| 196 | ) -> list[ToolExecutionResponse]: |
| 197 | """ |
| 198 | Handle tool calls from OpenAI Responses API. |
| 199 | |
| 200 | :param response: Response object from openai.OpenAI.beta.responses.create |
| 201 | :param user_id: User ID for direct tool execution. |
| 202 | :param session: Tool Router session that produced session tools. |
| 203 | :param modifiers: Optional modifiers for tool execution |
| 204 | :return: List[ToolExecutionResponse] with tool execution results |
| 205 | """ |
| 206 | if response is None: |
| 207 | raise TypeError("response is required") |
| 208 | self.resolve_tool_call_execution_target(user_id=user_id, session=session) |
| 209 | if session is not None and modifiers is not None: |
| 210 | raise ValueError( |
| 211 | "Direct execution modifiers cannot be used with a Tool Router session" |
| 212 | ) |
| 213 | outputs = [] |
| 214 | |
| 215 | if response.output: |
| 216 | for item in response.output: |
| 217 | if isinstance(item, ResponseFunctionToolCall): |
| 218 | result = ( |
| 219 | self.execute_tool_call( |
| 220 | session=session, |
| 221 | tool_call=item, |
| 222 | ) |
| 223 | if session is not None |
| 224 | else self.execute_tool_call( |
| 225 | user_id=t.cast(str, user_id), |
| 226 | tool_call=item, |
| 227 | modifiers=modifiers, |
| 228 | ) |
| 229 | ) |
| 230 | outputs.append(result) |
| 231 | |
| 232 | return outputs |