Skip to content

Commit

Permalink
fix: handle fragmented stream data from OpenAI API
Browse files Browse the repository at this point in the history
  • Loading branch information
liby committed Jun 4, 2023
1 parent 5d2ebe2 commit a53ac1c
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -319,8 +319,8 @@ function translate(query, completion) {
const header = buildHeader(isAzureServiceProvider, apiKey);
const body = buildRequestBody(model, isChatGPTModel, query);

// 初始化拼接结果变量
let targetText = "";
let targetText = ""; // 初始化拼接结果变量
let buffer = ""; // 新增 buffer 变量
(async () => {
await $http.streamRequest({
method: "POST",
Expand All @@ -338,14 +338,21 @@ function translate(query, completion) {
},
});
} else {
const lines = streamData.text.split('\n').filter(line => line);
lines.forEach(line => {
const match = line.match(/^data: (.*)/);
// 将新的数据添加到缓冲变量中
buffer += streamData.text;
// 检查缓冲变量是否包含一个完整的消息
while (true) {
const match = buffer.match(/data: (.*?})\n/);
if (match) {
// 如果是一个完整的消息,处理它并从缓冲变量中移除
const textFromResponse = match[1].trim();
targetText = handleResponse(query, isChatGPTModel, targetText, textFromResponse);
buffer = buffer.slice(match[0].length);
} else {
// 如果没有完整的消息,等待更多的数据
break;
}
});
}
}
},
handler: (result) => {
Expand Down

0 comments on commit a53ac1c

Please sign in to comment.