Skip to content

Commit 8db7cac

Browse files
committed
Buffer all streaming chunks until we have valid data
1 parent 1e01f89 commit 8db7cac

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

lib/openai/http.rb

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,16 @@ def to_json(string)
5454
# @return [Proc] An outer proc that iterates over a raw stream, converting it to JSON.
5555
def to_json_stream(user_proc:)
5656
proc do |chunk, _|
57-
chunk.scan(/(?:data|error): (\{.*\})/i).flatten.each do |data|
58-
user_proc.call(JSON.parse(data))
59-
rescue JSON::ParserError
60-
# Ignore invalid JSON.
57+
@buffer ||= ""
58+
@buffer += chunk
59+
while (match = @buffer.match(/(?:data|error): (\{.*\})/i))
60+
data = match[1]
61+
@buffer = @buffer[match.end(0)..-1] # Remove the processed data from the buffer
62+
begin
63+
user_proc.call(JSON.parse(data))
64+
rescue JSON::ParserError => e
65+
Rails.logger.error { "JSON parsing error: #{e.message}" }
66+
end
6167
end
6268
end
6369
end

0 commit comments

Comments
 (0)