17
SchemaError,
18
create_model as create_model_from_schema,
19
)
20
+from pydantic import Field, create_model as create_pydantic_model
21
+from pydantic_core import core_schema
22
23
from composio.utils.logging import get as get_logger
24
25
logger = get_logger(__name__)
26
27
+
28
+class _UnsatisfiableSchema:
29
+ """Pydantic type for JSON schemas that reject every value."""
30
+
31
+ @staticmethod
32
+ def _reject(_value: t.Any) -> t.NoReturn:
33
+ raise ValueError("schema is unsatisfiable (JSON Schema `false`)")
34
+
35
+ @classmethod
36
+ def __get_pydantic_core_schema__(
37
+ cls,
38
+ _source_type: t.Any,
39
+ _handler: t.Any,
40
+ ) -> core_schema.CoreSchema:
41
+ return core_schema.no_info_plain_validator_function(cls._reject)
42
+
43
+ @classmethod
44
+ def __get_pydantic_json_schema__(
45
+ cls,
46
+ _core_schema: core_schema.CoreSchema,
47
+ _handler: t.Any,
48
+ ) -> t.Dict[str, t.Any]:
49
+ return {"not": {}}
50
+
51
+
52
+def _is_unsatisfiable_schema(schema: t.Any) -> bool:
53
+ return schema is _UnsatisfiableSchema
54
+
55
+
56
# Type mapping for simple cases where we don't need full model creation
57
PYDANTIC_TYPE_TO_PYTHON_TYPE = {
58
"string": str,
82
83
def _filter_boolean_schemas(
84
schema: t.Union[t.Dict[str, t.Any], bool, t.List],
54
-) -> t.Union[t.Dict[str, t.Any], t.Any, None]:
85
+) -> t.Any:
86
"""
87
Pre-filter boolean schemas from anyOf/allOf/oneOf arrays.
88
92
93
The json-schema-to-pydantic library doesn't handle these, so we:
94
- Replace `true` with {} (empty schema, accepts anything)
64
- - Filter out `false` (rejects everything, so no point including it)
95
+ - Drop `false` from union combiners (`anyOf`/`oneOf`)
96
+ - Propagate an unsatisfiable marker through conjunctions and nested schemas
97
66
- Returns None if the schema is a standalone `false` boolean.
98
+ `None` remains the standalone-`false` filter sentinel for compatibility.
99
+ Composed schemas use `_UnsatisfiableSchema` so callers can distinguish
100
+ "drop this union branch" from "reject every value."
101
"""
102
if isinstance(schema, bool):
103
if schema:
112
filtered = []
113
for item in schema:
114
result = _filter_boolean_schemas(item)
81
- if result is not None:
115
+ if result is not None and not _is_unsatisfiable_schema(result):
116
filtered.append(result)
117
return filtered if filtered else None
118
122
# Make a copy to avoid mutating the original
123
result = {}
124
for key, value in schema.items():
91
- if key in ("anyOf", "allOf", "oneOf"):
92
- # Filter boolean schemas from combiner arrays
93
- filtered_value = _filter_boolean_schemas(value)
94
- if filtered_value is None or (
95
- isinstance(filtered_value, list) and len(filtered_value) == 0
125
+ if key == "allOf" and isinstance(value, list):
126
+ filtered_members = [_filter_boolean_schemas(member) for member in value]
127
+ if any(
128
+ member is None or _is_unsatisfiable_schema(member)
129
+ for member in filtered_members
130
):
97
- # All schemas were false, skip this combiner
98
- continue
99
- result[key] = filtered_value
131
+ return _UnsatisfiableSchema
132
+ result[key] = filtered_members
133
+ elif key in ("anyOf", "oneOf") and isinstance(value, list):
134
+ filtered_members = []
135
+ for member in value:
136
+ filtered_member = _filter_boolean_schemas(member)
137
+ if filtered_member is not None and not _is_unsatisfiable_schema(
138
+ filtered_member
139
+ ):
140
+ filtered_members.append(filtered_member)
141
+ if not filtered_members:
142
+ return _UnsatisfiableSchema
143
+ result[key] = filtered_members
144
elif key == "items" and isinstance(value, (dict, bool)):
145
# Handle array items schema
146
filtered_items = _filter_boolean_schemas(value)
103
- if filtered_items is not None:
104
- result[key] = filtered_items
147
+ result[key] = (
148
+ _UnsatisfiableSchema if filtered_items is None else filtered_items
149
+ )
150
elif key == "properties" and isinstance(value, dict):
151
# Recursively filter property schemas
152
filtered_props = {}
153
for prop_name, prop_schema in value.items():
154
filtered_prop = _filter_boolean_schemas(prop_schema)
110
- if filtered_prop is not None:
111
- filtered_props[prop_name] = filtered_prop
155
+ filtered_props[prop_name] = (
156
+ _UnsatisfiableSchema if filtered_prop is None else filtered_prop
157
+ )
158
result[key] = filtered_props
159
elif key in ("$defs", "definitions") and isinstance(value, dict):
160
# Recursively filter definitions
161
filtered_defs = {}
162
for def_name, def_schema in value.items():
163
filtered_def = _filter_boolean_schemas(def_schema)
118
- if filtered_def is not None:
119
- filtered_defs[def_name] = filtered_def
164
+ filtered_defs[def_name] = (
165
+ _UnsatisfiableSchema if filtered_def is None else filtered_def
166
+ )
167
result[key] = filtered_defs
168
else:
169
result[key] = value
171
return result
172
173
174
+def _resolve_unsatisfiable_references(schema: t.Any) -> t.Any:
175
+ """Replace local references to unsatisfiable definitions with the marker."""
176
+ if not isinstance(schema, dict):
177
+ return schema
178
+
179
+ unsatisfiable_refs = set()
180
+ for definitions_key in ("$defs", "definitions"):
181
+ definitions = schema.get(definitions_key)
182
+ if not isinstance(definitions, dict):
183
+ continue
184
+ for name, definition in definitions.items():
185
+ if _is_unsatisfiable_schema(definition):
186
+ unsatisfiable_refs.add(f"#/{definitions_key}/{name}")
187
+
188
+ if not unsatisfiable_refs:
189
+ return schema
190
+
191
+ def replace(value: t.Any) -> t.Any:
192
+ if isinstance(value, list):
193
+ return [replace(item) for item in value]
194
+ if not isinstance(value, dict):
195
+ return value
196
+ if value.get("$ref") in unsatisfiable_refs:
197
+ return _UnsatisfiableSchema
198
+
199
+ replaced = {}
200
+ for key, item in value.items():
201
+ if key in ("$defs", "definitions") and isinstance(item, dict):
202
+ replaced[key] = {
203
+ name: replace(definition)
204
+ for name, definition in item.items()
205
+ if not _is_unsatisfiable_schema(definition)
206
+ }
207
+ else:
208
+ replaced[key] = replace(item)
209
+ return replaced
210
+
211
+ return replace(schema)
212
+
213
+
214
+def _contains_unsatisfiable_schema(schema: t.Any) -> bool:
215
+ if _is_unsatisfiable_schema(schema):
216
+ return True
217
+ if isinstance(schema, list):
218
+ return any(_contains_unsatisfiable_schema(item) for item in schema)
219
+ if isinstance(schema, dict):
220
+ return any(_contains_unsatisfiable_schema(value) for value in schema.values())
221
+ return False
222
+
223
+
224
def json_schema_to_pydantic_type(
225
json_schema: t.Union[t.Dict[str, t.Any], bool],
226
) -> t.Union[t.Type, t.Optional[t.Any]]:
242
243
# Pre-filter boolean schemas from combiners
244
filtered_schema = _filter_boolean_schemas(json_schema)
148
- if filtered_schema is None:
149
- return str # Fallback if all schemas were false
245
+ filtered_schema = _resolve_unsatisfiable_references(filtered_schema)
246
+ return _filtered_schema_to_pydantic_type(filtered_schema)
247
+
248
+
249
+def _filtered_schema_to_pydantic_type(schema: t.Any) -> t.Type[t.Any]:
250
+ """Convert a schema after boolean-schema normalization."""
251
+ if schema is None or _is_unsatisfiable_schema(schema):
252
+ return _UnsatisfiableSchema
253
254
# Handle simple primitive types without complex combiners
152
- if _is_simple_primitive(filtered_schema):
153
- return _convert_simple_type(filtered_schema)
255
+ if _is_simple_primitive(schema):
256
+ return _convert_simple_type(schema)
257
258
# Use library for complex schemas (anyOf, allOf, oneOf, nested objects)
156
- return _convert_with_library(filtered_schema)
259
+ return _convert_with_library(schema)
260
261
262
def _is_simple_primitive(schema: t.Dict[str, t.Any]) -> bool:
279
return t.cast(t.Type[t.Any], PYDANTIC_TYPE_TO_PYTHON_TYPE.get(type_, str))
280
281
282
+def _convert_object_with_unsatisfiable_properties(
283
+ schema: t.Dict[str, t.Any],
284
+) -> t.Type[t.Any]:
285
+ """Build an object model while retaining always-rejecting properties."""
286
+ properties = schema.get("properties", {})
287
+ required = set(schema.get("required", []))
288
+ rejecting_properties = {
289
+ name: prop_schema
290
+ for name, prop_schema in properties.items()
291
+ if _contains_unsatisfiable_schema(prop_schema)
292
+ }
293
+ ordinary_properties = {
294
+ name: prop_schema
295
+ for name, prop_schema in properties.items()
296
+ if name not in rejecting_properties
297
+ }
298
+
299
+ model_name = schema.get("title", "GeneratedModel")
300
+ base_schema = {
301
+ **schema,
302
+ "title": model_name,
303
+ "properties": ordinary_properties,
304
+ "required": [
305
+ name for name in schema.get("required", []) if name in ordinary_properties
306
+ ],
307
+ }
308
+ base_model = create_model_from_schema(
309
+ base_schema,
310
+ allow_undefined_array_items=True,
311
+ allow_undefined_type=True,
312
+ )
313
+
314
+ field_definitions = {}
315
+ for name, prop_schema in rejecting_properties.items():
316
+ annotation = _filtered_schema_to_pydantic_type(prop_schema)
317
+ default = (
318
+ ...
319
+ if name in required
320
+ else prop_schema.get("default")
321
+ if isinstance(prop_schema, dict)
322
+ else None
323
+ )
324
+ field_kwargs = {}
325
+ if isinstance(prop_schema, dict):
326
+ for metadata_key in ("description", "examples", "title"):
327
+ if metadata_key in prop_schema:
328
+ field_kwargs[metadata_key] = prop_schema[metadata_key]
329
+ field_definitions[name] = (
330
+ annotation,
331
+ Field(default, **field_kwargs),
332
+ )
333
+
334
+ return create_pydantic_model( # type: ignore[call-overload]
335
+ model_name,
336
+ __base__=base_model,
337
+ **field_definitions,
338
+ )
339
+
340
+
341
def _convert_with_library(
342
schema: t.Dict[str, t.Any],
343
) -> t.Union[t.Type, t.Any]:
352
353
# For object schemas, create model directly
354
if schema.get("type") == "object":
355
+ if _contains_unsatisfiable_schema(schema.get("properties", {})):
356
+ return _convert_object_with_unsatisfiable_properties(schema)
357
if "title" not in schema:
358
schema = {**schema, "title": "GeneratedModel"}
359
return create_model_from_schema(
365
# For array schemas
366
if schema.get("type") == "array":
367
items = schema.get("items")
368
+ if _is_unsatisfiable_schema(items):
369
+ return t.List[_UnsatisfiableSchema] # type: ignore[return-value]
370
if items:
205
- item_type = json_schema_to_pydantic_type(items)
371
+ item_type = _filtered_schema_to_pydantic_type(items)
372
return t.List[t.cast(t.Type, item_type)] # type: ignore
373
return t.List
374
438
pydantic_types.append(ptype)
439
440
if len(pydantic_types) == 0:
275
- return t.Optional[t.Any] if has_null else str # type: ignore
441
+ return t.Optional[t.Any] if has_null else _UnsatisfiableSchema # type: ignore
442
443
if len(pydantic_types) == 1:
444
base_type = pydantic_types[0]