Skip to content

Commit 2250f45

Browse files
committed
Handle parsing case where stream response has multiple chunks of in byte stream
1 parent 56499bb commit 2250f45

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 0.0.6
2+
3+
* Handle parsing case where stream response has multiple chunks in byte stream
4+
15
## 0.0.5
26

37
* Use substring instead of replaceFirst for parsing stream response

lib/src/chatgptclient.dart

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,17 +103,20 @@ class ChatGPTClient {
103103

104104
var responseText = "";
105105
await for (final byte in byteStream) {
106-
var decoded = utf8.decode(byte).trim();
107-
if (decoded.startsWith("data: ") && !decoded.endsWith("[DONE]")) {
108-
decoded = decoded.substring(6);
109-
final map = jsonDecode(decoded) as Map;
106+
var decoded = utf8.decode(byte);
107+
final strings = decoded.split("data: ");
108+
for (final string in strings) {
109+
final trimmedString = string.trim();
110+
if (trimmedString.isNotEmpty && !trimmedString.endsWith("[DONE]")) {
111+
final map = jsonDecode(trimmedString) as Map;
110112
final choices = map["choices"] as List;
111113
final delta = choices[0]["delta"] as Map;
112114
if (delta["content"] != null) {
113115
final content = delta["content"] as String;
114116
responseText += content;
115117
yield content;
116118
}
119+
}
117120
}
118121
}
119122

pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name: chatgpt_client
22
description: ChatGPT API Client for Dart
3-
version: 0.0.5
3+
version: 0.0.6
44
homepage: https://github.com/alfianlosari/chatgpt_api_dart
55

66
environment:

0 commit comments

Comments
 (0)