Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
fix(python): emit strict and keep base provider config in OpenAIResponsesProvider
The strict flag now calls the base initializer (schema_config kwargs keep working), emits strict on the wrapped tool, and mirrors the TypeScript pipeline: optional parameters become required-nullable, unsupported schemas downgrade the tool to non-strict, and null arguments the tool schema rejects are dropped before execution. Co-authored-by: AseemPrasad <aseemprasad0520@gmail.com> Claude-Session: https://claude.ai/code/session_01TDrxCHn2hg51HmxVstSUgs
jkomyno committed
Aug 26, 2026 at 17:19 UTC
15e2b72f3df81bf3fcdbb8e359fcf25969894f54
3 files changed
+766
-263
python/composio/core/provider/_openai_responses.py
+72
-21
@@ -10,52 +10,97 @@ from openai.types.responses.response import Response
10
from openai.types.responses.response_output_item import ResponseFunctionToolCall
11
12
from composio.core.provider import NonAgenticProvider, ToolCallSession
13
+from composio.core.provider.base import BaseProviderConfig
14
from composio.types import Modifiers, Tool, ToolExecutionResponse
14
-from composio.utils.json_schema import dereference_json_schema
15
+from composio.utils.logging import get as get_logger
16
from composio.utils.shared import normalize_tool_arguments
16
-from composio.utils.strict_schema import to_strict_json_schema
17
+from composio.utils.strict_schema import omit_null_tool_arguments, to_strict_json_schema
18
+
19
+logger = get_logger(__name__)
20
21
# Responses API uses a flattened tool structure
22
ResponsesTool = dict[str, t.Any]
23
ResponsesToolCollection = list[ResponsesTool]
24
25
+# Parameters emitted for a tool without input parameters under strict mode.
26
+_EMPTY_OBJECT_SCHEMA: dict[str, t.Any] = {
27
+ "type": "object",
28
+ "properties": {},
29
+ "required": [],
30
+ "additionalProperties": False,
31
+}
32
+
33
34
class OpenAIResponsesProvider(
35
NonAgenticProvider[ResponsesTool, ResponsesToolCollection], name="openai_responses"
36
):
37
"""OpenAI Responses API Provider class definition."""
38
28
- def __init__(self, strict: bool = False) -> None:
39
+ def __init__(
40
+ self, strict: bool = False, **kwargs: t.Unpack[BaseProviderConfig]
41
+ ) -> None:
42
"""
30
- :param strict: Normalize wrapped tool parameter schemas for OpenAI
31
- structured outputs (every object fully required and closed,
32
- nullable types via ``anyOf``, ``$ref``/``$defs`` inlined).
33
- Mirrors the TypeScript ``OpenAIResponsesProvider({ strict })``
34
- option. Defaults to ``False``.
43
+ :param strict: Emit wrapped tools with ``strict: true`` and normalize
44
+ their parameter schemas for OpenAI structured outputs (every object
45
+ fully required and closed, optional properties widened to accept
46
+ ``null``, ``$ref``/``$defs`` inlined). Mirrors the TypeScript
47
+ ``OpenAIResponsesProvider({ strict })`` option. Defaults to
48
+ ``False``.
49
"""
50
+ super().__init__(**kwargs)
51
self.strict = strict
52
+ # Dereferenced parameter schemas of the tools wrapped under strict
53
+ # mode, keyed by slug, so tool-call arguments can be reconciled
54
+ # against the schema the model actually saw.
55
+ self._strict_input_schemas: dict[str, dict[str, t.Any]] = {}
56
57
def wrap_tool(self, tool: Tool) -> ResponsesTool:
58
"""Wrap a tool for the Responses API format."""
59
parameters: t.Any = tool.input_parameters or {}
41
- if (
42
- self.strict
43
- and isinstance(parameters, dict)
44
- and parameters.get("type") == "object"
45
- ):
46
- # Structured outputs reject schemas whose nested objects keep
47
- # optional properties or their own additionalProperties, so the
48
- # strict contract must be applied at every depth. Inline $refs
49
- # first; lenient mode keeps upstream schemas with dangling refs
50
- # usable.
51
- dereferenced = dereference_json_schema(parameters, on_unresolved="sentinel")
52
- parameters = to_strict_json_schema(dereferenced).schema
53
- return {
60
+ wrapped: ResponsesTool = {
61
"type": "function",
62
"name": tool.slug,
63
"description": tool.description,
64
"parameters": parameters,
65
+ "strict": self.strict,
66
}
67
+ if not self.strict:
68
+ return wrapped
69
+
70
+ # Structured outputs enforce their contract at every depth: all
71
+ # properties required, closed objects, no annotation keywords. The
72
+ # strict rewrite keeps every parameter (optional ones become nullable)
73
+ # and reports constructs it cannot express; such a tool is sent
74
+ # without strict mode rather than with a narrower schema.
75
+ source = parameters if tool.input_parameters else dict(_EMPTY_OBJECT_SCHEMA)
76
+ strict = to_strict_json_schema(source)
77
+ if strict.unsupported:
78
+ reasons = "; ".join(
79
+ f"{entry.path or '<root>'}: {entry.keyword} ({entry.detail})"
80
+ for entry in strict.unsupported
81
+ )
82
+ logger.warning(
83
+ 'OpenAIResponsesProvider: tool "%s" is sent without strict mode '
84
+ "because its schema cannot be expressed as strict structured "
85
+ "outputs: %s",
86
+ tool.slug,
87
+ reasons,
88
+ )
89
+ self._strict_input_schemas.pop(tool.slug, None)
90
+ wrapped["parameters"] = source
91
+ wrapped["strict"] = False
92
+ return wrapped
93
+ if strict.total_changes:
94
+ logger.debug(
95
+ 'OpenAIResponsesProvider: strict mode rewrote %d node(s) of tool "%s": %s',
96
+ strict.total_changes,
97
+ tool.slug,
98
+ "; ".join(f"{c.path}: {c.reason}" for c in strict.changes),
99
+ )
100
+ self._strict_input_schemas[tool.slug] = strict.source
101
+ wrapped["parameters"] = strict.schema
102
+ wrapped["strict"] = True
103
+ return wrapped
104
105
def wrap_tools(self, tools: t.Sequence[Tool]) -> ResponsesToolCollection:
106
"""Wrap multiple tools for the Responses API format."""
@@ -103,6 +148,12 @@ class OpenAIResponsesProvider(
148
# tolerates empty / object-shaped payloads too (issue #2406).
149
slug = tool_call.name
150
arguments = normalize_tool_arguments(tool_call.arguments)
151
+ strict_schema = self._strict_input_schemas.get(slug)
152
+ if strict_schema is not None:
153
+ # Under strict mode optional parameters are emitted as
154
+ # required-nullable, so a ``null`` the tool's own schema does not
155
+ # accept means "omitted".
156
+ arguments = omit_null_tool_arguments(arguments, strict_schema)
157
158
return self.execute_tool_for_target(
159
target=target,
python/composio/utils/strict_schema.py
+277
-158
@@ -3,21 +3,32 @@
3
Python counterpart of the TypeScript SDK's ``toStrictJsonSchema``
4
(``ts/packages/core/src/utils/jsonSchema.ts``). OpenAI's structured-output
5
contract requires *every* object node — not just the root — to list all of its
6
-properties in ``required``, set ``additionalProperties: False``, avoid
7
-annotation-only keywords, and express nullable / multi-typed fields via
8
-``anyOf``. Tool parameter schemas that nest objects or use ``type`` arrays are
9
-otherwise rejected by the API with a 400.
10
-
11
-Every structural change is recorded so callers can surface diagnostics instead
12
-of failing silently. The input is never mutated. Dereference ``$ref`` pointers
13
-first (see :func:`composio.utils.json_schema.dereference_json_schema`) so
14
-definitions under ``$defs`` are normalized too.
6
+properties in ``required``, set ``additionalProperties: False`` and avoid
7
+annotation-only keywords. Optional fields are emulated the way OpenAI
8
+documents: the property stays, becomes required, and is widened to accept
9
+``null`` (``"type": ["string", "null"]`` or an extra ``anyOf`` branch). Nothing
10
+is dropped, so the model keeps every parameter it could pass before; the strict
11
+provider drops a ``null`` the tool's own schema does not accept before
12
+executing the tool (see :func:`omit_null_tool_arguments`).
13
+
14
+Constructs strict mode cannot express — objects that accept arbitrary keys
15
+(schema-valued or ``True`` ``additionalProperties``, ``patternProperties``,
16
+property-less free-form objects), ``allOf``, ``prefixItems``, dangling or
17
+cyclic ``$ref`` pointers and a non-object root — are reported in
18
+``unsupported`` instead of being rewritten into something narrower; the
19
+provider sends such a tool without strict mode.
20
+
21
+The pipeline is ``dereference_json_schema`` (lenient) → strict rewrite →
22
+``required`` de-duplication. The input is never mutated and every rewrite is
23
+recorded (capped at 50 entries; ``total_changes`` carries the real count).
24
"""
25
26
from __future__ import annotations
27
28
import typing as t
29
30
+from composio.utils.json_schema import dereference_json_schema
31
+
32
MAX_NODE_DEPTH = 512
33
MAX_CHANGES = 50
34
@@ -25,9 +36,9 @@ MAX_CHANGES = 50
36
STRICT_STRIP_KEYWORDS = frozenset({"examples", "default"})
37
38
# Keywords whose values are literal data, not schemas - never recursed as schemas.
28
-STRICT_INSTANCE_VALUE_KEYWORDS = frozenset({"const", "enum"})
39
+INSTANCE_VALUE_KEYWORDS = frozenset({"const", "default", "enum", "examples"})
40
30
-STRICT_SCHEMA_SINGLE_KEYS = frozenset(
41
+SCHEMA_KEYWORDS = frozenset(
42
{
43
"additionalItems",
44
"additionalProperties",
@@ -42,190 +53,298 @@ STRICT_SCHEMA_SINGLE_KEYS = frozenset(
53
"unevaluatedProperties",
54
}
55
)
45
-STRICT_SCHEMA_ARRAY_KEYS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"})
46
-STRICT_SCHEMA_MAP_KEYS = frozenset(
56
+SCHEMA_ARRAY_KEYWORDS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"})
57
+SCHEMA_MAP_KEYWORDS = frozenset(
58
{"$defs", "definitions", "dependentSchemas", "patternProperties", "properties"}
59
)
60
61
+# Keywords OpenAI structured outputs reject and that have no lossless rewrite.
62
+STRICT_UNSUPPORTED_KEYWORDS = ("allOf", "prefixItems")
63
+
64
+StrictSchemaChangeReason = t.Literal[
65
+ "optional-property-nullable",
66
+ "unsupported-keyword-stripped",
67
+ "one-of-converted",
68
+]
69
+
70
71
class StrictSchemaChange(t.NamedTuple):
52
- """A single structural change applied by :func:`to_strict_json_schema`."""
72
+ """A single lossless rewrite applied by :func:`to_strict_json_schema`."""
73
74
path: str
55
- reason: str
75
+ reason: StrictSchemaChangeReason
76
detail: str = ""
77
78
79
+class StrictSchemaIncompatibility(t.NamedTuple):
80
+ """A construct strict structured outputs cannot express."""
81
+
82
+ path: str
83
+ keyword: str
84
+ detail: str
85
+
86
+
87
class StrictJsonSchemaResult(t.NamedTuple):
60
- """Normalized schema plus a change log."""
88
+ """Result of :func:`to_strict_json_schema`."""
89
62
- schema: t.Any
90
+ schema: dict[str, t.Any]
91
+ """The strict schema; only usable when ``unsupported`` is empty."""
92
+ source: dict[str, t.Any]
93
+ """The dereferenced input optionality was decided against."""
94
changes: list[StrictSchemaChange]
95
+ total_changes: int
96
+ unsupported: list[StrictSchemaIncompatibility]
97
98
99
def _join_path(parent: str, key: str) -> str:
100
return f"{parent}.{key}" if parent else key
101
102
70
-def _split_type_array(
71
- node: dict[str, t.Any], path: str, changes: list[StrictSchemaChange]
72
-) -> dict[str, t.Any]:
73
- type_values = node["type"]
74
- branches = [
75
- {"type": "null"} if value == "null" else {**node, "type": value}
76
- for value in type_values
77
- ]
78
- rest = {key: value for key, value in node.items() if key != "type"}
79
- reason = (
80
- "nullable-type-converted" if "null" in type_values else "multi-type-converted"
81
- )
82
- if len(changes) < MAX_CHANGES:
83
- changes.append(
84
- StrictSchemaChange(
85
- path=path,
86
- reason=reason,
87
- detail=f"type [{', '.join(str(value) for value in type_values)}] converted to anyOf",
88
- )
89
- )
90
- return {**rest, "anyOf": branches}
91
-
92
-
93
-def _walk(
94
- value: t.Any,
95
- mode: str,
96
- depth: int,
97
- path: str,
98
- changes: list[StrictSchemaChange],
99
-) -> t.Any:
103
+def _widen_to_nullable(node: dict[str, t.Any]) -> dict[str, t.Any]:
104
+ """Accept ``null`` without placing ``type`` beside ``anyOf``."""
105
+ any_of = node.get("anyOf")
106
+ if isinstance(any_of, list):
107
+ if any(isinstance(b, dict) and b.get("type") == "null" for b in any_of):
108
+ return node
109
+ return {**node, "anyOf": [*any_of, {"type": "null"}]}
110
+ node_type = node.get("type")
111
+ if isinstance(node_type, str):
112
+ return node if node_type == "null" else {**node, "type": [node_type, "null"]}
113
+ if isinstance(node_type, list):
114
+ return node if "null" in node_type else {**node, "type": [*node_type, "null"]}
115
+ annotations: dict[str, t.Any] = {
116
+ k: node[k] for k in ("description", "title") if k in node
117
+ }
118
+ rest = {k: v for k, v in node.items() if k not in annotations}
119
+ if not rest:
120
+ return node
121
+ return {**annotations, "anyOf": [rest, {"type": "null"}]}
122
+
123
+
124
+def _schema_accepts_null(node: t.Any) -> bool:
125
+ """Whether a (dereferenced) schema node accepts ``null`` as an instance."""
126
+ if not isinstance(node, dict):
127
+ return True
128
+ node_type = node.get("type")
129
+ if isinstance(node_type, str):
130
+ return node_type == "null"
131
+ if isinstance(node_type, list):
132
+ return "null" in node_type
133
+ if isinstance(node.get("enum"), list):
134
+ return None in node["enum"]
135
+ if "const" in node:
136
+ return node["const"] is None
137
+ for keyword in ("anyOf", "oneOf"):
138
+ branches = node.get(keyword)
139
+ if isinstance(branches, list):
140
+ return any(_schema_accepts_null(b) for b in branches)
141
+ return True
142
+
143
+
144
+def _dedupe_required(value: t.Any, is_schema: bool = True, depth: int = 0) -> t.Any:
145
if depth > MAX_NODE_DEPTH:
146
raise ValueError(
147
f"JSON Schema exceeds maximum nesting depth of {MAX_NODE_DEPTH}"
148
)
104
-
149
if isinstance(value, list):
106
- item_mode = "schema" if mode == "schema-array" else "value"
107
- return [
108
- _walk(item, item_mode, depth + 1, f"{path}[{index}]", changes)
109
- for index, item in enumerate(value)
110
- ]
111
-
112
- if not isinstance(value, dict) or mode == "value":
150
+ return [_dedupe_required(item, is_schema, depth + 1) for item in value]
151
+ if not isinstance(value, dict):
152
return value
153
+ clone: dict[str, t.Any] = {}
154
+ for key, child in value.items():
155
+ if is_schema and key == "required" and isinstance(child, list):
156
+ clone[key] = list(dict.fromkeys(child))
157
+ else:
158
+ clone[key] = _dedupe_required(
159
+ child, is_schema and key not in INSTANCE_VALUE_KEYWORDS, depth + 1
160
+ )
161
+ return clone
162
115
- node: dict[str, t.Any] = value
116
-
117
- # Nullable / multi-type arrays must become anyOf before anything else so
118
- # the generated branches flow through the normal recursion below.
119
- if isinstance(node.get("type"), list):
120
- node = _split_type_array(node, path, changes)
121
-
122
- stripped: dict[str, t.Any] = {}
123
- for key, child in node.items():
124
- if key in STRICT_STRIP_KEYWORDS:
125
- if len(changes) < MAX_CHANGES:
126
- changes.append(
127
- StrictSchemaChange(
128
- path=path,
129
- reason="annotation-keyword-stripped",
130
- detail=f'keyword "{key}" removed',
163
+
164
+class _Walker:
165
+ def __init__(self) -> None:
166
+ self.changes: list[StrictSchemaChange] = []
167
+ self.total_changes = 0
168
+ self.unsupported: list[StrictSchemaIncompatibility] = []
169
+
170
+ def record(self, path: str, reason: StrictSchemaChangeReason, detail: str) -> None:
171
+ self.total_changes += 1
172
+ if len(self.changes) < MAX_CHANGES:
173
+ self.changes.append(StrictSchemaChange(path, reason, detail))
174
+
175
+ def reject(self, path: str, keyword: str, detail: str) -> None:
176
+ self.unsupported.append(StrictSchemaIncompatibility(path, keyword, detail))
177
+
178
+ def walk_children(
179
+ self, node: dict[str, t.Any], mode: str, depth: int, path: str
180
+ ) -> dict[str, t.Any]:
181
+ clone: dict[str, t.Any] = {}
182
+ for key, child in node.items():
183
+ child_mode = "value"
184
+ if mode == "schema-map":
185
+ child_mode = "schema"
186
+ elif mode == "schema" and key not in INSTANCE_VALUE_KEYWORDS:
187
+ if key in SCHEMA_MAP_KEYWORDS:
188
+ child_mode = "schema-map"
189
+ elif key in SCHEMA_ARRAY_KEYWORDS or (
190
+ key == "items" and isinstance(child, list)
191
+ ):
192
+ child_mode = "schema-array"
193
+ elif key in SCHEMA_KEYWORDS or key == "items":
194
+ child_mode = "schema"
195
+
196
+ if child_mode == "schema-map" and isinstance(child, dict):
197
+ clone[key] = {
198
+ name: self.walk(
199
+ sub_schema,
200
+ "schema",
201
+ depth + 1,
202
+ _join_path(_join_path(path, key), name),
203
)
132
- )
133
- continue
134
- stripped[key] = child
135
- node = stripped
136
-
137
- has_properties_keyword = isinstance(node.get("properties"), dict)
138
- if not (has_properties_keyword or node.get("type") == "object"):
139
- return _walk_children(node, mode, depth, path, changes)
140
-
141
- properties = node["properties"] if has_properties_keyword else {}
142
- declared_required = [
143
- entry for entry in node.get("required", []) if isinstance(entry, str)
144
- ]
145
- keep_only_required = len(declared_required) > 0
146
- kept = set(declared_required if keep_only_required else properties.keys())
147
-
148
- next_properties: dict[str, t.Any] = {}
149
- for name, property_schema in properties.items():
150
- child_path = _join_path(path, f"properties.{name}")
151
- if name in kept:
152
- next_properties[name] = _walk(
153
- property_schema, "schema", depth + 1, child_path, changes
204
+ for name, sub_schema in child.items()
205
+ }
206
+ continue
207
+ clone[key] = self.walk(child, child_mode, depth + 1, _join_path(path, key))
208
+ return clone
209
+
210
+ def walk(self, value: t.Any, mode: str, depth: int, path: str) -> t.Any:
211
+ if depth > MAX_NODE_DEPTH:
212
+ raise ValueError(
213
+ f"JSON Schema exceeds maximum nesting depth of {MAX_NODE_DEPTH}"
214
)
155
- elif len(changes) < MAX_CHANGES:
156
- changes.append(
157
- StrictSchemaChange(
158
- path=child_path,
159
- reason="non-required-property-dropped",
160
- detail=f'property "{name}" is not listed in "required"',
215
+ if isinstance(value, list):
216
+ item_mode = "schema" if mode == "schema-array" else "value"
217
+ return [
218
+ self.walk(item, item_mode, depth + 1, f"{path}[{index}]")
219
+ for index, item in enumerate(value)
220
+ ]
221
+ if not isinstance(value, dict) or mode == "value":
222
+ return value
223
+
224
+ node: dict[str, t.Any] = {}
225
+ for key, child in value.items():
226
+ if key in STRICT_STRIP_KEYWORDS:
227
+ self.record(
228
+ path, "unsupported-keyword-stripped", f'keyword "{key}" removed'
229
)
230
+ continue
231
+ node[key] = child
232
+ if isinstance(node.get("oneOf"), list) and "anyOf" not in node:
233
+ node["anyOf"] = node.pop("oneOf")
234
+ self.record(path, "one-of-converted", "oneOf became anyOf")
235
+ for keyword in STRICT_UNSUPPORTED_KEYWORDS:
236
+ if keyword in node:
237
+ self.reject(path, keyword, f'"{keyword}" has no strict-mode equivalent')
238
+
239
+ out = self.walk_children(node, mode, depth, path)
240
+
241
+ node_type = out.get("type")
242
+ declares_object = node_type == "object" or (
243
+ isinstance(node_type, list) and "object" in node_type
244
+ )
245
+ if not declares_object and not isinstance(out.get("properties"), dict):
246
+ return out
247
+
248
+ properties: dict[str, t.Any] = dict(out.get("properties") or {})
249
+ declared_required = {
250
+ entry for entry in out.get("required") or [] if isinstance(entry, str)
251
+ }
252
+ for name, property_schema in properties.items():
253
+ if name in declared_required or not isinstance(property_schema, dict):
254
+ continue
255
+ properties[name] = _widen_to_nullable(property_schema)
256
+ self.record(
257
+ _join_path(path, f"properties.{name}"),
258
+ "optional-property-nullable",
259
+ f'property "{name}" is now required and accepts null',
260
)
261
164
- managed = ("type", "properties", "required", "additionalProperties")
165
- rest = {key: child for key, child in node.items() if key not in managed}
262
+ additional = out.get("additionalProperties")
263
+ accepts_dynamic_keys = additional is True or isinstance(additional, dict)
264
+ if accepts_dynamic_keys:
265
+ self.reject(path, "additionalProperties", "object accepts arbitrary keys")
266
+ elif "patternProperties" in out:
267
+ self.reject(
268
+ path, "patternProperties", "object accepts pattern-matched keys"
269
+ )
270
+ elif not properties and "additionalProperties" not in out:
271
+ self.reject(path, "properties", "free-form object accepts arbitrary keys")
272
167
- return {
168
- **_walk_children(rest, "schema", depth, path, changes),
169
- "type": "object",
170
- "properties": next_properties,
171
- "required": list(next_properties.keys()),
172
- "additionalProperties": False,
173
- }
273
+ result = {**out}
274
+ if "type" not in result:
275
+ result["type"] = "object"
276
+ result["properties"] = properties
277
+ result["required"] = list(properties.keys())
278
+ if not accepts_dynamic_keys:
279
+ result["additionalProperties"] = False
280
+ return result
281
282
176
-def _walk_children(
177
- node: dict[str, t.Any],
178
- mode: str,
179
- depth: int,
180
- path: str,
181
- changes: list[StrictSchemaChange],
182
-) -> dict[str, t.Any]:
183
- clone: dict[str, t.Any] = {}
184
- for key, child in node.items():
185
- child_mode = "value"
186
- if mode == "schema-map":
187
- child_mode = "schema"
188
- elif mode == "schema" and key not in STRICT_INSTANCE_VALUE_KEYWORDS:
189
- if key in STRICT_SCHEMA_MAP_KEYS:
190
- child_mode = "schema-map"
191
- elif key in STRICT_SCHEMA_ARRAY_KEYS or (
192
- key == "items" and isinstance(child, list)
193
- ):
194
- child_mode = "schema-array"
195
- elif key in STRICT_SCHEMA_SINGLE_KEYS or key == "items":
196
- child_mode = "schema"
283
+def to_strict_json_schema(schema: t.Any) -> StrictJsonSchemaResult:
284
+ """Normalize a tool parameter schema for OpenAI structured outputs.
285
198
- if child_mode == "schema-map" and isinstance(child, dict):
199
- map_clone: dict[str, t.Any] = {}
200
- for name, sub_schema in child.items():
201
- map_clone[name] = _walk(
202
- sub_schema,
203
- "schema",
204
- depth + 1,
205
- _join_path(_join_path(path, key), name),
206
- changes,
207
- )
208
- clone[key] = map_clone
209
- continue
210
- clone[key] = _walk(child, child_mode, depth + 1, _join_path(path, key), changes)
211
- return clone
286
+ Applies the strict contract at every depth: every object lists all of its
287
+ properties in ``required`` and is closed; optional properties are widened
288
+ to accept ``null`` instead of being dropped; ``oneOf`` becomes ``anyOf``;
289
+ ``default`` and ``examples`` are stripped; internal ``$ref`` pointers are
290
+ inlined first and ``required`` arrays are de-duplicated last. Constructs
291
+ strict mode cannot express are listed in ``unsupported``; when that list
292
+ is non-empty the returned ``schema`` must not be sent as strict.
293
294
+ :param schema: The JSON schema to normalize; never mutated.
295
+ :return: A :class:`StrictJsonSchemaResult`.
296
+ """
297
+ walker = _Walker()
298
+ dereferenced = dereference_json_schema(
299
+ schema,
300
+ on_unresolved="sentinel",
301
+ on_replace=lambda ref, _reason: walker.reject(
302
+ "", "$ref", f'unresolved $ref "{ref}"'
303
+ ),
304
+ )
305
+ normalized = _dedupe_required(walker.walk(dereferenced, "schema", 0, ""))
306
+ if not isinstance(normalized, dict) or normalized.get("type") != "object":
307
+ walker.reject("", "type", "root must be a non-nullable object")
308
+ return StrictJsonSchemaResult(
309
+ schema=normalized,
310
+ source=dereferenced,
311
+ changes=walker.changes,
312
+ total_changes=walker.total_changes,
313
+ unsupported=walker.unsupported,
314
+ )
315
214
-def to_strict_json_schema(schema: t.Any) -> StrictJsonSchemaResult:
215
- """Normalize a JSON Schema for OpenAI structured outputs.
316
217
- Applies the strict contract at every depth:
317
+def omit_null_tool_arguments(
318
+ arguments: dict[str, t.Any], schema: t.Any
319
+) -> dict[str, t.Any]:
320
+ """Drop ``None``-valued arguments the tool's own schema does not accept.
321
+
322
+ Strict structured outputs cannot express optional parameters, so
323
+ :func:`to_strict_json_schema` makes every parameter required and nullable.
324
+ The model then sends ``null`` for a parameter it would otherwise have
325
+ omitted; forwarding it to the tool would fail validation against the
326
+ tool's real schema, so it is treated as "omitted". A ``null`` the original
327
+ schema accepts is kept. ``schema`` is the dereferenced tool schema
328
+ (``StrictJsonSchemaResult.source``). The input is not mutated.
329
+ """
330
+ return t.cast(dict[str, t.Any], _omit_nulls(arguments, schema))
331
219
- - Objects with a non-empty ``required`` keep only those properties;
220
- objects without one keep every property but require them all.
221
- - ``type`` arrays become ``anyOf`` branches with an explicit null variant.
222
- - Annotation keywords (``examples``, ``default``) are stripped.
223
- - Composition keywords, array items and property maps normalize recursively.
332
225
- :param schema: The JSON schema to normalize; never mutated.
226
- :return: A :class:`StrictJsonSchemaResult` with the normalized schema and
227
- a change log capped at 50 entries.
228
- """
229
- changes: list[StrictSchemaChange] = []
230
- normalized = _walk(schema, "schema", 0, "", changes)
231
- return StrictJsonSchemaResult(schema=normalized, changes=changes)
333
+def _omit_nulls(value: t.Any, schema: t.Any) -> t.Any:
334
+ node = schema if isinstance(schema, dict) else {}
335
+ if isinstance(value, list):
336
+ items = node.get("items") if isinstance(node.get("items"), dict) else None
337
+ return [_omit_nulls(item, items) for item in value]
338
+ if not isinstance(value, dict):
339
+ return value
340
+ declared = node.get("properties")
341
+ properties: dict[str, t.Any] = declared if isinstance(declared, dict) else {}
342
+ clone: dict[str, t.Any] = {}
343
+ for key, child in value.items():
344
+ property_schema = properties.get(key)
345
+ if child is None:
346
+ if property_schema is None or _schema_accepts_null(property_schema):
347
+ clone[key] = child
348
+ continue
349
+ clone[key] = _omit_nulls(child, property_schema)
350
+ return clone
python/tests/test_strict_schema.py
+417
-84
@@ -1,8 +1,39 @@
1
"""Tests for composio.utils.strict_schema and its use by OpenAIResponsesProvider."""
2
3
+import copy
4
+import json
5
+
6
import pytest
7
5
-from composio.utils.strict_schema import to_strict_json_schema
8
+from composio.utils.strict_schema import omit_null_tool_arguments, to_strict_json_schema
9
+
10
+
11
+def assert_strict_shape(node, path=""):
12
+ """Structural invariants OpenAI enforces on every node of a strict schema."""
13
+ if isinstance(node, list):
14
+ for index, item in enumerate(node):
15
+ assert_strict_shape(item, f"{path}[{index}]")
16
+ return
17
+ if not isinstance(node, dict):
18
+ return
19
+ if "anyOf" in node:
20
+ assert "type" not in node, f"{path}: type beside anyOf"
21
+ for keyword in ("default", "examples", "oneOf", "patternProperties"):
22
+ assert keyword not in node, f"{path}: {keyword}"
23
+ node_type = node.get("type")
24
+ is_object = node_type == "object" or (
25
+ isinstance(node_type, list) and "object" in node_type
26
+ )
27
+ if is_object or "properties" in node:
28
+ properties = node.get("properties") or {}
29
+ assert node.get("required") == list(properties.keys()), f"{path}: required"
30
+ assert node.get("additionalProperties") is False, (
31
+ f"{path}: additionalProperties"
32
+ )
33
+ for key, child in node.items():
34
+ if key in ("enum", "const"):
35
+ continue
36
+ assert_strict_shape(child, f"{path}.{key}" if path else key)
37
38
39
class TestToStrictJsonSchema:
@@ -19,7 +50,7 @@ class TestToStrictJsonSchema:
50
assert result.schema == schema
51
assert result.changes == []
52
22
- def test_drops_nested_non_required_properties_and_closes_every_object(self):
53
+ def test_keeps_optional_properties_required_and_nullable(self):
54
result = to_strict_json_schema(
55
{
56
"type": "object",
@@ -28,7 +59,7 @@ class TestToStrictJsonSchema:
59
"type": "object",
60
"properties": {
61
"url": {"type": "string"},
31
- "note": {"type": "string"},
62
+ "note": {"type": "string", "description": "optional note"},
63
},
64
"required": ["url"],
65
}
@@ -42,23 +73,25 @@ class TestToStrictJsonSchema:
73
"properties": {
74
"cfg": {
75
"type": "object",
45
- "properties": {"url": {"type": "string"}},
46
- "required": ["url"],
76
+ "properties": {
77
+ "url": {"type": "string"},
78
+ "note": {
79
+ "type": ["string", "null"],
80
+ "description": "optional note",
81
+ },
82
+ },
83
+ "required": ["url", "note"],
84
"additionalProperties": False,
85
}
86
},
87
"required": ["cfg"],
88
"additionalProperties": False,
89
}
53
- dropped = [
54
- change
55
- for change in result.changes
56
- if change.reason == "non-required-property-dropped"
90
+ assert [(c.path, c.reason) for c in result.changes] == [
91
+ ("properties.cfg.properties.note", "optional-property-nullable")
92
]
58
- assert len(dropped) == 1
59
- assert "note" in dropped[0].detail
93
61
- def test_requires_every_property_when_required_is_missing(self):
94
+ def test_requires_and_widens_every_property_when_required_is_missing(self):
95
result = to_strict_json_schema(
96
{
97
"type": "object",
@@ -66,31 +99,74 @@ class TestToStrictJsonSchema:
99
}
100
)
101
69
- assert result.schema["required"] == ["a", "b"]
70
- assert result.schema["additionalProperties"] is False
102
+ assert result.schema == {
103
+ "type": "object",
104
+ "properties": {
105
+ "a": {"type": ["string", "null"]},
106
+ "b": {"type": ["number", "null"]},
107
+ },
108
+ "required": ["a", "b"],
109
+ "additionalProperties": False,
110
+ }
111
72
- def test_converts_nullable_type_arrays_into_any_of(self):
112
+ def test_keeps_nullable_type_arrays_and_closes_nullable_objects(self):
113
result = to_strict_json_schema(
114
{
115
"type": "object",
116
"properties": {
77
- "id": {"type": ["string", "null"], "description": "identifier"}
117
+ "id": {"type": ["string", "null"], "description": "identifier"},
118
+ "cfg": {
119
+ "type": ["object", "null"],
120
+ "properties": {"a": {"type": "string"}},
121
+ "required": ["a"],
122
+ },
123
+ "xs": {"type": ["array", "null"], "items": {"type": "string"}},
124
},
79
- "required": ["id"],
125
+ "required": ["id", "cfg", "xs"],
126
}
127
)
128
129
+ assert result.schema["properties"]["cfg"] == {
130
+ "type": ["object", "null"],
131
+ "properties": {"a": {"type": "string"}},
132
+ "required": ["a"],
133
+ "additionalProperties": False,
134
+ }
135
assert result.schema["properties"]["id"] == {
84
- "anyOf": [
85
- {"type": "string", "description": "identifier"},
86
- {"type": "null"},
87
- ],
136
+ "type": ["string", "null"],
137
"description": "identifier",
138
}
90
- reasons = {change.reason for change in result.changes}
91
- assert "nullable-type-converted" in reasons
139
+ assert result.changes == []
140
+ assert_strict_shape(result.schema)
141
+
142
+ def test_widens_composition_and_enum_properties_without_type_beside_any_of(self):
143
+ result = to_strict_json_schema(
144
+ {
145
+ "type": "object",
146
+ "properties": {
147
+ "value": {"anyOf": [{"type": "string"}, {"type": "number"}]},
148
+ "already": {"anyOf": [{"type": "string"}, {"type": "null"}]},
149
+ "choice": {"enum": ["a", "b"], "description": "pick one"},
150
+ "multi": {"type": ["string", "number"]},
151
+ },
152
+ }
153
+ )
154
+
155
+ properties = result.schema["properties"]
156
+ assert properties["value"] == {
157
+ "anyOf": [{"type": "string"}, {"type": "number"}, {"type": "null"}]
158
+ }
159
+ assert properties["already"] == {
160
+ "anyOf": [{"type": "string"}, {"type": "null"}]
161
+ }
162
+ assert properties["choice"] == {
163
+ "description": "pick one",
164
+ "anyOf": [{"enum": ["a", "b"]}, {"type": "null"}],
165
+ }
166
+ assert properties["multi"] == {"type": ["string", "number", "null"]}
167
+ assert_strict_shape(result.schema)
168
93
- def test_normalizes_composition_branches_recursively(self):
169
+ def test_normalizes_composition_branches_and_array_items_recursively(self):
170
result = to_strict_json_schema(
171
{
172
"type": "object",
@@ -107,25 +183,7 @@ class TestToStrictJsonSchema:
183
},
184
{"type": "null"},
185
]
110
- }
111
- },
112
- "required": ["payload"],
113
- }
114
- )
115
-
116
- branch = result.schema["properties"]["payload"]["anyOf"][0]
117
- assert branch == {
118
- "type": "object",
119
- "properties": {"inner": {"type": "string"}},
120
- "required": ["inner"],
121
- "additionalProperties": False,
122
- }
123
-
124
- def test_normalizes_array_items(self):
125
- result = to_strict_json_schema(
126
- {
127
- "type": "object",
128
- "properties": {
186
+ },
187
"rows": {
188
"type": "array",
189
"items": {
@@ -136,54 +194,206 @@ class TestToStrictJsonSchema:
194
},
195
"required": ["id"],
196
},
139
- }
197
+ },
198
+ "either": {"oneOf": [{"type": "string"}, {"type": "number"}]},
199
},
141
- "required": ["rows"],
200
+ "required": ["payload", "rows", "either"],
201
}
202
)
203
145
- assert result.schema["properties"]["rows"]["items"] == {
204
+ assert result.schema["properties"]["payload"]["anyOf"][0] == {
205
"type": "object",
147
- "properties": {"id": {"type": "string"}},
148
- "required": ["id"],
206
+ "properties": {
207
+ "inner": {"type": "string"},
208
+ "extra": {"type": ["string", "null"]},
209
+ },
210
+ "required": ["inner", "extra"],
211
"additionalProperties": False,
212
}
213
+ assert result.schema["properties"]["rows"]["items"]["required"] == ["id", "tag"]
214
+ assert result.schema["properties"]["either"] == {
215
+ "anyOf": [{"type": "string"}, {"type": "number"}]
216
+ }
217
+ assert "one-of-converted" in {c.reason for c in result.changes}
218
+ assert_strict_shape(result.schema)
219
152
- def test_strips_annotation_keywords_and_reports_them(self):
220
+ def test_reports_dynamic_key_and_free_form_objects_as_unsupported(self):
221
result = to_strict_json_schema(
222
{
223
"type": "object",
224
"properties": {
157
- "name": {"type": "string", "examples": ["a"], "default": "x"}
225
+ "headers": {
226
+ "type": "object",
227
+ "additionalProperties": {"type": "string"},
228
+ },
229
+ "meta": {"type": "object", "description": "any json"},
230
+ "tagged": {
231
+ "type": "object",
232
+ "patternProperties": {"^x-": {"type": "string"}},
233
+ },
234
+ "open": {"type": "object", "additionalProperties": True},
235
+ },
236
+ "required": ["headers", "meta", "tagged", "open"],
237
+ }
238
+ )
239
+
240
+ assert [(e.path, e.keyword) for e in result.unsupported] == [
241
+ ("properties.headers", "additionalProperties"),
242
+ ("properties.meta", "properties"),
243
+ ("properties.tagged", "patternProperties"),
244
+ ("properties.open", "additionalProperties"),
245
+ ]
246
+ # The schema-valued additionalProperties is preserved, not overwritten.
247
+ assert result.schema["properties"]["headers"]["additionalProperties"] == {
248
+ "type": "string"
249
+ }
250
+ assert "patternProperties" in result.schema["properties"]["tagged"]
251
+
252
+ def test_strips_annotation_keywords_and_reports_keywords_it_cannot_rewrite(self):
253
+ result = to_strict_json_schema(
254
+ {
255
+ "type": "object",
256
+ "properties": {
257
+ "name": {"type": "string", "examples": ["a"], "default": "x"},
258
+ "pair": {"type": "array", "prefixItems": [{"type": "number"}]},
259
+ "all": {"allOf": [{"type": "string"}]},
260
},
159
- "required": ["name"],
261
+ "required": ["name", "pair", "all"],
262
}
263
)
264
265
assert result.schema["properties"]["name"] == {"type": "string"}
164
- stripped = [
165
- change
166
- for change in result.changes
167
- if change.reason == "annotation-keyword-stripped"
266
+ reasons = [c.reason for c in result.changes]
267
+ assert reasons.count("unsupported-keyword-stripped") == 2
268
+ assert [(e.path, e.keyword) for e in result.unsupported] == [
269
+ ("properties.pair", "prefixItems"),
270
+ ("properties.all", "allOf"),
271
]
169
- assert len(stripped) == 2
272
+
273
+ def test_inlines_refs_dedupes_required_and_reports_dangling_refs(self):
274
+ result = to_strict_json_schema(
275
+ {
276
+ "type": "object",
277
+ "properties": {
278
+ "cfg": {"$ref": "#/$defs/Config"},
279
+ "missing": {"$ref": "#/$defs/Nope"},
280
+ },
281
+ "required": ["cfg", "cfg", "missing"],
282
+ "$defs": {
283
+ "Config": {
284
+ "type": "object",
285
+ "properties": {
286
+ "url": {"type": "string"},
287
+ "note": {"type": "string"},
288
+ },
289
+ "required": ["url"],
290
+ }
291
+ },
292
+ }
293
+ )
294
+
295
+ assert "$ref" not in json.dumps(result.schema)
296
+ assert "$defs" not in result.schema
297
+ assert result.schema["properties"]["cfg"] == {
298
+ "type": "object",
299
+ "properties": {
300
+ "url": {"type": "string"},
301
+ "note": {"type": ["string", "null"]},
302
+ },
303
+ "required": ["url", "note"],
304
+ "additionalProperties": False,
305
+ }
306
+ assert result.schema["required"] == ["cfg", "missing"]
307
+ assert [(e.path, e.keyword) for e in result.unsupported] == [
308
+ ("", "$ref"),
309
+ ("properties.missing", "additionalProperties"),
310
+ ]
311
+ assert ("properties.cfg.properties.note", "optional-property-nullable") in [
312
+ (c.path, c.reason) for c in result.changes
313
+ ]
314
+
315
+ def test_caps_the_change_log_without_losing_properties(self):
316
+ properties = {f"p{i}": {"type": "string"} for i in range(60)}
317
+
318
+ result = to_strict_json_schema(
319
+ {"type": "object", "properties": properties, "required": ["p0"]}
320
+ )
321
+
322
+ assert len(result.schema["properties"]) == 60
323
+ assert len(result.changes) == 50
324
+ assert result.total_changes == 59
325
326
def test_does_not_mutate_input(self):
327
schema = {
328
"type": "object",
329
"properties": {
175
- "cfg": {"type": "object", "properties": {"opt": {"type": "string"}}}
330
+ "cfg": {
331
+ "type": "object",
332
+ "properties": {"opt": {"type": "string", "default": 1}},
333
+ }
334
},
335
"required": ["cfg"],
336
}
179
- import copy
180
-
337
snapshot = copy.deepcopy(schema)
338
339
to_strict_json_schema(schema)
340
341
assert schema == snapshot
342
343
+ def test_is_idempotent(self):
344
+ once = to_strict_json_schema(
345
+ {
346
+ "type": "object",
347
+ "properties": {
348
+ "cfg": {"$ref": "#/$defs/Config"},
349
+ "id": {"type": ["string", "null"]},
350
+ },
351
+ "$defs": {
352
+ "Config": {
353
+ "type": "object",
354
+ "properties": {
355
+ "url": {"type": "string"},
356
+ "note": {"type": "string"},
357
+ },
358
+ "required": ["url"],
359
+ }
360
+ },
361
+ }
362
+ ).schema
363
+
364
+ twice = to_strict_json_schema(once)
365
+
366
+ assert twice.schema == once
367
+ assert twice.changes == []
368
+ assert twice.unsupported == []
369
+
370
+ def test_reports_non_object_and_cyclic_roots_as_unsupported(self):
371
+ assert [
372
+ (e.path, e.keyword)
373
+ for e in to_strict_json_schema({"type": "string"}).unsupported
374
+ ] == [("", "type")]
375
+ nullable_root = to_strict_json_schema(
376
+ {"type": ["object", "null"], "properties": {"a": {"type": "string"}}}
377
+ )
378
+ assert ("", "type") in [(e.path, e.keyword) for e in nullable_root.unsupported]
379
+
380
+ cyclic = to_strict_json_schema(
381
+ {
382
+ "type": "object",
383
+ "properties": {"node": {"$ref": "#/$defs/Node"}},
384
+ "required": ["node"],
385
+ "$defs": {
386
+ "Node": {
387
+ "type": "object",
388
+ "properties": {"child": {"$ref": "#/$defs/Node"}},
389
+ "required": ["child"],
390
+ }
391
+ },
392
+ }
393
+ )
394
+ # The cycle-break sentinel is a free-form object strict mode cannot express.
395
+ assert "additionalProperties" in {e.keyword for e in cyclic.unsupported}
396
+
397
def test_raises_past_maximum_depth(self):
398
deep = {"type": "string"}
399
for _ in range(600):
@@ -193,10 +403,54 @@ class TestToStrictJsonSchema:
403
"required": ["nest"],
404
}
405
196
- with pytest.raises(ValueError, match="maximum nesting depth"):
406
+ with pytest.raises(Exception, match="depth"):
407
to_strict_json_schema(deep)
408
409
410
+_OMIT_SCHEMA = {
411
+ "type": "object",
412
+ "properties": {
413
+ "cfg": {
414
+ "type": "object",
415
+ "properties": {"url": {"type": "string"}, "note": {"type": "string"}},
416
+ "required": ["url"],
417
+ },
418
+ "label": {"type": "string"},
419
+ "clearable": {"type": ["string", "null"]},
420
+ "choice": {"anyOf": [{"enum": ["a"]}, {"type": "null"}]},
421
+ "rows": {
422
+ "type": "array",
423
+ "items": {
424
+ "type": "object",
425
+ "properties": {"id": {"type": "string"}, "tag": {"type": "string"}},
426
+ },
427
+ },
428
+ },
429
+}
430
+
431
+
432
+class TestOmitNullToolArguments:
433
+ def test_drops_nulls_the_schema_rejects_and_keeps_the_ones_it_accepts(self):
434
+ arguments = {
435
+ "cfg": {"url": "https://example.com", "note": None},
436
+ "label": None,
437
+ "clearable": None,
438
+ "choice": None,
439
+ "unknown": None,
440
+ "rows": [{"id": "1", "tag": None}, None],
441
+ }
442
+ snapshot = copy.deepcopy(arguments)
443
+
444
+ assert omit_null_tool_arguments(arguments, _OMIT_SCHEMA) == {
445
+ "cfg": {"url": "https://example.com"},
446
+ "clearable": None,
447
+ "choice": None,
448
+ "unknown": None,
449
+ "rows": [{"id": "1"}, None],
450
+ }
451
+ assert arguments == snapshot
452
+
453
+
454
class TestOpenAIResponsesProviderStrict:
455
def _tool(self, input_parameters):
456
from tests.test_provider import create_mock_tool
@@ -212,8 +466,19 @@ class TestOpenAIResponsesProviderStrict:
466
wrapped = provider.wrap_tool(self._tool({"type": "object", "properties": {}}))
467
468
assert wrapped["parameters"] == {"type": "object", "properties": {}}
469
+ assert wrapped["strict"] is False
470
+
471
+ def test_constructor_keeps_base_provider_config(self):
472
+ from composio.core.provider._openai_responses import OpenAIResponsesProvider
473
+
474
+ provider = OpenAIResponsesProvider(
475
+ strict=True, schema_config={"skip_defaults": True}
476
+ )
477
216
- def test_wrap_tool_normalizes_complex_schemas_in_strict_mode(self):
478
+ assert provider.strict is True
479
+ assert provider.skip_default is True
480
+
481
+ def test_wrap_tool_emits_strict_and_normalizes_complex_schemas(self):
482
from composio.core.provider._openai_responses import OpenAIResponsesProvider
483
484
provider = OpenAIResponsesProvider(strict=True)
@@ -223,62 +488,130 @@ class TestOpenAIResponsesProviderStrict:
488
"type": "object",
489
"properties": {
490
"cfg": {
491
+ "$ref": "#/$defs/Config",
492
+ },
493
+ "id": {"type": ["string", "null"]},
494
+ "label": {"type": "string"},
495
+ },
496
+ "required": ["cfg", "id"],
497
+ "$defs": {
498
+ "Config": {
499
"type": "object",
500
"properties": {
501
"url": {"type": "string"},
502
"note": {"type": "string"},
503
},
504
"required": ["url"],
232
- },
233
- "id": {"type": ["string", "null"]},
505
+ }
506
},
235
- "required": ["cfg", "id"],
507
}
508
)
509
)
510
240
- import json
241
-
511
+ assert wrapped["strict"] is True
512
assert "$ref" not in json.dumps(wrapped)
513
assert wrapped["parameters"] == {
514
"type": "object",
515
"properties": {
516
"cfg": {
517
"type": "object",
248
- "properties": {"url": {"type": "string"}},
249
- "required": ["url"],
518
+ "properties": {
519
+ "url": {"type": "string"},
520
+ "note": {"type": ["string", "null"]},
521
+ },
522
+ "required": ["url", "note"],
523
"additionalProperties": False,
524
},
252
- "id": {"anyOf": [{"type": "string"}, {"type": "null"}]},
525
+ "id": {"type": ["string", "null"]},
526
+ "label": {"type": ["string", "null"]},
527
},
254
- "required": ["cfg", "id"],
528
+ "required": ["cfg", "id", "label"],
529
"additionalProperties": False,
530
}
531
258
- def test_wrap_tool_inlines_defs_in_strict_mode(self):
532
+ def test_wrap_tool_sends_unsupported_schemas_without_strict(self):
533
from composio.core.provider._openai_responses import OpenAIResponsesProvider
534
535
provider = OpenAIResponsesProvider(strict=True)
262
- wrapped = provider.wrap_tool(
536
+ input_parameters = {
537
+ "type": "object",
538
+ "properties": {
539
+ "headers": {
540
+ "type": "object",
541
+ "additionalProperties": {"type": "string"},
542
+ },
543
+ "name": {"type": "string"},
544
+ },
545
+ "required": ["headers"],
546
+ }
547
+ wrapped = provider.wrap_tool(self._tool(input_parameters))
548
+
549
+ assert wrapped["strict"] is False
550
+ assert wrapped["parameters"] == input_parameters
551
+
552
+ def test_wrap_tool_emits_empty_closed_object_without_parameters(self):
553
+ from composio.core.provider._openai_responses import OpenAIResponsesProvider
554
+
555
+ provider = OpenAIResponsesProvider(strict=True)
556
+ wrapped = provider.wrap_tool(self._tool(None))
557
+
558
+ assert wrapped["strict"] is True
559
+ assert wrapped["parameters"] == {
560
+ "type": "object",
561
+ "properties": {},
562
+ "required": [],
563
+ "additionalProperties": False,
564
+ }
565
+
566
+ def test_execute_tool_call_omits_null_arguments_in_strict_mode(self):
567
+ from openai.types.responses.response_output_item import ResponseFunctionToolCall
568
+
569
+ from composio.core.provider._openai_responses import OpenAIResponsesProvider
570
+
571
+ received = {}
572
+
573
+ def execute_tool(slug, arguments, modifiers=None, **kwargs):
574
+ received["slug"] = slug
575
+ received["arguments"] = arguments
576
+ return {"data": {}, "error": None, "successful": True}
577
+
578
+ provider = OpenAIResponsesProvider(strict=True)
579
+ provider.set_execute_tool_fn(execute_tool)
580
+ provider.wrap_tool(
581
self._tool(
582
{
583
"type": "object",
266
- "properties": {"cfg": {"$ref": "#/$defs/Config"}},
267
- "required": ["cfg"],
268
- "$defs": {
269
- "Config": {
584
+ "properties": {
585
+ "cfg": {
586
"type": "object",
271
- "properties": {"url": {"type": "string"}},
587
+ "properties": {
588
+ "url": {"type": "string"},
589
+ "note": {"type": "string"},
590
+ },
591
"required": ["url"],
273
- }
592
+ },
593
+ "label": {"type": "string"},
594
+ "clearable": {"type": ["string", "null"]},
595
},
596
+ "required": ["cfg"],
597
}
598
)
599
)
600
+ provider.execute_tool_call(
601
+ user_id="user",
602
+ tool_call=ResponseFunctionToolCall(
603
+ type="function_call",
604
+ call_id="call_1",
605
+ name="TEST_TOOL",
606
+ arguments=json.dumps(
607
+ {
608
+ "cfg": {"url": "u", "note": None},
609
+ "label": None,
610
+ "clearable": None,
611
+ }
612
+ ),
613
+ ),
614
+ )
615
279
- assert wrapped["parameters"]["properties"]["cfg"] == {
280
- "type": "object",
281
- "properties": {"url": {"type": "string"}},
282
- "required": ["url"],
283
- "additionalProperties": False,
284
- }
616
+ assert received["slug"] == "TEST_TOOL"
617
+ assert received["arguments"] == {"cfg": {"url": "u"}, "clearable": None}