From 108086990c359158d6d1c8c006fa7826ee227305 Mon Sep 17 00:00:00 2001 From: shaohuzhang1 Date: Wed, 3 Jan 2024 18:10:40 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20fetch=E6=97=A0=E6=B3=95=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E6=AD=A3=E7=A1=AE=E4=BB=8Echunk?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ui/src/components/ai-chat/index.vue | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/ui/src/components/ai-chat/index.vue b/ui/src/components/ai-chat/index.vue index dbdd084af..fe4c8e79e 100644 --- a/ui/src/components/ai-chat/index.vue +++ b/ui/src/components/ai-chat/index.vue @@ -273,6 +273,7 @@ function chatMessage() { ChatManagement.addChatRecord(row, 50, loading) ChatManagement.write(id) const reader = response.body.getReader() + let tempResult = '' /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/ const write = ({ done, value }: { done: boolean; value: any }) => { try { @@ -282,7 +283,16 @@ function chatMessage() { } const decoder = new TextDecoder('utf-8') - const str = decoder.decode(value, { stream: true }) + let str = decoder.decode(value, { stream: true }) + // 这里解释一下 start 因为数据流返回流并不是按照后端chunk返回 我们希望得到的chunk是data:{xxx}\n\n 但是它获取到的可能是 data:{ -> xxx}\n\n 总而言之就是 fetch不能保证每个chunk都说以data:开始 \n\n结束 + tempResult += str + if (tempResult.endsWith('\n\n')) { + str = tempResult + tempResult = '' + } else { + return reader.read().then(write) + } + // 这里解释一下 end if (str && str.startsWith('data:')) { const split = str.match(/data:.*}\n\n/g) if (split) {