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: gemini stream error #712

Merged
merged 2 commits into from
Nov 2, 2024
Merged
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
16 changes: 15 additions & 1 deletion Easydict/Swift/Service/Gemini/GeminiService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,14 @@ public final class GeminiService: LLMStreamService {
return chatModels
}

override func cancelStream() {
currentTask?.cancel()
}

// MARK: Private

private var currentTask: Task<(), Never>?

// Set Gemini safety level to BLOCK_NONE
private let blockNoneSettings = [
SafetySetting(harmCategory: .harassment, threshold: .blockNone),
Expand All @@ -109,11 +115,15 @@ public final class GeminiService: LLMStreamService {
to: Language,
completion: @escaping (EZQueryResult, Error?) -> ()
) {
if let currentTask, currentTask.isCancelled == false {
currentTask.cancel()
}

let queryType = queryType(text: text, from: from, to: to)

// Gemini Docs: https://github.com/google/generative-ai-swift

Task {
currentTask = Task {
do {
result.isStreamFinished = false

Expand Down Expand Up @@ -152,6 +162,7 @@ public final class GeminiService: LLMStreamService {

let outputContentStream = model.generateContentStream(chatHistory)
for try await outputContent in outputContentStream {
try Task.checkCancellation()
guard let line = outputContent.text else {
return
}
Expand All @@ -163,6 +174,9 @@ public final class GeminiService: LLMStreamService {
updateResultText(resultText, queryType: queryType, error: nil, completion: completion)
result.isStreamFinished = true

} catch is CancellationError {
// Task was cancelled.
log("Gemini task was cancelled.")
} catch {
/**
https://github.com/google/generative-ai-swift/issues/89
Expand Down