Skip to content

Don't swallow model errors in streaming mode #270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions lib/openai/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,19 @@ def to_json(string)
# @param user_proc [Proc] The inner proc to call for each JSON object in the chunk.
# @return [Proc] An outer proc that iterates over a raw stream, converting it to JSON.
def to_json_stream(user_proc:)
proc do |chunk, _|
chunk.scan(/(?:data|error): (\{.*\})/i).flatten.each do |data|
user_proc.call(JSON.parse(data))
rescue JSON::ParserError
# Ignore invalid JSON.
proc do |chunk, overall_received_bytes, env|
Rails.logger.debug("raw chunk: #{chunk}")
Copy link
Contributor

Choose a reason for hiding this comment

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

Please remove references to Rails. It's not a dependency and will cause issues for anyone using this outside of Rails.

I've created a new issue (#320) to track adding a logger, and this can be added there.


if chunk.start_with?("data: {")
chunk.each_line do |line|
next unless line.start_with?("data: {")
line.delete_prefix!("data: ")
user_proc.call(JSON.parse(line))
end
elsif chunk.include?('"error": ')

Choose a reason for hiding this comment

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

don't know 100% how it works, but can it just return me some JSON examples with this string?

Copy link

Choose a reason for hiding this comment

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

raw chunk: {
    "error": {
        "message": "The model `gpt-3.5-turbo!!!!` does not exist",
        "type": "invalid_request_error",
        "param": null,
        "code": null
    }
}

user_proc.call(JSON.parse(chunk))
else
Rails.logger.warn("unkown raw chunk: #{chunk}")
end
end
end
Expand Down