Skip to content

Commit 90ca293

Browse files
committed
More strict parsing according SSE spec
1 parent 66e4657 commit 90ca293

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

openai/init.moon

+15-6
Original file line numberDiff line numberDiff line change
@@ -224,15 +224,24 @@ class OpenAI
224224
accumulation_buffer ..= chunk
225225

226226
while true
227-
line, rest = accumulation_buffer\match "^(.-)\r?\n\r?\n(.-)$"
228-
unless line
227+
event, rest = accumulation_buffer\match "^(.-)\r?\n\r?\n(.-)$"
228+
unless event
229229
break
230230

231231
accumulation_buffer = rest
232-
json_blob = line\match "^data:%s+(.-)%s*$"
233-
if json_blob and json_blob~="[DONE]"
234-
if chunk = parse_completion_chunk cjson.decode json_blob
235-
chunk_callback chunk
232+
while event and #event>0
233+
field, value, rest_evt = event\match "^(.-):%s+([^\r\n]+)(.-)$"
234+
switch field
235+
when "data"
236+
unless value=="[DONE]"
237+
chunk_callback (json.decode value)
238+
when "event","id","retry","" --comment
239+
nil -- noop
240+
when nil
241+
error "Cannot parse SSE event: "..event
242+
else
243+
error ('Unknown field "%s" with value "%s"')\format(field, value)
244+
event = #rest_evt>0 and rest_evt\match"^\r?\n(.*)"
236245

237246
...
238247

0 commit comments

Comments
 (0)