@@ -25,13 +25,15 @@ def __init__(
2525 * ,
2626 strict : bool | None = None ,
2727 prefer_inlined_defs : bool = False ,
28+ simplify_nullable_unions : bool = False , # TODO (v2): Remove this, no longer used
2829 ):
2930 self .schema = schema
3031
3132 self .strict = strict
3233 self .is_strict_compatible = True # Can be set to False by subclasses to set `strict` on `ToolDefinition` when set not set by user explicitly
3334
3435 self .prefer_inlined_defs = prefer_inlined_defs
36+ self .simplify_nullable_unions = simplify_nullable_unions # TODO (v2): Remove this, no longer used
3537
3638 self .defs : dict [str , JsonSchema ] = self .schema .get ('$defs' , {})
3739 self .refs_stack : list [str ] = []
@@ -144,11 +146,39 @@ def _handle_union(self, schema: JsonSchema, union_kind: Literal['anyOf', 'oneOf'
144146
145147 handled = [self ._handle (member ) for member in members ]
146148
149+ # TODO (v2): Remove this feature, no longer used
150+ if self .simplify_nullable_unions :
151+ handled = self ._simplify_nullable_union (handled )
152+
153+ if len (handled ) == 1 :
154+ # In this case, no need to retain the union
155+ return handled [0 ] | schema
156+
147157 # If we have keys besides the union kind (such as title or discriminator), keep them without modifications
148158 schema = schema .copy ()
149159 schema [union_kind ] = handled
150160 return schema
151161
162+ @staticmethod
163+ def _simplify_nullable_union (cases : list [JsonSchema ]) -> list [JsonSchema ]:
164+ # TODO (v2): Remove this method, no longer used
165+ if len (cases ) == 2 and {'type' : 'null' } in cases :
166+ # Find the non-null schema
167+ non_null_schema = next (
168+ (item for item in cases if item != {'type' : 'null' }),
169+ None ,
170+ )
171+ if non_null_schema :
172+ # Create a new schema based on the non-null part, mark as nullable
173+ new_schema = deepcopy (non_null_schema )
174+ new_schema ['nullable' ] = True
175+ return [new_schema ]
176+ else : # pragma: no cover
177+ # they are both null, so just return one of them
178+ return [cases [0 ]]
179+
180+ return cases
181+
152182
153183class InlineDefsJsonSchemaTransformer (JsonSchemaTransformer ):
154184 """Transforms the JSON Schema to inline $defs."""
0 commit comments