Skip to content

Commit ca9e981

Browse files
committed
Use ResponseStream to handle stream responses
1 parent a412c23 commit ca9e981

1 file changed

Lines changed: 18 additions & 27 deletions

File tree

Tool/Sources/OpenAIService/APIs/OpenAIChatCompletionsService.swift

Lines changed: 18 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -218,37 +218,28 @@ actor OpenAIChatCompletionsService: ChatCompletionsStreamAPI, ChatCompletionsAPI
218218
throw error ?? ChatGPTServiceError.responseInvalid
219219
}
220220

221-
let stream = AsyncThrowingStream<ChatCompletionsStreamDataChunk, Error> { continuation in
222-
let task = Task {
223-
do {
224-
for try await line in result.lines {
225-
if Task.isCancelled { break }
226-
let prefix = "data: "
227-
guard line.hasPrefix(prefix),
228-
let content = line.dropFirst(prefix.count).data(using: .utf8)
229-
else { continue }
230-
do {
231-
let chunk = try JSONDecoder().decode(
232-
StreamDataChunk.self,
233-
from: content
234-
)
235-
continuation.yield(chunk.formalized())
236-
} catch {
237-
Logger.service.error("Error decoding stream data: \(error)")
238-
}
239-
}
240-
continuation.finish()
241-
} catch {
242-
continuation.finish(throwing: error)
243-
}
221+
let stream = ResponseStream<StreamDataChunk>(result: result) {
222+
var line = $0
223+
let prefix = "data: "
224+
if line.hasPrefix(prefix) {
225+
line.removeFirst(prefix.count)
244226
}
245-
continuation.onTermination = { _ in
246-
task.cancel()
247-
result.task.cancel()
227+
228+
if line == "[DONE]" { return .init(chunk: nil, done: true) }
229+
230+
do {
231+
let chunk = try JSONDecoder().decode(
232+
StreamDataChunk.self,
233+
from: line.data(using: .utf8) ?? Data()
234+
)
235+
return .init(chunk: chunk, done: false)
236+
} catch {
237+
Logger.service.error("Error decoding stream data: \(error)")
238+
throw error
248239
}
249240
}
250241

251-
return stream
242+
return stream.map { $0.formalized() }.toStream()
252243
}
253244

254245
func callAsFunction() async throws -> ChatCompletionResponseBody {

0 commit comments

Comments
 (0)