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 | """Normalize JSON Schemas for OpenAI structured outputs (``strict`` mode). |
| 2 | |
| 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`` and avoid |
| 7 | annotation-only keywords, including a string ``format`` outside the accepted |
| 8 | list. Optional fields are emulated the way OpenAI |
| 9 | documents: the property stays, becomes required, and is widened to accept |
| 10 | ``null`` (``"type": ["string", "null"]`` or an extra ``anyOf`` branch). Nothing |
| 11 | is dropped, so the model keeps every parameter it could pass before; the strict |
| 12 | provider drops a ``null`` the tool's own schema does not accept before |
| 13 | executing the tool (see :func:`omit_null_tool_arguments`). |
| 14 | |
| 15 | Local ``$ref`` pointers into ``$defs``/``definitions`` are kept (the API |
| 16 | supports them, including recursion) and the definitions themselves are |
| 17 | normalized; an optional ``$ref`` property is widened with an ``anyOf`` null |
| 18 | branch. Constructs strict mode cannot express — objects that accept arbitrary |
| 19 | keys (schema-valued or ``True`` ``additionalProperties``, ``patternProperties``, |
| 20 | property-less free-form objects), ``allOf``, ``prefixItems``, external or |
| 21 | dangling ``$ref`` pointers and a non-object root — are reported in |
| 22 | ``unsupported`` instead of being rewritten into something narrower; the |
| 23 | provider sends such a tool without strict mode. |
| 24 | |
| 25 | The input is never mutated, every rewrite is recorded (capped at 50 entries; |
| 26 | ``total_changes`` carries the real count) and ``required`` arrays are |
| 27 | de-duplicated at the end. |
| 28 | """ |
| 29 | |
| 30 | from __future__ import annotations |
| 31 | |
| 32 | import typing as t |
| 33 | |
| 34 | from composio.utils.json_schema import MAX_REF_CHAIN_DEPTH, _try_resolve_pointer |
| 35 | |
| 36 | MAX_NODE_DEPTH = 512 |
| 37 | MAX_CHANGES = 50 |
| 38 | # Bounds on one null-acceptance check; past either, null is not proven accepted. |
| 39 | MAX_NULL_CHECK_DEPTH = 64 |
| 40 | MAX_NULL_CHECK_NODES = 2_000 |
| 41 | |
| 42 | # Annotation-only keywords OpenAI structured outputs rejects; safe to strip. |
| 43 | STRICT_STRIP_KEYWORDS = frozenset({"examples", "default"}) |
| 44 | |
| 45 | # The `format` values OpenAI structured outputs accepts on a string schema, |
| 46 | # matched case-sensitively; any other value there is rejected with a 400. |
| 47 | # Formats on number and integer schemas are not checked. |
| 48 | STRICT_STRING_FORMATS = frozenset( |
| 49 | { |
| 50 | "date-time", |
| 51 | "time", |
| 52 | "date", |
| 53 | "duration", |
| 54 | "email", |
| 55 | "hostname", |
| 56 | "ipv4", |
| 57 | "ipv6", |
| 58 | "uuid", |
| 59 | } |
| 60 | ) |
| 61 | |
| 62 | # Keywords whose values are literal data, not schemas - never recursed as schemas. |
| 63 | INSTANCE_VALUE_KEYWORDS = frozenset({"const", "default", "enum", "examples"}) |
| 64 | |
| 65 | SCHEMA_KEYWORDS = frozenset( |
| 66 | { |
| 67 | "additionalItems", |
| 68 | "additionalProperties", |
| 69 | "contains", |
| 70 | "contentSchema", |
| 71 | "else", |
| 72 | "if", |
| 73 | "not", |
| 74 | "propertyNames", |
| 75 | "then", |
| 76 | "unevaluatedItems", |
| 77 | "unevaluatedProperties", |
| 78 | } |
| 79 | ) |
| 80 | SCHEMA_ARRAY_KEYWORDS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"}) |
| 81 | SCHEMA_MAP_KEYWORDS = frozenset( |
| 82 | {"$defs", "definitions", "dependentSchemas", "patternProperties", "properties"} |
| 83 | ) |
| 84 | |
| 85 | # Keywords OpenAI structured outputs reject and that have no lossless rewrite. |
| 86 | STRICT_UNSUPPORTED_KEYWORDS = ( |
| 87 | "allOf", |
| 88 | "prefixItems", |
| 89 | "additionalItems", |
| 90 | "contains", |
| 91 | "dependencies", |
| 92 | "dependentSchemas", |
| 93 | "else", |
| 94 | "if", |
| 95 | "not", |
| 96 | "propertyNames", |
| 97 | "then", |
| 98 | "unevaluatedItems", |
| 99 | "unevaluatedProperties", |
| 100 | ) |
| 101 | |
| 102 | |
| 103 | def _is_object_type(node_type: t.Any) -> bool: |
| 104 | """Whether a ``type`` value declares exactly the object type.""" |
| 105 | return node_type == "object" or ( |
| 106 | isinstance(node_type, list) and node_type == ["object"] |
| 107 | ) |
| 108 | |
| 109 | |
| 110 | StrictSchemaChangeReason = t.Literal[ |
| 111 | "optional-property-nullable", |
| 112 | "unsupported-keyword-stripped", |
| 113 | "one-of-converted", |
| 114 | "nullable-converted", |
| 115 | ] |
| 116 | |
| 117 | |
| 118 | class StrictSchemaChange(t.NamedTuple): |
| 119 | """A single lossless rewrite applied by :func:`to_strict_json_schema`.""" |
| 120 | |
| 121 | path: str |
| 122 | reason: StrictSchemaChangeReason |
| 123 | detail: str = "" |
| 124 | |
| 125 | |
| 126 | class StrictSchemaIncompatibility(t.NamedTuple): |
| 127 | """A construct strict structured outputs cannot express.""" |
| 128 | |
| 129 | path: str |
| 130 | keyword: str |
| 131 | detail: str |
| 132 | |
| 133 | |
| 134 | class StrictJsonSchemaResult(t.NamedTuple): |
| 135 | """Result of :func:`to_strict_json_schema`.""" |
| 136 | |
| 137 | schema: dict[str, t.Any] |
| 138 | """The strict schema; only usable when ``unsupported`` is empty.""" |
| 139 | source: dict[str, t.Any] |
| 140 | """The input schema optionality was decided against.""" |
| 141 | changes: list[StrictSchemaChange] |
| 142 | total_changes: int |
| 143 | unsupported: list[StrictSchemaIncompatibility] |
| 144 | |
| 145 | |
| 146 | def _join_path(parent: str, key: str) -> str: |
| 147 | return f"{parent}.{key}" if parent else key |
| 148 | |
| 149 | |
| 150 | def _admits_string(type_: t.Any) -> bool: |
| 151 | """Whether a `type` value admits strings; an absent `type` admits every type.""" |
| 152 | return ( |
| 153 | type_ is None |
| 154 | or type_ == "string" |
| 155 | or (isinstance(type_, list) and "string" in type_) |
| 156 | ) |
| 157 | |
| 158 | |
| 159 | # The only keywords that can reject a ``null`` instance; every other keyword |
| 160 | # constrains strings, numbers, arrays or objects and ignores ``null``. |
| 161 | NULL_CONSTRAINT_KEYWORDS = ( |
| 162 | "type", |
| 163 | "enum", |
| 164 | "const", |
| 165 | "$ref", |
| 166 | "anyOf", |
| 167 | "oneOf", |
| 168 | "allOf", |
| 169 | "not", |
| 170 | "if", |
| 171 | "then", |
| 172 | "else", |
| 173 | ) |
| 174 | |
| 175 | |
| 176 | def _widen_to_nullable( |
| 177 | node: dict[str, t.Any], null_check: _NullCheck |
| 178 | ) -> dict[str, t.Any]: |
| 179 | """Accept ``null`` while keeping every other constraint the node declares. |
| 180 | |
| 181 | A node whose only obstacle is ``type`` or ``anyOf`` is widened in place. |
| 182 | Anything else is wrapped whole, because JSON Schema keywords apply |
| 183 | together: adding ``null`` to ``type`` does not lift a sibling ``enum``. |
| 184 | ``null_check`` must answer for the strict output. |
| 185 | """ |
| 186 | if null_check.accepts(node): |
| 187 | return node |
| 188 | constraints = [key for key in NULL_CONSTRAINT_KEYWORDS if key in node] |
| 189 | if constraints == ["type"]: |
| 190 | node_type = node["type"] |
| 191 | members = node_type if isinstance(node_type, list) else [node_type] |
| 192 | return {**node, "type": [*members, "null"]} |
| 193 | if constraints == ["anyOf"]: |
| 194 | return {**node, "anyOf": [*node["anyOf"], {"type": "null"}]} |
| 195 | annotations: dict[str, t.Any] = { |
| 196 | k: node[k] for k in ("description", "title") if k in node |
| 197 | } |
| 198 | rest = {k: v for k, v in node.items() if k not in annotations} |
| 199 | return {**annotations, "anyOf": [rest, {"type": "null"}]} |
| 200 | |
| 201 | |
| 202 | def _resolve_local_refs(node: t.Any, root: dict[str, t.Any]) -> t.Any: |
| 203 | """Follow local ``$ref`` pointers until a concrete node is reached.""" |
| 204 | current = node |
| 205 | for _ in range(MAX_REF_CHAIN_DEPTH): |
| 206 | if not isinstance(current, dict) or not isinstance(current.get("$ref"), str): |
| 207 | return current |
| 208 | resolution = _try_resolve_pointer(root, current["$ref"]) |
| 209 | if not resolution.ok: |
| 210 | return current |
| 211 | current = resolution.value |
| 212 | return current |
| 213 | |
| 214 | |
| 215 | # Markers for what an answer leans on, besides the depth of a node on the path. |
| 216 | _NOTHING = MAX_NULL_CHECK_DEPTH + 1 |
| 217 | _A_BOUND = -1 |
| 218 | |
| 219 | |
| 220 | class _NullCheck: |
| 221 | """Decides whether schemas of one document accept ``null`` as an instance. |
| 222 | |
| 223 | Every keyword in :data:`NULL_CONSTRAINT_KEYWORDS` that is present must |
| 224 | accept it. This is the single definition of null acceptance: the strict |
| 225 | rewrite and :func:`omit_null_tool_arguments` both decide with it. |
| 226 | |
| 227 | ``strict_output`` answers for the schema :func:`to_strict_json_schema` |
| 228 | emits instead of the one it was given: the rewrite types every node that |
| 229 | declares ``properties`` as an object, so such a node stops accepting null. |
| 230 | |
| 231 | ``follow_refs=False`` makes every ``$ref`` reject null without resolving |
| 232 | it. Folding ``nullable`` needs that, because a ``$ref`` can lead back to |
| 233 | the node being folded, whose source still accepts null. It costs at most |
| 234 | a redundant null branch. |
| 235 | |
| 236 | One instance serves every check against a document, and an answer is |
| 237 | computed once per node. A reference cycle never yields a null by itself, |
| 238 | so a node met again while it is being evaluated counts as rejecting. An |
| 239 | answer that leans on that is provisional until the node it leans on is |
| 240 | done: it is kept if that node does reject null and discarded otherwise. |
| 241 | |
| 242 | Each check is bounded in depth and in nodes visited. A check that meets a |
| 243 | bound proves nothing, so it rejects null whatever its other branches say, |
| 244 | which costs at most a redundant null branch or a dropped null. The nodes |
| 245 | it went through stay marked as unproven, so a later check that reaches |
| 246 | one of them neither repeats the work nor trusts the answer. |
| 247 | """ |
| 248 | |
| 249 | def __init__( |
| 250 | self, |
| 251 | root: dict[str, t.Any], |
| 252 | strict_output: bool = False, |
| 253 | follow_refs: bool = True, |
| 254 | ) -> None: |
| 255 | self.root = root |
| 256 | self.strict_output = strict_output |
| 257 | self.follow_refs = follow_refs |
| 258 | # id(node) -> (node, answer, what it leans on). Holding the node keeps |
| 259 | # its id from being reused while the answer is remembered. |
| 260 | self.answers: dict[int, tuple[dict[str, t.Any], bool, int]] = {} |
| 261 | # Nodes whose answer is provisional, oldest first. |
| 262 | self.provisional: list[int] = [] |
| 263 | # Nodes being evaluated, mapped to their depth on the current path. |
| 264 | self.path: dict[int, int] = {} |
| 265 | # Depths of the path nodes that were met again below themselves. |
| 266 | self.met_again: set[int] = set() |
| 267 | self.budget = 0 |
| 268 | # Shallowest thing the answers used since the last reset lean on. |
| 269 | self.leans_on = _NOTHING |
| 270 | |
| 271 | def accepts(self, schema: t.Any) -> bool: |
| 272 | if isinstance(schema, bool): |
| 273 | return schema |
| 274 | if not isinstance(schema, dict): |
| 275 | return True |
| 276 | key = id(schema) |
| 277 | remembered = self.answers.get(key) |
| 278 | if remembered is not None: |
| 279 | if not self.path: |
| 280 | return remembered[1] and remembered[2] != _A_BOUND |
| 281 | self.leans_on = min(self.leans_on, remembered[2]) |
| 282 | return remembered[1] |
| 283 | if key in self.path: |
| 284 | self.met_again.add(self.path[key]) |
| 285 | self.leans_on = min(self.leans_on, self.path[key]) |
| 286 | return False |
| 287 | depth = len(self.path) |
| 288 | if depth == 0: |
| 289 | self.budget = MAX_NULL_CHECK_NODES |
| 290 | if depth >= MAX_NULL_CHECK_DEPTH or self.budget <= 0: |
| 291 | self.leans_on = _A_BOUND |
| 292 | return False |
| 293 | self.budget -= 1 |
| 294 | |
| 295 | outer, self.leans_on = self.leans_on, _NOTHING |
| 296 | mark = len(self.provisional) |
| 297 | self.path[key] = depth |
| 298 | result = self._keywords_accept(schema) |
| 299 | del self.path[key] |
| 300 | |
| 301 | leans_on = self.leans_on |
| 302 | settled = leans_on >= depth |
| 303 | below = self.provisional[mark:] |
| 304 | del self.provisional[mark:] |
| 305 | if result and depth in self.met_again: |
| 306 | # The answers below took this node for rejecting null. |
| 307 | for other in below: |
| 308 | del self.answers[other] |
| 309 | else: |
| 310 | for other in below: |
| 311 | node, answer, inner = self.answers[other] |
| 312 | if settled: |
| 313 | inner = _NOTHING |
| 314 | else: |
| 315 | inner = inner if inner < depth else leans_on |
| 316 | self.provisional.append(other) |
| 317 | self.answers[other] = (node, answer, inner) |
| 318 | self.met_again.discard(depth) |
| 319 | |
| 320 | if depth == 0 and leans_on == _A_BOUND: |
| 321 | result = False |
| 322 | self.answers[key] = (schema, result, _NOTHING if settled else leans_on) |
| 323 | if not settled: |
| 324 | self.provisional.append(key) |
| 325 | self.leans_on = outer if settled else min(outer, leans_on) |
| 326 | if depth == 0: |
| 327 | # Whatever is still provisional leans on a bound, and stays so. |
| 328 | self.provisional.clear() |
| 329 | self.leans_on = _NOTHING |
| 330 | return result |
| 331 | |
| 332 | def _keywords_accept(self, node: dict[str, t.Any]) -> bool: |
| 333 | # OpenAPI ``nullable: true`` admits null whatever the other keywords |
| 334 | # say, as the Zod conversion reads it. |
| 335 | if node.get("nullable") is True: |
| 336 | return True |
| 337 | accepts = self.accepts |
| 338 | node_type = node.get("type") |
| 339 | if isinstance(node_type, str) and node_type != "null": |
| 340 | return False |
| 341 | if isinstance(node_type, list) and "null" not in node_type: |
| 342 | return False |
| 343 | if ( |
| 344 | self.strict_output |
| 345 | and "type" not in node |
| 346 | and isinstance(node.get("properties"), dict) |
| 347 | ): |
| 348 | return False |
| 349 | if isinstance(node.get("enum"), list) and None not in node["enum"]: |
| 350 | return False |
| 351 | if "const" in node and node["const"] is not None: |
| 352 | return False |
| 353 | if "$ref" in node: |
| 354 | if not self.follow_refs: |
| 355 | return False |
| 356 | ref = node["$ref"] |
| 357 | resolution = ( |
| 358 | _try_resolve_pointer(self.root, ref) if isinstance(ref, str) else None |
| 359 | ) |
| 360 | if resolution is None or not resolution.ok: |
| 361 | return False |
| 362 | if not accepts(resolution.value): |
| 363 | return False |
| 364 | any_of, one_of, all_of = node.get("anyOf"), node.get("oneOf"), node.get("allOf") |
| 365 | if isinstance(any_of, list) and not any(accepts(b) for b in any_of): |
| 366 | return False |
| 367 | if isinstance(one_of, list): |
| 368 | matches = sum(accepts(b) for b in one_of) |
| 369 | # The strict rewrite turns oneOf into anyOf. |
| 370 | if matches == 0 or (matches > 1 and not self.strict_output): |
| 371 | return False |
| 372 | if isinstance(all_of, list) and not all(accepts(b) for b in all_of): |
| 373 | return False |
| 374 | if "not" in node and accepts(node["not"]): |
| 375 | return False |
| 376 | if "if" in node: |
| 377 | branch = "then" if accepts(node["if"]) else "else" |
| 378 | if branch in node and not accepts(node[branch]): |
| 379 | return False |
| 380 | return True |
| 381 | |
| 382 | |
| 383 | def _dedupe_required(value: t.Any, is_schema: bool = True, depth: int = 0) -> t.Any: |
| 384 | if depth > MAX_NODE_DEPTH: |
| 385 | raise ValueError( |
| 386 | f"JSON Schema exceeds maximum nesting depth of {MAX_NODE_DEPTH}" |
| 387 | ) |
| 388 | if isinstance(value, list): |
| 389 | return [_dedupe_required(item, is_schema, depth + 1) for item in value] |
| 390 | if not isinstance(value, dict): |
| 391 | return value |
| 392 | clone: dict[str, t.Any] = {} |
| 393 | for key, child in value.items(): |
| 394 | if is_schema and key == "required" and isinstance(child, list): |
| 395 | clone[key] = list(dict.fromkeys(child)) |
| 396 | else: |
| 397 | clone[key] = _dedupe_required( |
| 398 | child, is_schema and key not in INSTANCE_VALUE_KEYWORDS, depth + 1 |
| 399 | ) |
| 400 | return clone |
| 401 | |
| 402 | |
| 403 | class _Walker: |
| 404 | def __init__(self, root: dict[str, t.Any]) -> None: |
| 405 | self.root = root |
| 406 | self.changes: list[StrictSchemaChange] = [] |
| 407 | self.total_changes = 0 |
| 408 | self.unsupported: list[StrictSchemaIncompatibility] = [] |
| 409 | self.null_check = _NullCheck(root, strict_output=True) |
| 410 | self.null_check_without_refs = _NullCheck( |
| 411 | root, strict_output=True, follow_refs=False |
| 412 | ) |
| 413 | # Resolved references, re-checked against the rewritten schema. |
| 414 | self.references: list[tuple[str, str]] = [] |
| 415 | |
| 416 | def record(self, path: str, reason: StrictSchemaChangeReason, detail: str) -> None: |
| 417 | self.total_changes += 1 |
| 418 | if len(self.changes) < MAX_CHANGES: |
| 419 | self.changes.append(StrictSchemaChange(path, reason, detail)) |
| 420 | |
| 421 | def reject(self, path: str, keyword: str, detail: str) -> None: |
| 422 | self.unsupported.append(StrictSchemaIncompatibility(path, keyword, detail)) |
| 423 | |
| 424 | def walk_children( |
| 425 | self, node: dict[str, t.Any], mode: str, depth: int, path: str |
| 426 | ) -> dict[str, t.Any]: |
| 427 | clone: dict[str, t.Any] = {} |
| 428 | for key, child in node.items(): |
| 429 | child_mode = "value" |
| 430 | if mode == "schema-map": |
| 431 | child_mode = "schema" |
| 432 | elif mode == "schema" and key not in INSTANCE_VALUE_KEYWORDS: |
| 433 | if key in SCHEMA_MAP_KEYWORDS: |
| 434 | child_mode = "schema-map" |
| 435 | elif key in SCHEMA_ARRAY_KEYWORDS or ( |
| 436 | key == "items" and isinstance(child, list) |
| 437 | ): |
| 438 | child_mode = "schema-array" |
| 439 | elif key in SCHEMA_KEYWORDS or key == "items": |
| 440 | child_mode = "schema" |
| 441 | |
| 442 | if child_mode == "schema-map" and isinstance(child, dict): |
| 443 | clone[key] = { |
| 444 | name: self.walk( |
| 445 | sub_schema, |
| 446 | "schema", |
| 447 | depth + 1, |
| 448 | _join_path(_join_path(path, key), name), |
| 449 | ) |
| 450 | for name, sub_schema in child.items() |
| 451 | } |
| 452 | continue |
| 453 | clone[key] = self.walk(child, child_mode, depth + 1, _join_path(path, key)) |
| 454 | return clone |
| 455 | |
| 456 | def walk(self, value: t.Any, mode: str, depth: int, path: str) -> t.Any: |
| 457 | if depth > MAX_NODE_DEPTH: |
| 458 | raise ValueError( |
| 459 | f"JSON Schema exceeds maximum nesting depth of {MAX_NODE_DEPTH}" |
| 460 | ) |
| 461 | if isinstance(value, list): |
| 462 | item_mode = "schema" if mode == "schema-array" else "value" |
| 463 | return [ |
| 464 | self.walk(item, item_mode, depth + 1, f"{path}[{index}]") |
| 465 | for index, item in enumerate(value) |
| 466 | ] |
| 467 | if not isinstance(value, dict) or mode == "value": |
| 468 | return value |
| 469 | |
| 470 | node: dict[str, t.Any] = {} |
| 471 | for key, child in value.items(): |
| 472 | if key == "nullable": |
| 473 | continue |
| 474 | if key in STRICT_STRIP_KEYWORDS: |
| 475 | self.record( |
| 476 | path, "unsupported-keyword-stripped", f'keyword "{key}" removed' |
| 477 | ) |
| 478 | continue |
| 479 | if ( |
| 480 | key == "format" |
| 481 | and isinstance(child, str) |
| 482 | and child not in STRICT_STRING_FORMATS |
| 483 | and _admits_string(value.get("type")) |
| 484 | ): |
| 485 | self.record( |
| 486 | path, "unsupported-keyword-stripped", f'format "{child}" removed' |
| 487 | ) |
| 488 | continue |
| 489 | node[key] = child |
| 490 | if isinstance(node.get("oneOf"), list) and "anyOf" not in node: |
| 491 | node["anyOf"] = node.pop("oneOf") |
| 492 | self.record(path, "one-of-converted", "oneOf became anyOf") |
| 493 | for keyword in STRICT_UNSUPPORTED_KEYWORDS: |
| 494 | if keyword in node: |
| 495 | self.reject(path, keyword, f'"{keyword}" has no strict-mode equivalent') |
| 496 | if "oneOf" in node: |
| 497 | self.reject(path, "oneOf", "oneOf beside anyOf cannot be merged") |
| 498 | if isinstance(node.get("items"), list): |
| 499 | self.reject(path, "items", "tuple-form items has no strict-mode equivalent") |
| 500 | elif isinstance(node.get("items"), bool): |
| 501 | self.reject(path, "items", "boolean subschema") |
| 502 | if "properties" in node and not isinstance(node["properties"], dict): |
| 503 | self.reject(path, "properties", "properties is not an object") |
| 504 | |
| 505 | normalized = self.normalize_node(node, mode, depth, path) |
| 506 | if "nullable" not in value: |
| 507 | return normalized |
| 508 | widened = ( |
| 509 | _widen_to_nullable(normalized, self.null_check_without_refs) |
| 510 | if value["nullable"] is True |
| 511 | else normalized |
| 512 | ) |
| 513 | if widened is normalized: |
| 514 | self.record( |
| 515 | path, "unsupported-keyword-stripped", 'keyword "nullable" removed' |
| 516 | ) |
| 517 | else: |
| 518 | self.record(path, "nullable-converted", "nullable became a null type") |
| 519 | return widened |
| 520 | |
| 521 | def normalize_node( |
| 522 | self, node: dict[str, t.Any], mode: str, depth: int, path: str |
| 523 | ) -> dict[str, t.Any]: |
| 524 | out = self.walk_children(node, mode, depth, path) |
| 525 | |
| 526 | ref = node.get("$ref") |
| 527 | if isinstance(ref, str): |
| 528 | resolved = (ref == "#" or ref.startswith("#/")) and _try_resolve_pointer( |
| 529 | self.root, ref |
| 530 | ).ok |
| 531 | if not resolved: |
| 532 | self.reject(path, "$ref", f'unresolved $ref "{ref}"') |
| 533 | else: |
| 534 | self.references.append((path, ref)) |
| 535 | # The referenced definition is normalized where it is declared. |
| 536 | return out |
| 537 | |
| 538 | node_type = out.get("type") |
| 539 | declares_object = node_type == "object" or ( |
| 540 | isinstance(node_type, list) and "object" in node_type |
| 541 | ) |
| 542 | if not declares_object and not isinstance(out.get("properties"), dict): |
| 543 | return out |
| 544 | if "properties" in out and not isinstance(out["properties"], dict): |
| 545 | return out |
| 546 | |
| 547 | properties: dict[str, t.Any] = dict(out.get("properties") or {}) |
| 548 | required = out.get("required") |
| 549 | declared_required = { |
| 550 | entry |
| 551 | for entry in (required if isinstance(required, list) else []) |
| 552 | if isinstance(entry, str) |
| 553 | } |
| 554 | for name, property_schema in properties.items(): |
| 555 | if isinstance(property_schema, bool): |
| 556 | self.reject( |
| 557 | _join_path(path, f"properties.{name}"), |
| 558 | "properties", |
| 559 | "boolean subschema", |
| 560 | ) |
| 561 | continue |
| 562 | if name in declared_required or not isinstance(property_schema, dict): |
| 563 | continue |
| 564 | properties[name] = _widen_to_nullable(property_schema, self.null_check) |
| 565 | self.record( |
| 566 | _join_path(path, f"properties.{name}"), |
| 567 | "optional-property-nullable", |
| 568 | f'property "{name}" is now required and accepts null', |
| 569 | ) |
| 570 | |
| 571 | additional = out.get("additionalProperties") |
| 572 | accepts_dynamic_keys = additional is True or isinstance(additional, dict) |
| 573 | if accepts_dynamic_keys: |
| 574 | self.reject(path, "additionalProperties", "object accepts arbitrary keys") |
| 575 | elif "patternProperties" in out: |
| 576 | self.reject( |
| 577 | path, "patternProperties", "object accepts pattern-matched keys" |
| 578 | ) |
| 579 | elif not properties and "additionalProperties" not in out: |
| 580 | self.reject(path, "properties", "free-form object accepts arbitrary keys") |
| 581 | |
| 582 | result = {**out} |
| 583 | if "type" not in result: |
| 584 | result["type"] = "object" |
| 585 | result["properties"] = properties |
| 586 | result["required"] = list(properties.keys()) |
| 587 | if not accepts_dynamic_keys: |
| 588 | result["additionalProperties"] = False |
| 589 | return result |
| 590 | |
| 591 | |
| 592 | def to_strict_json_schema(schema: t.Any) -> StrictJsonSchemaResult: |
| 593 | """Normalize a tool parameter schema for OpenAI structured outputs. |
| 594 | |
| 595 | Applies the strict contract at every depth: every object lists all of its |
| 596 | properties in ``required`` and is closed; optional properties are widened |
| 597 | to accept ``null`` instead of being dropped; ``oneOf`` becomes ``anyOf``; |
| 598 | ``default`` and ``examples`` are stripped; OpenAPI ``nullable`` is |
| 599 | stripped and a node that set it to ``true`` accepts ``null``; local |
| 600 | ``$ref`` pointers into |
| 601 | ``$defs`` or ``definitions`` are kept and the definitions are normalized |
| 602 | where they are declared; ``required`` arrays are de-duplicated last. |
| 603 | Constructs strict mode cannot express are listed in ``unsupported``; when |
| 604 | that list is non-empty the returned ``schema`` must not be sent as strict. |
| 605 | |
| 606 | :param schema: The JSON schema to normalize; never mutated. |
| 607 | :return: A :class:`StrictJsonSchemaResult`. |
| 608 | """ |
| 609 | root: dict[str, t.Any] = schema if isinstance(schema, dict) else {} |
| 610 | walker = _Walker(root) |
| 611 | normalized = _dedupe_required(walker.walk(root, "schema", 0, "")) |
| 612 | if isinstance(normalized, dict): |
| 613 | # Wrapping a property in a null branch moves everything nested in it. |
| 614 | for path, ref in walker.references: |
| 615 | if not _try_resolve_pointer(normalized, ref).ok: |
| 616 | walker.reject(path, "$ref", f'$ref "{ref}" target moved by the rewrite') |
| 617 | if not isinstance(normalized, dict) or not _is_object_type(normalized.get("type")): |
| 618 | walker.reject("", "type", "root must be a non-nullable object") |
| 619 | return StrictJsonSchemaResult( |
| 620 | schema=normalized, |
| 621 | source=root, |
| 622 | changes=walker.changes, |
| 623 | total_changes=walker.total_changes, |
| 624 | unsupported=walker.unsupported, |
| 625 | ) |
| 626 | |
| 627 | |
| 628 | def omit_null_tool_arguments( |
| 629 | arguments: dict[str, t.Any], schema: t.Any |
| 630 | ) -> dict[str, t.Any]: |
| 631 | """Drop ``None``-valued arguments the tool's own schema does not accept. |
| 632 | |
| 633 | Strict structured outputs cannot express optional parameters, so |
| 634 | :func:`to_strict_json_schema` makes every parameter required and nullable. |
| 635 | The model then sends ``null`` for a parameter it would otherwise have |
| 636 | omitted; forwarding it to the tool would fail validation against the |
| 637 | tool's real schema, so it is treated as "omitted". A ``null`` the original |
| 638 | schema accepts is kept. ``schema`` is the tool schema the strict rewrite |
| 639 | was computed from (``StrictJsonSchemaResult.source``). The input is not |
| 640 | mutated. |
| 641 | """ |
| 642 | root: dict[str, t.Any] = schema if isinstance(schema, dict) else {} |
| 643 | return t.cast( |
| 644 | dict[str, t.Any], _omit_nulls(arguments, root, root, 0, _NullCheck(root)) |
| 645 | ) |
| 646 | |
| 647 | |
| 648 | def _select_branch_for( |
| 649 | schema: t.Any, value: t.Any, root: dict[str, t.Any] |
| 650 | ) -> dict[str, t.Any] | None: |
| 651 | """Pick the composition branch that describes a value's shape.""" |
| 652 | resolved = _resolve_local_refs(schema, root) |
| 653 | if not isinstance(resolved, dict): |
| 654 | return None |
| 655 | wanted = "items" if isinstance(value, list) else "properties" |
| 656 | |
| 657 | def find(node: t.Any, depth: int) -> dict[str, t.Any] | None: |
| 658 | candidate = _resolve_local_refs(node, root) |
| 659 | if not isinstance(candidate, dict) or depth > MAX_NODE_DEPTH: |
| 660 | return None |
| 661 | if wanted in candidate: |
| 662 | return candidate |
| 663 | for keyword in ("anyOf", "oneOf"): |
| 664 | branches = candidate.get(keyword) |
| 665 | if not isinstance(branches, list): |
| 666 | continue |
| 667 | for branch in branches: |
| 668 | found = find(branch, depth + 1) |
| 669 | if found is not None: |
| 670 | return found |
| 671 | return None |
| 672 | |
| 673 | return find(resolved, 0) or resolved |
| 674 | |
| 675 | |
| 676 | def _omit_nulls( |
| 677 | value: t.Any, |
| 678 | schema: t.Any, |
| 679 | root: dict[str, t.Any], |
| 680 | depth: int, |
| 681 | null_check: _NullCheck, |
| 682 | ) -> t.Any: |
| 683 | if depth > MAX_NODE_DEPTH: |
| 684 | raise ValueError( |
| 685 | f"Tool arguments exceed maximum nesting depth of {MAX_NODE_DEPTH}" |
| 686 | ) |
| 687 | node = _select_branch_for(schema, value, root) or {} |
| 688 | if isinstance(value, list): |
| 689 | items = node.get("items") if isinstance(node.get("items"), dict) else None |
| 690 | return [_omit_nulls(item, items, root, depth + 1, null_check) for item in value] |
| 691 | if not isinstance(value, dict): |
| 692 | return value |
| 693 | declared = node.get("properties") |
| 694 | properties: dict[str, t.Any] = declared if isinstance(declared, dict) else {} |
| 695 | clone: dict[str, t.Any] = {} |
| 696 | for key, child in value.items(): |
| 697 | property_schema = properties.get(key) |
| 698 | if child is None: |
| 699 | if property_schema is None or null_check.accepts(property_schema): |
| 700 | clone[key] = child |
| 701 | continue |
| 702 | clone[key] = _omit_nulls(child, property_schema, root, depth + 1, null_check) |
| 703 | return clone |