Skip to content

Commit

Permalink
รวมคําขอดึง #80 จาก wliu6v/fix-sse
Browse files Browse the repository at this point in the history
fix parse exception when sse stream returns incomplete data
  • Loading branch information
redevrx committed Nov 22, 2023
2 parents 62628a6 + be02275 commit 58ec1dc
Showing 1 changed file with 28 additions and 3 deletions.
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

0 comments on commit 58ec1dc

Please sign in to comment.