@@ -95,27 +95,6 @@ parse_completion_chunk = types.partial {
95
95
}
96
96
}
97
97
98
- -- lpeg pattern to read a json data block from the front of a string, returns
99
- -- the json blob and the rest of the string if it could parse one
100
- consume_json_head = do
101
- import C , S , P from require " lpeg"
102
-
103
- -- this pattern reads from the front just enough characters to consume a
104
- -- valid json object
105
- consume_json = P ( str, pos) ->
106
- str_len = # str
107
- for k= pos+ 1 , str_len
108
- candidate = str\ sub pos, k
109
- parsed = false
110
- pcall -> parsed = cjson. decode candidate
111
- if parsed
112
- return k + 1
113
-
114
- return nil -- fail
115
-
116
- S ( " \t\n\r " ) ^ 0 * P ( " data: " ) * C ( consume_json) * C ( P ( 1 ) ^ 0 )
117
-
118
-
119
98
parse_error_message = types. partial {
120
99
error : types. partial {
121
100
message : types. string\ tag " message"
@@ -245,13 +224,16 @@ class OpenAI
245
224
accumulation_buffer ..= chunk
246
225
247
226
while true
248
- json_blob , rest = consume_json_head \ match accumulation_buffer
249
- unless json_blob
227
+ _ , pos , line = accumulation_buffer \ find " ^(.-) \r ? \n\r ? \n "
228
+ unless line
250
229
break
251
230
252
- accumulation_buffer = rest
253
- if chunk = parse_completion_chunk cjson. decode json_blob
254
- chunk_callback chunk
231
+ accumulation_buffer = accumulation_buffer\ sub pos+ 1
232
+
233
+ json_blob = line\ match " ^data:%s+(.-)%s*$"
234
+ if json_blob and json_blob~= " [DONE]"
235
+ if chunk = parse_completion_chunk cjson. decode json_blob
236
+ chunk_callback chunk
255
237
256
238
...
257
239
0 commit comments