Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the problem of missing messages when streaming messages #12

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions Shared/ChatGPTAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,22 +98,23 @@ class ChatGPTAPI: LLMClient, @unchecked Sendable {

throw "Bad Response: \(httpResponse.statusCode), \(errorText)"
}

var responseText = ""
return AsyncThrowingStream { [weak self] in
guard let self else { return nil }
for try await line in result.lines {
try Task.checkCancellation()
if line.hasPrefix("data: "),
let data = line.dropFirst(6).data(using: .utf8),
let response = try? self.jsonDecoder.decode(StreamCompletionResponse.self, from: data),
let text = response.choices.first?.delta.content {
responseText += text
return text

return AsyncThrowingStream { continuation in
Task {
var responseText = ""
for try await line in result.lines {
try Task.checkCancellation()
if line.hasPrefix("data: "),
let data = line.dropFirst(6).data(using: .utf8),
let response = try? self.jsonDecoder.decode(StreamCompletionResponse.self, from: data),
let text = response.choices.first?.delta.content {
responseText += text
continuation.yield(text)
}
}
self.appendToHistoryList(userText: text, responseText: responseText)
continuation.finish()
}
self.appendToHistoryList(userText: text, responseText: responseText)
return nil
}
}

Expand Down