Update chat.service.js

This commit is contained in:
vastxie 2024-05-18 20:51:28 +08:00 committed by GitHub
parent 1ca06679a0
commit 5d2caa4d3a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -994,38 +994,42 @@ let ChatService = class ChatService {
} }
} }
async sendMessageFromAi(messagesHistory, inputs, isClientClosed) { async sendMessageFromAi(messagesHistory, inputs, isClientClosed) {
if (isClientClosed) { const { onFailure, onProgress, apiKey, model, proxyUrl, modelName, timeout, chatId, isFileUpload, modelAvatar, temperature, } = inputs;
console.log("操作终止,因为客户端已关闭连接"); let result = {
return; text: '',
} model: '',
const { onFailure, onProgress, apiKey, model, proxyUrl, modelName, timeout, chatId, isFileUpload } = inputs; modelName: modelName,
let result = { text: '', model: '', modelName: modelName, chatId: chatId, answer: '', errMsg: '' }; chatId: chatId,
answer: '',
errMsg: '',
modelAvatar: modelAvatar,
};
const options = { const options = {
method: 'POST', method: 'POST',
url: `${proxyUrl}/v1/chat/completions`, url: `${proxyUrl}/v1/chat/completions`,
responseType: "stream", responseType: 'stream',
timeout: timeout, timeout: timeout,
headers: { headers: {
"Content-Type": "application/json", 'Content-Type': 'application/json',
"Authorization": `Bearer ${apiKey}`, Authorization: `Bearer ${apiKey}`,
}, },
data: Object.assign({ stream: true, model, messages: messagesHistory }, (isFileUpload === 2 && { max_tokens: 2048 })), data: Object.assign({ stream: true, model, temperature: temperature, messages: messagesHistory }, (isFileUpload === 2 && { max_tokens: 2048 })),
}; };
try { try {
const response = await (0, axios_1.default)(options); const response = await (0, axios_1.default)(options);
const stream = response.data; const stream = response.data;
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
stream.on('data', (chunk) => { stream.on('data', (chunk) => {
const splitArr = chunk.toString().split('\n\n').filter(line => line.trim()); const pattern = /(?<=\})(\n\n)(?=data)/g;
splitArr.forEach(line => { const splitArr = chunk
.toString()
.split(pattern)
.filter((line) => line.trim());
// common_1.Logger.log('splitArr', splitArr);
splitArr.forEach((line) => {
var _a, _b; var _a, _b;
if (line.trim() === "data: [DONE]") { if (line.trim() === 'data: [DONE]') {
console.log("处理结束信号 [DONE]"); console.log('处理结束信号 [DONE]');
resolve(result);
return;
}
if (isClientClosed) {
console.log("操作终止,因为客户端已关闭连接");
resolve(result); resolve(result);
return; return;
} }
@ -1041,7 +1045,6 @@ let ChatService = class ChatService {
} }
} }
catch (error) { catch (error) {
common_1.Logger.error('返回格式错误,重新提取回答', error, line);
const contentMatch = line.match(/"content":"([^"]+)"/); const contentMatch = line.match(/"content":"([^"]+)"/);
if (contentMatch && contentMatch[1]) { if (contentMatch && contentMatch[1]) {
result.answer += contentMatch[1]; result.answer += contentMatch[1];