File tree Expand file tree Collapse file tree 3 files changed +23
-4
lines changed Expand file tree Collapse file tree 3 files changed +23
-4
lines changed Original file line number Diff line number Diff line change 3
3
module OpenAI
4
4
module HTTP
5
5
def get ( path :)
6
- conn . get ( uri ( path : path ) ) do |req |
6
+ parse_jsonl ( conn . get ( uri ( path : path ) ) do |req |
7
7
req . headers = headers
8
- end &.body
8
+ end &.body )
9
9
end
10
10
11
11
def json_post ( path :, parameters :)
@@ -29,6 +29,16 @@ def delete(path:)
29
29
30
30
private
31
31
32
+ def parse_jsonl ( response )
33
+ return unless response
34
+ return response unless response . is_a? ( String )
35
+
36
+ # Convert a multiline string of JSON objects to a JSON array.
37
+ response = response . gsub ( "}\n {" , "},{" ) . prepend ( "[" ) . concat ( "]" )
38
+
39
+ JSON . parse ( response )
40
+ end
41
+
32
42
# Given a proc, returns an outer proc that can be used to iterate over a JSON stream of chunks.
33
43
# For each chunk, the inner user_proc is called giving it the JSON object. The JSON object could
34
44
# be a data object or an error object as described in the OpenAI API documentation.
Original file line number Diff line number Diff line change @@ -77,7 +77,7 @@ def call(chunk)
77
77
let ( :cassette ) { "#{ model } streamed chat with error response" . downcase }
78
78
79
79
it "raises an HTTP error" do
80
- VCR . use_cassette ( cassette ) do
80
+ VCR . use_cassette ( cassette , record : :none ) do
81
81
response
82
82
rescue Faraday ::BadRequestError => e
83
83
expect ( e . response ) . to include ( status : 400 )
Original file line number Diff line number Diff line change 109
109
let ( :cassette ) { "http get with error response" . downcase }
110
110
111
111
it "raises an HTTP error" do
112
- VCR . use_cassette ( cassette ) do
112
+ VCR . use_cassette ( cassette , record : :none ) do
113
113
OpenAI ::Client . new . models . retrieve ( id : "text-ada-001" )
114
114
rescue Faraday ::Error => e
115
115
expect ( e . response ) . to include ( status : 400 )
189
189
end
190
190
end
191
191
192
+ describe ".parse_jsonl" do
193
+ context "with a jsonl string" do
194
+ let ( :body ) { "{\" prompt\" :\" :)\" }\n {\" prompt\" :\" :(\" }\n " }
195
+ let ( :parsed ) { OpenAI ::Client . new . send ( :parse_jsonl , body ) }
196
+
197
+ it { expect ( parsed ) . to eq ( [ { "prompt" => ":)" } , { "prompt" => ":(" } ] ) }
198
+ end
199
+ end
200
+
192
201
describe ".uri" do
193
202
let ( :path ) { "/chat" }
194
203
let ( :uri ) { OpenAI ::Client . new . send ( :uri , path : path ) }
You can’t perform that action at this time.
0 commit comments