Skip to content

Commit 3a05a89

Browse files
committed
More strict parsing according SSE spec
1 parent 3ecb15c commit 3a05a89

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
@@ -227,15 +227,24 @@ class OpenAI
227227
accumulation_buffer ..= chunk
228228

229229
while true
230-
line, rest = accumulation_buffer\match "^(.-)\r?\n\r?\n(.-)$"
231-
unless line
230+
event, rest = accumulation_buffer\match "^(.-)\r?\n\r?\n(.-)$"
231+
unless event
232232
break
233233

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

240249
...
241250

0 commit comments

Comments
 (0)