Skip to content

Commit e055041

Browse files
committed
Return the original response if attempt to parse JSONL file fails
1 parent 6bd8a03 commit e055041

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

lib/openai/http.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,15 @@ def parse_json(response)
4444
return unless response
4545
return response unless response.is_a?(String)
4646

47+
original_response = response.dup
4748
if response.include?("}\n{")
48-
# Convert a multiline string of JSON objects to a JSON array.
49+
# Attempt to convert what looks like a multiline string of JSON objects to a JSON array.
4950
response = response.gsub("}\n{", "},{").prepend("[").concat("]")
5051
end
5152

52-
try_parse_json(response)
53+
JSON.parse(response)
54+
rescue JSON::ParserError
55+
original_response
5356
end
5457

5558
# Given a proc, returns an outer proc that can be used to iterate over a JSON stream of chunks.

spec/openai/client/http_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,15 @@
196196

197197
it { expect(parsed).to eq([{ "prompt" => ":)" }, { "prompt" => ":(" }]) }
198198
end
199+
200+
context "with a non-json string containing newline-brace pattern" do
201+
let(:body) { "Hello}\n{World" }
202+
let(:parsed) { OpenAI::Client.new.send(:parse_json, body) }
203+
204+
it "returns the original string when JSON parsing fails" do
205+
expect(parsed).to eq("Hello}\n{World")
206+
end
207+
end
199208
end
200209

201210
describe ".uri" do

0 commit comments

Comments
 (0)