From 600a42938c8dc912977b43705eb8b33ac264b4d9 Mon Sep 17 00:00:00 2001 From: Vinlic Date: Fri, 26 Apr 2024 16:19:57 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A4=9A=E8=BD=AE=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E6=97=B6=E6=96=87=E4=BB=B6=E4=BC=A0=E9=80=81=E8=A7=92?= =?UTF-8?q?=E8=89=B2=E9=94=99=E9=85=8D=EF=BC=8C=E6=8A=B9=E9=99=A4=E4=B8=B4?= =?UTF-8?q?=E6=97=B6=E6=96=87=E4=BB=B6=E8=B7=AF=E5=BE=84=E5=87=8F=E5=B0=91?= =?UTF-8?q?=E5=A4=9A=E8=BD=AE=E5=B9=BB=E8=A7=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/controllers/chat.ts | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/api/controllers/chat.ts b/src/api/controllers/chat.ts index 2d0e802..a37bc28 100644 --- a/src/api/controllers/chat.ts +++ b/src/api/controllers/chat.ts @@ -486,10 +486,6 @@ function extractRefFileUrls(messages: any[]) { * 消息预处理 * * 由于接口只取第一条消息,此处会将多条消息合并为一条,实现多轮对话效果 - * 使用”你“这个角色回复”我“这个角色,以第一人称对话\n - * 我:旧消息1 - * 你:旧消息2 - * 我:新消息 * * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文 */ @@ -520,20 +516,25 @@ function messagesPrepare(messages: any[], refs: any[]) { const content = ( messages.reduce((content, message) => { + const role = message.role + .replace("system", "<|sytstem|>") + .replace("assistant", "<|assistant|>") + .replace("user", "<|user|>"); if (_.isArray(message.content)) { return ( message.content.reduce((_content, v) => { if (!_.isObject(v) || v["type"] != "text") return _content; - return _content + ("<|user|>\n" + v["text"] || "") + "\n"; + return _content + (`${role}\n` + v["text"] || "") + "\n"; }, content) ); } - return (content += `${message.role - .replace("system", "<|sytstem|>") - .replace("assistant", "<|assistant|>") - .replace("user", "<|user|>")}\n${message.content}\n`); + return (content += `${role}\n${message.content}\n`); }, "") + "<|assistant|>\n" - ).replace(/\!\[.+\]\(.+\)/g, ""); + ) + // 移除MD图像URL避免幻觉 + .replace(/\!\[.+\]\(.+\)/g, "") + // 移除临时路径避免在新会话引发幻觉 + .replace(/\/mnt\/data\/.+/g, ""); const fileRefs = refs.filter((ref) => !ref.width && !ref.height); const imageRefs = refs .filter((ref) => ref.width || ref.height) @@ -541,6 +542,7 @@ function messagesPrepare(messages: any[], refs: any[]) { ref.image_url = ref.file_url; return ref; }); + content logger.info("\n对话合并:\n" + content); return [ { @@ -1062,7 +1064,7 @@ async function receiveImages( let match; while ((match = urlPattern.exec(text)) !== null) { const url = match[1]; - if(imageUrls.indexOf(url) == -1) + if (imageUrls.indexOf(url) == -1) imageUrls.push(url); } } @@ -1141,7 +1143,7 @@ async function getTokenLiveStatus(refreshToken: string) { const { accessToken } = _result; return !!accessToken; } - catch(err) { + catch (err) { return false; } }