Skip to content

Commit 1de5e62

Browse files
committed
fix: handle fragmented stream data from OpenAI API
1 parent 3a5de9e commit 1de5e62

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

src/main.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -318,8 +318,9 @@ function translate(query) {
318318
const header = buildHeader(isAzureServiceProvider, apiKey);
319319
const body = buildRequestBody(model, isChatGPTModel, query);
320320

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

0 commit comments

Comments
 (0)