Skip to content

Commit a53ac1c

Browse files
committed
fix: handle fragmented stream data from OpenAI API
1 parent 5d2ebe2 commit a53ac1c

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

src/main.js

+13-6
Original file line numberDiff line numberDiff line change
@@ -319,8 +319,8 @@ function translate(query, completion) {
319319
const header = buildHeader(isAzureServiceProvider, apiKey);
320320
const body = buildRequestBody(model, isChatGPTModel, query);
321321

322-
// 初始化拼接结果变量
323-
let targetText = "";
322+
let targetText = ""; // 初始化拼接结果变量
323+
let buffer = ""; // 新增 buffer 变量
324324
(async () => {
325325
await $http.streamRequest({
326326
method: "POST",
@@ -338,14 +338,21 @@ function translate(query, completion) {
338338
},
339339
});
340340
} else {
341-
const lines = streamData.text.split('\n').filter(line => line);
342-
lines.forEach(line => {
343-
const match = line.match(/^data: (.*)/);
341+
// 将新的数据添加到缓冲变量中
342+
buffer += streamData.text;
343+
// 检查缓冲变量是否包含一个完整的消息
344+
while (true) {
345+
const match = buffer.match(/data: (.*?})\n/);
344346
if (match) {
347+
// 如果是一个完整的消息,处理它并从缓冲变量中移除
345348
const textFromResponse = match[1].trim();
346349
targetText = handleResponse(query, isChatGPTModel, targetText, textFromResponse);
350+
buffer = buffer.slice(match[0].length);
351+
} else {
352+
// 如果没有完整的消息,等待更多的数据
353+
break;
347354
}
348-
});
355+
}
349356
}
350357
},
351358
handler: (result) => {

0 commit comments

Comments
 (0)