@@ -417,47 +417,48 @@ def __init__(self, schema: _utils.ObjectJsonSchema):
417
417
self .defs = self .schema .pop ('$defs' , {})
418
418
419
419
def simplify (self ) -> dict [str , Any ]:
420
- self ._simplify (self .schema , allow_ref = True )
420
+ self ._simplify (self .schema , refs_stack = () )
421
421
return self .schema
422
422
423
- def _simplify (self , schema : dict [str , Any ], allow_ref : bool ) -> None :
423
+ def _simplify (self , schema : dict [str , Any ], refs_stack : tuple [ str , ...] ) -> None :
424
424
schema .pop ('title' , None )
425
425
schema .pop ('default' , None )
426
426
if ref := schema .pop ('$ref' , None ):
427
- if not allow_ref :
428
- raise shared .UserError ('Recursive `$ref`s in JSON Schema are not supported by Gemini' )
429
427
# noinspection PyTypeChecker
430
428
key = re .sub (r'^#/\$defs/' , '' , ref )
429
+ if key in refs_stack :
430
+ raise shared .UserError ('Recursive `$ref`s in JSON Schema are not supported by Gemini' )
431
+ refs_stack += (key ,)
431
432
schema_def = self .defs [key ]
432
- self ._simplify (schema_def , allow_ref = False )
433
+ self ._simplify (schema_def , refs_stack )
433
434
schema .update (schema_def )
434
435
return
435
436
436
437
if any_of := schema .get ('anyOf' ):
437
438
for schema in any_of :
438
- self ._simplify (schema , allow_ref )
439
+ self ._simplify (schema , refs_stack )
439
440
440
441
type_ = schema .get ('type' )
441
442
442
443
if type_ == 'object' :
443
- self ._object (schema , allow_ref )
444
+ self ._object (schema , refs_stack )
444
445
elif type_ == 'array' :
445
- return self ._array (schema , allow_ref )
446
+ return self ._array (schema , refs_stack )
446
447
447
- def _object (self , schema : dict [str , Any ], allow_ref : bool ) -> None :
448
+ def _object (self , schema : dict [str , Any ], refs_stack : tuple [ str , ...] ) -> None :
448
449
ad_props = schema .pop ('additionalProperties' , None )
449
450
if ad_props :
450
451
raise shared .UserError ('Additional properties in JSON Schema are not supported by Gemini' )
451
452
452
453
if properties := schema .get ('properties' ): # pragma: no branch
453
454
for value in properties .values ():
454
- self ._simplify (value , allow_ref )
455
+ self ._simplify (value , refs_stack )
455
456
456
- def _array (self , schema : dict [str , Any ], allow_ref : bool ) -> None :
457
+ def _array (self , schema : dict [str , Any ], refs_stack : tuple [ str , ...] ) -> None :
457
458
if prefix_items := schema .get ('prefixItems' ):
458
459
# TODO I think this not is supported by Gemini, maybe we should raise an error?
459
460
for prefix_item in prefix_items :
460
- self ._simplify (prefix_item , allow_ref )
461
+ self ._simplify (prefix_item , refs_stack )
461
462
462
463
if items_schema := schema .get ('items' ): # pragma: no branch
463
- self ._simplify (items_schema , allow_ref )
464
+ self ._simplify (items_schema , refs_stack )
0 commit comments