Skip to content

Conversation

@yashwantbezawada
Copy link

@yashwantbezawada yashwantbezawada commented Nov 5, 2025

Fixes #282

I ran into this issue while following the structured output documentation. When the API returns empty or invalid JSON content, client.chat.parse() crashes with a JSONDecodeError instead of handling it gracefully.

The problem is in struct_chat.py line 27 - it tries to parse the content string with json.loads() without checking if it's actually valid JSON first.

I've added validation to check if the content is non-empty and catch any JSON parsing errors. When parsing fails, it now sets parsed to None instead of crashing, which is consistent with how the code already handles None content.

I also added some tests to cover the edge cases:

  • Empty strings
  • Whitespace-only strings
  • Invalid JSON strings
  • None values (regression test)

All the existing tests still pass, and the new behavior is backward compatible - valid JSON inputs work exactly the same as before. The only difference is that edge cases that used to crash now return parsed=None, which users can check to see if parsing succeeded.

Let me know if you'd like me to change anything!

Fixes mistralai#282

The client.chat.parse() method crashed with JSONDecodeError when the
API returned empty, whitespace-only, or invalid JSON content.

Changes:
- Add content validation before JSON parsing in struct_chat.py
- Strip whitespace and check if content is non-empty
- Catch JSONDecodeError and set parsed to None instead of crashing
- Add 4 comprehensive test cases for edge cases

This change improves error handling without breaking existing
functionality. Empty or invalid JSON content now results in
parsed=None instead of raising an exception.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG CLIENT]: client.chat.parse throws an error

1 participant