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: filter out sse comments #243

Closed
wants to merge 1 commit into from
Closed
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
15 changes: 12 additions & 3 deletions Sources/OpenAI/Private/StreamingSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,23 @@ extension StreamingSession {
if stringContent.isEmpty {
return
}
let jsonObjects = "\(previousChunkBuffer)\(stringContent)"

// Join the previous chunk buffer with the new chunk, and filter out comments.
// FIX OpenRouter: https://github.com/tisfeng/Easydict/issues/743
let filteredContent = "\(previousChunkBuffer)\(stringContent)"
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: .newlines)
.filter { !$0.hasPrefix(":") } // Filter out comments, like ": OPENROUTER PROCESSING"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, @tisfeng!
Is there any documentation on OpenRouter API about this line? We'd like to be sure we don't get a regression here and do not break any other providers.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And what do you think about writing unit tests that cover both cases (with and without comments)

.joined(separator: "\n")

// Split the filtered content into separate JSON objects.
let jsonObjects = filteredContent
.components(separatedBy: "data:")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { $0.isEmpty == false }
.filter { !$0.isEmpty }

previousChunkBuffer = ""

guard jsonObjects.isEmpty == false, jsonObjects.first != streamingCompletionMarker else {
return
}
Expand Down