Skip to content

Commit cf6f3a2

Browse files
committed
Handle case where error response body may not be JSON
1 parent 2fc94c5 commit cf6f3a2

File tree

4 files changed

+69
-19
lines changed

4 files changed

+69
-19
lines changed

lib/openai/http.rb

+7-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def to_json_stream(user_proc:)
5151
proc do |chunk, _bytes, env|
5252
if env && env.status != 200
5353
raise_error = Faraday::Response::RaiseError.new
54-
raise_error.on_complete(env.merge(body: JSON.parse(chunk)))
54+
raise_error.on_complete(env.merge(body: try_parse_json(chunk)))
5555
end
5656

5757
parser.feed(chunk) do |_type, data|
@@ -125,5 +125,11 @@ def configure_json_post_request(req, parameters)
125125
req.headers = headers
126126
req.body = req_parameters.to_json
127127
end
128+
129+
def try_parse_json(maybe_json)
130+
JSON.parse(maybe_json)
131+
rescue JSON::ParserError
132+
maybe_json
133+
end
128134
end
129135
end

spec/fixtures/cassettes/gpt-3_5-turbo_streamed_chat_with_error_response.yml

+2-15
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

spec/fixtures/cassettes/gpt-3_5-turbo_streamed_chat_with_json_error_response.yml

+42
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

spec/openai/client/chat_spec.rb

+18-3
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,10 @@ def call(chunk)
7373
end
7474
end
7575

76-
context "with an error response" do
77-
let(:cassette) { "#{model} streamed chat with error response".downcase }
76+
context "with an error response with a JSON body" do
77+
let(:cassette) { "#{model} streamed chat with json error response".downcase }
7878

79-
it "raises an HTTP error" do
79+
it "raises an HTTP error with the parsed body" do
8080
VCR.use_cassette(cassette, record: :none) do
8181
response
8282
rescue Faraday::BadRequestError => e
@@ -94,6 +94,21 @@ def call(chunk)
9494
end
9595
end
9696
end
97+
98+
context "with an error response without a JSON body" do
99+
let(:cassette) { "#{model} streamed chat with error response".downcase }
100+
101+
it "raises an HTTP error" do
102+
VCR.use_cassette(cassette, record: :none) do
103+
response
104+
rescue Faraday::ServerError => e
105+
expect(e.response).to include(status: 500)
106+
expect(e.response[:body]).to eq("")
107+
else
108+
raise "Expected to raise Faraday::ServerError"
109+
end
110+
end
111+
end
97112
end
98113
end
99114

0 commit comments

Comments
 (0)