|
3 | 3 | package com.openai.core.handlers
|
4 | 4 |
|
5 | 5 | import com.fasterxml.jackson.databind.json.JsonMapper
|
6 |
| -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef |
| 6 | +import com.openai.core.JsonValue |
7 | 7 | import com.openai.core.http.HttpResponse
|
8 | 8 | import com.openai.core.http.HttpResponse.Handler
|
9 | 9 | import com.openai.core.http.SseMessage
|
10 | 10 | import com.openai.core.http.StreamResponse
|
11 | 11 | import com.openai.errors.OpenAIException
|
12 | 12 | import java.util.stream.Stream
|
| 13 | +import kotlin.jvm.optionals.getOrNull |
13 | 14 | import kotlin.streams.asStream
|
14 | 15 |
|
15 |
| -@JvmSynthetic internal fun sseHandler(): Handler<StreamResponse<SseMessage>> = SseHandlerInternal |
16 |
| - |
17 |
| -private object SseHandlerInternal : Handler<StreamResponse<SseMessage>> { |
18 |
| - |
19 |
| - override fun handle(response: HttpResponse): StreamResponse<SseMessage> { |
20 |
| - val sequence = sequence { |
21 |
| - response.body().bufferedReader().buffered().useLines { lines -> |
22 |
| - val state = SseState() |
23 |
| - var done = false |
24 |
| - for (line in lines) { |
25 |
| - // Stop emitting messages, but iterate through the full stream. |
26 |
| - if (done) { |
27 |
| - continue |
28 |
| - } |
29 |
| - val message = state.decode(line) ?: continue |
30 |
| - |
31 |
| - if (message.data.startsWith("[DONE]")) { |
32 |
| - // In this case we don't break because we still want to iterate through the |
33 |
| - // full stream. |
34 |
| - done = true |
35 |
| - continue |
36 |
| - } |
37 |
| - |
38 |
| - if (message.event == null) { |
39 |
| - yield(message) |
| 16 | +@JvmSynthetic |
| 17 | +internal fun sseHandler(jsonMapper: JsonMapper): Handler<StreamResponse<SseMessage>> = |
| 18 | + object : Handler<StreamResponse<SseMessage>> { |
| 19 | + |
| 20 | + override fun handle(response: HttpResponse): StreamResponse<SseMessage> { |
| 21 | + val sequence = sequence { |
| 22 | + response.body().bufferedReader().buffered().useLines { lines -> |
| 23 | + val state = SseState(jsonMapper) |
| 24 | + var done = false |
| 25 | + for (line in lines) { |
| 26 | + // Stop emitting messages, but iterate through the full stream. |
| 27 | + if (done) { |
| 28 | + continue |
| 29 | + } |
| 30 | + val message = state.decode(line) ?: continue |
| 31 | + |
| 32 | + if (message.data.startsWith("[DONE]")) { |
| 33 | + // In this case we don't break because we still want to iterate through |
| 34 | + // the full stream. |
| 35 | + done = true |
| 36 | + continue |
| 37 | + } |
| 38 | + |
| 39 | + if (message.event == null) { |
| 40 | + val error = |
| 41 | + message.json<JsonValue>().asObject().getOrNull()?.get("error") |
| 42 | + if (error != null) { |
| 43 | + val errorMessage = |
| 44 | + error.asString().getOrNull() |
| 45 | + ?: error |
| 46 | + .asObject() |
| 47 | + .getOrNull() |
| 48 | + ?.get("message") |
| 49 | + ?.asString() |
| 50 | + ?.getOrNull() |
| 51 | + ?: "An error occurred during streaming" |
| 52 | + throw OpenAIException(errorMessage) |
| 53 | + } |
| 54 | + yield(message) |
| 55 | + } |
40 | 56 | }
|
41 | 57 | }
|
42 | 58 | }
|
43 |
| - } |
44 | 59 |
|
45 |
| - return object : StreamResponse<SseMessage> { |
46 |
| - override fun stream(): Stream<SseMessage> = sequence.asStream() |
| 60 | + return object : StreamResponse<SseMessage> { |
| 61 | + override fun stream(): Stream<SseMessage> = sequence.asStream() |
47 | 62 |
|
48 |
| - override fun close() = response.close() |
| 63 | + override fun close() = response.close() |
| 64 | + } |
49 | 65 | }
|
50 | 66 | }
|
51 | 67 |
|
52 |
| - private class SseState( |
53 |
| - var event: String? = null, |
54 |
| - val data: MutableList<String> = mutableListOf(), |
55 |
| - var lastId: String? = null, |
56 |
| - var retry: Int? = null |
57 |
| - ) { |
58 |
| - // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation |
59 |
| - fun decode(line: String): SseMessage? { |
60 |
| - if (line.isEmpty()) { |
61 |
| - return flush() |
62 |
| - } |
| 68 | +private class SseState( |
| 69 | + val jsonMapper: JsonMapper, |
| 70 | + var event: String? = null, |
| 71 | + val data: MutableList<String> = mutableListOf(), |
| 72 | + var lastId: String? = null, |
| 73 | + var retry: Int? = null |
| 74 | +) { |
| 75 | + // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation |
| 76 | + fun decode(line: String): SseMessage? { |
| 77 | + if (line.isEmpty()) { |
| 78 | + return flush() |
| 79 | + } |
63 | 80 |
|
64 |
| - if (line.startsWith(':')) { |
65 |
| - return null |
66 |
| - } |
| 81 | + if (line.startsWith(':')) { |
| 82 | + return null |
| 83 | + } |
67 | 84 |
|
68 |
| - val fieldName: String |
69 |
| - var value: String |
| 85 | + val fieldName: String |
| 86 | + var value: String |
70 | 87 |
|
71 |
| - val colonIndex = line.indexOf(':') |
72 |
| - if (colonIndex == -1) { |
73 |
| - fieldName = line |
74 |
| - value = "" |
75 |
| - } else { |
76 |
| - fieldName = line.substring(0, colonIndex) |
77 |
| - value = line.substring(colonIndex + 1) |
78 |
| - } |
| 88 | + val colonIndex = line.indexOf(':') |
| 89 | + if (colonIndex == -1) { |
| 90 | + fieldName = line |
| 91 | + value = "" |
| 92 | + } else { |
| 93 | + fieldName = line.substring(0, colonIndex) |
| 94 | + value = line.substring(colonIndex + 1) |
| 95 | + } |
79 | 96 |
|
80 |
| - if (value.startsWith(' ')) { |
81 |
| - value = value.substring(1) |
82 |
| - } |
| 97 | + if (value.startsWith(' ')) { |
| 98 | + value = value.substring(1) |
| 99 | + } |
83 | 100 |
|
84 |
| - when (fieldName) { |
85 |
| - "event" -> event = value |
86 |
| - "data" -> data.add(value) |
87 |
| - "id" -> { |
88 |
| - if (!value.contains('\u0000')) { |
89 |
| - lastId = value |
90 |
| - } |
| 101 | + when (fieldName) { |
| 102 | + "event" -> event = value |
| 103 | + "data" -> data.add(value) |
| 104 | + "id" -> { |
| 105 | + if (!value.contains('\u0000')) { |
| 106 | + lastId = value |
91 | 107 | }
|
92 |
| - "retry" -> value.toIntOrNull()?.let { retry = it } |
93 | 108 | }
|
94 |
| - |
95 |
| - return null |
| 109 | + "retry" -> value.toIntOrNull()?.let { retry = it } |
96 | 110 | }
|
97 | 111 |
|
98 |
| - private fun flush(): SseMessage? { |
99 |
| - if (isEmpty()) { |
100 |
| - return null |
101 |
| - } |
102 |
| - |
103 |
| - val message = |
104 |
| - SseMessage.builder() |
105 |
| - .event(event) |
106 |
| - .data(data.joinToString("\n")) |
107 |
| - .id(lastId) |
108 |
| - .retry(retry) |
109 |
| - .build() |
110 |
| - |
111 |
| - // NOTE: Per the SSE spec, do not reset lastId. |
112 |
| - event = null |
113 |
| - data.clear() |
114 |
| - retry = null |
| 112 | + return null |
| 113 | + } |
115 | 114 |
|
116 |
| - return message |
| 115 | + private fun flush(): SseMessage? { |
| 116 | + if (isEmpty()) { |
| 117 | + return null |
117 | 118 | }
|
118 | 119 |
|
119 |
| - private fun isEmpty(): Boolean = |
120 |
| - event.isNullOrEmpty() && data.isEmpty() && lastId.isNullOrEmpty() && retry == null |
| 120 | + val message = |
| 121 | + SseMessage.builder() |
| 122 | + .jsonMapper(jsonMapper) |
| 123 | + .event(event) |
| 124 | + .data(data.joinToString("\n")) |
| 125 | + .id(lastId) |
| 126 | + .retry(retry) |
| 127 | + .build() |
| 128 | + |
| 129 | + // NOTE: Per the SSE spec, do not reset lastId. |
| 130 | + event = null |
| 131 | + data.clear() |
| 132 | + retry = null |
| 133 | + |
| 134 | + return message |
121 | 135 | }
|
| 136 | + |
| 137 | + private fun isEmpty(): Boolean = |
| 138 | + event.isNullOrEmpty() && data.isEmpty() && lastId.isNullOrEmpty() && retry == null |
122 | 139 | }
|
123 | 140 |
|
124 | 141 | @JvmSynthetic
|
125 |
| -internal inline fun <reified T> Handler<StreamResponse<SseMessage>>.mapJson( |
126 |
| - jsonMapper: JsonMapper |
127 |
| -): Handler<StreamResponse<T>> = |
| 142 | +internal inline fun <reified T> Handler<StreamResponse<SseMessage>>.mapJson(): |
| 143 | + Handler<StreamResponse<T>> = |
128 | 144 | object : Handler<StreamResponse<T>> {
|
129 | 145 | override fun handle(response: HttpResponse): StreamResponse<T> =
|
130 | 146 | this@mapJson.handle(response).map {
|
131 | 147 | try {
|
132 |
| - jsonMapper.readValue(it.data, jacksonTypeRef()) |
| 148 | + it.json<T>() |
133 | 149 | } catch (e: Exception) {
|
134 | 150 | throw OpenAIException("Error reading response", e)
|
135 | 151 | }
|
|
0 commit comments