diff --git a/src/routes/chat-history/chat-io.ts b/src/routes/chat-history/chat-io.ts index e5831f9..ae90435 100644 --- a/src/routes/chat-history/chat-io.ts +++ b/src/routes/chat-history/chat-io.ts @@ -54,29 +54,46 @@ const onMessage = async ({ data, end, ws }) => { return; } const { uid, id, key } = client.data; - const { inputs, message: sendMessage } = data; + const { + inputs, + message: sendMessage, + data: {}, + } = data; let root = data.root || false; let chatSession = await ChatSession.findByPk(id); const config = await getConfigByKey(key); const { prompt, aiAgent, chatPrompt } = config; + let userQuestion = sendMessage; if (!chatSession) { - chatSession = await ChatSession.create({ key, id, data: {}, uid, chatPromptId: chatPrompt.id }); + chatSession = await ChatSession.create({ key, id, data: data, uid, chatPromptId: chatPrompt.id }); root = true; } else { + // 更新session context的值 + const newData = JSON.parse(data); + if (newData !== '{}' && JSON.stringify(chatSession.data) !== JSON.stringify(data)) { + await chatSession.update({ data: data }); + } + if (root) { + const chatHistory = await ChatHistory.findAll({ where: { chatId: id }, logging: false }); + chatHistory.forEach((item) => { + end({ code: 200, data: item, message: 'success', type: 'messages' }); + }); + // return; + } root = false; - const chatHistory = await ChatHistory.findAll({ where: { chatId: id }, logging: false }); - chatHistory.forEach((item) => { - end({ code: 200, data: item, message: 'success', type: 'messages' }); - }); - return; } - - const template = await getTemplate({ data: prompt.presetData.data, inputs }); - if (!template) { - end({ code: 404, data: {}, message: 'template not found' }); - return; + if (!userQuestion) { + if (!prompt?.presetData) { + end({ code: 404, data: {}, message: 'prompt not set, need presetData' }); + return; + } + const template = await getTemplate({ data: prompt.presetData.data, inputs }); + if (!template) { + end({ code: 404, data: {}, message: 'template not found' }); + return; + } + userQuestion = template; } - const userQuestion = template || sendMessage; // 保存到数据库 const roleUser = await ChatHistory.create({ data: { @@ -90,7 +107,7 @@ const onMessage = async ({ data, end, ws }) => { role: 'user', }); end({ code: 200, data: roleUser, message: 'success', type: 'messages' }); - const result = await aiAgent.sendHumanMessage(template, { thread_id: id }); + const result = await aiAgent.sendHumanMessage(userQuestion, { thread_id: id }); const lastMessage = result.messages[result.messages.length - 1]; const message = result.messages[result.messages.length - 1].content; // 根据key找到对应的prompt