Skip to content

Commit be57514

Browse files
committed
Fix stop responding
1 parent d716269 commit be57514

1 file changed

Lines changed: 24 additions & 18 deletions

File tree

Core/Sources/OpenAIService/CompletionStreamAPI.swift

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -89,28 +89,34 @@ struct OpenAICompletionStreamAPI: CompletionStreamAPI {
8989
let error = try? decoder.decode(ChatGPTError.self, from: data)
9090
throw error ?? ChatGPTServiceError.responseInvalid
9191
}
92-
93-
return (
94-
AsyncThrowingStream<CompletionStreamDataTrunk, Error> { continuation in
95-
Task {
96-
do {
97-
for try await line in result.lines {
98-
let prefix = "data: "
99-
guard line.hasPrefix(prefix),
100-
let content = line.dropFirst(prefix.count).data(using: .utf8),
101-
let trunk = try? JSONDecoder()
102-
.decode(CompletionStreamDataTrunk.self, from: content)
103-
else { continue }
104-
continuation.yield(trunk)
105-
}
106-
continuation.finish()
107-
} catch {
108-
continuation.finish(throwing: error)
92+
93+
var receivingDataTask: Task<Void, Error>?
94+
95+
let stream = AsyncThrowingStream<CompletionStreamDataTrunk, Error> { continuation in
96+
receivingDataTask = Task {
97+
do {
98+
for try await line in result.lines {
99+
if Task.isCancelled { break }
100+
let prefix = "data: "
101+
guard line.hasPrefix(prefix),
102+
let content = line.dropFirst(prefix.count).data(using: .utf8),
103+
let trunk = try? JSONDecoder()
104+
.decode(CompletionStreamDataTrunk.self, from: content)
105+
else { continue }
106+
continuation.yield(trunk)
109107
}
108+
continuation.finish()
109+
} catch {
110+
continuation.finish(throwing: error)
110111
}
111-
},
112+
}
113+
}
114+
115+
return (
116+
stream,
112117
Cancellable {
113118
result.task.cancel()
119+
receivingDataTask?.cancel()
114120
}
115121
)
116122
}

0 commit comments

Comments
 (0)