fix: handle malformed JSON in structChat parsed response#200
Open
JacobiusMakes wants to merge 1 commit intomistralai:mainfrom
Open
fix: handle malformed JSON in structChat parsed response#200JacobiusMakes wants to merge 1 commit intomistralai:mainfrom
JacobiusMakes wants to merge 1 commit intomistralai:mainfrom
Conversation
…nResponse The unguarded JSON.parse() call in convertToParsedChatCompletionResponse throws an unhandled SyntaxError when the model returns malformed JSON (common when finish_reason is "length" due to token limit truncation). This wraps the JSON.parse in a try/catch so that malformed content gracefully sets parsed to undefined instead of crashing. Also fixes a secondary issue where choices with null/undefined/array content were silently dropped from the output instead of being preserved. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
convertToParsedChatCompletionResponseinsrc/extra/structChat.tscrashes with an unhandledSyntaxErrorwhen the model returns malformed JSON content (common whenfinish_reasonis"length"due to token limit truncation).Bug: The
JSON.parse()call on line 127 is unguarded. WhileresponseFormat.safeParse()correctly uses Zod's safe parsing, the precedingJSON.parse()throws on invalid JSON, propagating an uncaught exception to the caller.Secondary issue: When a choice has
null,undefined, or array content, the choice was silently dropped from the output (the innerifhad noelsebranch), causing the response to have fewer choices than expected.Changes
JSON.parse()in a try/catch so malformed JSON gracefully setsparsedtoundefinedinstead of throwingelsebranch to preserve choices with non-string content (null/undefined/array) withparsed: undefinedTest plan
structChattests pass (3 existing + 5 new)