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 parse exception when sse stream returns incomplete data #80

Merged
merged 1 commit into from
Nov 22, 2023
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
31 changes: 28 additions & 3 deletions lib/src/client/openai_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,9 @@ class OpenAIClient extends OpenAIWrapper {
)
.then(
(it) {
// Sometimes, the information in a response may be truncated, in which
// case it needs to be concatenated with the next one.
String tmpData = '';
it.data.stream.listen(
(it) {
final rawData = utf8.decode(it);
Expand All @@ -276,9 +279,31 @@ class OpenAIClient extends OpenAIWrapper {
return;
}

controller
..sink
..add(complete(json.decode(data)));
try {
controller
..sink
..add(complete(json.decode(data)));
tmpData = '';
} on FormatException catch (_) {
// Sometimes, the information in a response may be truncated,
// in which case it needs to be concatenated with the next one.
tmpData = data;
}
} else {
// If the response does not start with 'data: ', it is considered
// to be truncated, and at this time it needs to be concatenated
// together with 'tmpData'.
try {
final decodeData = json.decode('$tmpData$line');
controller
..sink
..add(complete(decodeData));
} catch (e) {
// skip
log.log('unexpected exception: $e');
log.log('tmpData=$tmpData\nline=$line');
}
tmpData = '';
}
}
},
Expand Down
Loading