Skip to content

Commit d9192df

Browse files
authored
Merge pull request #104 from PallavAg/patch-1
Correctly handle partial JSON at the end of a chunk
2 parents 41b3515 + 8f08006 commit d9192df

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

Sources/OpenAI/Private/StreamingSession.swift

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
2828
return session
2929
}()
3030

31+
private var previousChunkBuffer = ""
32+
3133
init(urlRequest: URLRequest) {
3234
self.urlRequest = urlRequest
3335
}
@@ -47,14 +49,25 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
4749
onProcessingError?(self, StreamingError.unknownContent)
4850
return
4951
}
50-
let jsonObjects = stringContent
52+
processJSON(from: stringContent)
53+
}
54+
55+
}
56+
57+
extension StreamingSession {
58+
59+
private func processJSON(from stringContent: String) {
60+
let jsonObjects = "\(previousChunkBuffer)\(stringContent)"
5161
.components(separatedBy: "data:")
5262
.filter { $0.isEmpty == false }
5363
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
64+
65+
previousChunkBuffer = ""
66+
5467
guard jsonObjects.isEmpty == false, jsonObjects.first != streamingCompletionMarker else {
5568
return
5669
}
57-
jsonObjects.forEach { jsonContent in
70+
jsonObjects.enumerated().forEach { (index, jsonContent) in
5871
guard jsonContent != streamingCompletionMarker else {
5972
return
6073
}
@@ -77,9 +90,14 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
7790
let decoded = try JSONDecoder().decode(APIErrorResponse.self, from: jsonData)
7891
onProcessingError?(self, decoded)
7992
} catch {
80-
onProcessingError?(self, apiError)
93+
if index == jsonObjects.count - 1 {
94+
previousChunkBuffer = "data: \(jsonContent)" // Chunk ends in a partial JSON
95+
} else {
96+
onProcessingError?(self, apiError)
97+
}
8198
}
8299
}
83100
}
84101
}
102+
85103
}

0 commit comments

Comments
 (0)