@@ -105,52 +105,7 @@ parse_completion_chunk = types.partial({
105105 }
106106} ) % ( value, state) -> setmetatable state, completion_chunk_mt
107107
108- -- lpeg pattern to read a json data block from the front of a string, returns
109- -- the json blob and the rest of the string if it could parse one
110- consume_json_head = do
111- import C , S , P from require " lpeg"
112-
113- -- this pattern reads from the front just enough characters to consume a
114- -- valid json object
115- consume_json = P ( str, pos) ->
116- str_len = # str
117- for k= pos+ 1 , str_len
118- candidate = str\ sub pos, k
119- parsed = false
120- pcall -> parsed = cjson. decode candidate
121- if parsed
122- return k + 1
123-
124- return nil -- fail
125-
126- S ( " \t\n\r " ) ^ 0 * P ( " data: " ) * C ( consume_json) * C ( P ( 1 ) ^ 0 )
127-
128-
129- -- creates a ltn12 compatible filter function that will call chunk_callback
130- -- for each parsed json chunk from the server-sent events api response
131- create_chat_stream_filter = ( chunk_callback) ->
132- assert types. function( chunk_callback) , " Must provide chunk_callback function when streaming response"
133-
134- accumulation_buffer = " "
135-
136- ( ... ) ->
137- chunk = ...
138-
139- if type ( chunk) == " string"
140- accumulation_buffer ..= chunk
141-
142- while true
143- json_blob, rest = consume_json_head\ match accumulation_buffer
144- unless json_blob
145- break
146-
147- accumulation_buffer = rest
148- chunk_callback cjson. decode json_blob
149- -- if chunk = parse_completion_chunk cjson.decode json_blob
150- -- chunk_callback chunk
151-
152- ...
153-
108+ import create_stream_filter from require " openai.sse"
154109
155110-- handles appending response for each call to chat
156111-- TODO: hadle appending the streaming response to the output
@@ -219,7 +174,7 @@ class ChatSession
219174 " Expected string response from streaming output"
220175
221176 parts = {}
222- f = create_chat_stream_filter ( c) ->
177+ f = create_stream_filter ( c) ->
223178 if parsed = parse_completion_chunk c
224179 table.insert parts, parsed. content
225180
@@ -256,6 +211,5 @@ class ChatSession
256211{
257212 : ChatSession
258213 : test_message
259- : create_chat_stream_filter
260214 : parse_completion_chunk
261215}
0 commit comments