Skip to content

fix(extra): handle malformed JSON in structChat parsed response#230

Merged
Nelson-PROIA merged 1 commit into
mainfrom
fix/structchat-json-parse-error-handling
May 22, 2026
Merged

fix(extra): handle malformed JSON in structChat parsed response#230
Nelson-PROIA merged 1 commit into
mainfrom
fix/structchat-json-parse-error-handling

Conversation

@Nelson-PROIA

Copy link
Copy Markdown
Contributor

Summary

JSON.parse in convertToParsedChatCompletionResponse (src/extra/structChat.ts) throws a SyntaxError when the model returns malformed JSON, which happens regularly with structured outputs when finish_reason is length (truncated mid-JSON). This crashes user code instead of returning a parsable response.

Fix

Wrap the parse in try/catch. On failure, leave parsed as undefined so callers can detect the truncation gracefully.

Also adds 5 unit tests covering malformed JSON, valid JSON failing schema validation, null content, empty choices, and undefined choices.

Credit

Original work by @JacobiusMakes in #200. Opening clean as part of the current release bundle.

JSON.parse in convertToParsedChatCompletionResponse can throw a
SyntaxError when the model returns malformed JSON (common when
finish_reason is "length" and the output is truncated). Wrap the
parse in try/catch and leave parsed as undefined so callers can
detect the failure gracefully instead of crashing.

Also adds unit tests covering malformed JSON, valid JSON failing
schema validation, null content, empty choices, and undefined
choices.

Original work by @JacobiusMakes in #200.

@andreaonofrei01 andreaonofrei01 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice!

@Nelson-PROIA
Nelson-PROIA merged commit fbb5b7b into main May 22, 2026
3 checks passed
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.

3 participants