Skip to content

Commit

Permalink
Move json processing to separate method
Browse files Browse the repository at this point in the history
  • Loading branch information
Ihor Makhnyk committed Nov 13, 2023
1 parent 80e9160 commit 8f08006
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions Sources/OpenAI/Private/StreamingSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
return session
}()

private var prevChunkBuffer = ""
private var previousChunkBuffer = ""

init(urlRequest: URLRequest) {
self.urlRequest = urlRequest
Expand All @@ -49,11 +49,20 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
onProcessingError?(self, StreamingError.unknownContent)
return
}
let jsonObjects = "\(prevChunkBuffer)\(stringContent)"
processJSON(from: stringContent)
}

}

extension StreamingSession {

private func processJSON(from stringContent: String) {
let jsonObjects = "\(previousChunkBuffer)\(stringContent)"
.components(separatedBy: "data:")
.filter { $0.isEmpty == false }
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
prevChunkBuffer = ""

previousChunkBuffer = ""

guard jsonObjects.isEmpty == false, jsonObjects.first != streamingCompletionMarker else {
return
Expand Down Expand Up @@ -82,13 +91,13 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
onProcessingError?(self, decoded)
} catch {
if index == jsonObjects.count - 1 {
// Chunk ends in a partial JSON
prevChunkBuffer = "data: \(jsonContent)"
previousChunkBuffer = "data: \(jsonContent)" // Chunk ends in a partial JSON
} else {
onProcessingError?(self, apiError)
}
}
}
}
}

}

0 comments on commit 8f08006

Please sign in to comment.