fix(openai): parsing of streaming completions #1844
Merged
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.
streamCompletion
previously failed often (not always though), becauseparseResponseChunk
assumed that a chunk of the input stream from the OpenAI api would only ever contain a single message. However, the API often sends two data messages in one chunk separated by two newlines (which the format allows) together at the start of a completion, which failed to parse as JSON. Because the unparsed chunks were stuck in the buffer, they were always appended to the beginning for all other chunks, which therefore also didn't parse, leading to all messages not being parsed.I fixed this by re-chunking the stream into lines with
Streams.lines
. And also added parsing logic for comments, multi-line messages and messages separated by double-newlines, as specified in the Server-Sent Events spec the API uses here. It seems the API currently doesn't send comments and only ever sends single-line messages, but in case they change that, IHP can now handle it.https://platform.openai.com/docs/api-reference/chat/create#chat/create-stream
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format