@@ -264,8 +264,17 @@ def generate(
264264 if response_format is not None :
265265 # Strip code fences before validation
266266 content = self ._strip_code_fences (content )
267- results .append (
268- response_format .model_validate_json (content ))
267+ try :
268+ results .append (
269+ response_format .model_validate_json (content ))
270+ except Exception as validation_error :
271+ # Show the content that failed to parse for debugging
272+ content_preview = content [:500 ] + "..." if len (content ) > 500 else content
273+ raise ValueError (
274+ f"Failed to parse JSON response into { response_format .__name__ } .\n "
275+ f"Validation error: { validation_error } \n "
276+ f"Content received (first 500 chars):\n { content_preview } "
277+ ) from validation_error
269278 else :
270279 # Strip leading/trailing whitespace for text responses
271280 results .append (content .strip () if content else content )
@@ -471,7 +480,16 @@ def generate(
471480 if response_format is not None :
472481 # Strip code fences before validation
473482 content = self ._strip_code_fences (content )
474- results .append (response_format .model_validate_json (content ))
483+ try :
484+ results .append (response_format .model_validate_json (content ))
485+ except Exception as validation_error :
486+ # Show the content that failed to parse for debugging
487+ content_preview = content [:500 ] + "..." if len (content ) > 500 else content
488+ raise ValueError (
489+ f"Failed to parse JSON response into { response_format .__name__ } .\n "
490+ f"Validation error: { validation_error } \n "
491+ f"Content received (first 500 chars):\n { content_preview } "
492+ ) from validation_error
475493 else :
476494 # Strip leading/trailing whitespace for text responses
477495 results .append (content .strip () if content else content )
0 commit comments