@@ -6,69 +6,40 @@ import com.fasterxml.jackson.databind.json.JsonMapper
66import com.openai.core.JsonValue
77import com.openai.core.http.HttpResponse
88import com.openai.core.http.HttpResponse.Handler
9- import com.openai.core.http.PhantomReachableClosingStreamResponse
109import com.openai.core.http.SseMessage
1110import com.openai.core.http.StreamResponse
1211import com.openai.errors.OpenAIException
1312import java.util.stream.Stream
1413import kotlin.jvm.optionals.getOrNull
15- import kotlin.streams.asStream
1614
1715@JvmSynthetic
1816internal fun sseHandler (jsonMapper : JsonMapper ): Handler <StreamResponse <SseMessage >> =
19- object : Handler <StreamResponse <SseMessage >> {
20-
21- override fun handle (response : HttpResponse ): StreamResponse <SseMessage > {
22- val reader = response.body().bufferedReader()
23- val sequence =
24- sequence {
25- reader.useLines { lines ->
26- val state = SseState (jsonMapper)
27- var done = false
28- for (line in lines) {
29- // Stop emitting messages, but iterate through the full stream.
30- if (done) {
31- continue
32- }
33- val message = state.decode(line) ? : continue
34-
35- if (message.data.startsWith(" [DONE]" )) {
36- // In this case we don't break because we still want to iterate
37- // through the full stream.
38- done = true
39- continue
40- }
41-
42- val error =
43- message.json<JsonValue >().asObject().getOrNull()?.get(" error" )
44- if (error != null ) {
45- val errorMessage =
46- error.asString().getOrNull()
47- ? : error
48- .asObject()
49- .getOrNull()
50- ?.get(" message" )
51- ?.asString()
52- ?.getOrNull()
53- ? : " An error occurred during streaming"
54- throw OpenAIException (errorMessage)
55- }
56- yield (message)
57- }
58- }
59- }
60- .constrainOnce()
61-
62- return PhantomReachableClosingStreamResponse (
63- object : StreamResponse <SseMessage > {
64- override fun stream (): Stream <SseMessage > = sequence.asStream()
65-
66- override fun close () {
67- reader.close()
68- response.close()
69- }
70- }
71- )
17+ streamHandler { lines ->
18+ val state = SseState (jsonMapper)
19+ var done = false
20+ for (line in lines) {
21+ // Stop emitting messages, but iterate through the full stream.
22+ if (done) {
23+ continue
24+ }
25+ val message = state.decode(line) ? : continue
26+
27+ if (message.data.startsWith(" [DONE]" )) {
28+ // In this case we don't break because we still want to iterate through the full
29+ // stream.
30+ done = true
31+ continue
32+ }
33+
34+ val error = message.json<JsonValue >().asObject().getOrNull()?.get(" error" )
35+ if (error != null ) {
36+ val errorMessage =
37+ error.asString().getOrNull()
38+ ? : error.asObject().getOrNull()?.get(" message" )?.asString()?.getOrNull()
39+ ? : " An error occurred during streaming"
40+ throw OpenAIException (errorMessage)
41+ }
42+ yield (message)
7243 }
7344 }
7445
0 commit comments