Browse Source

优化ai对话逻辑

cq.tianyong 3 hours ago
parent
commit
fb6378f270
3 changed files with 50 additions and 40 deletions
  1. 0 27
      apis/AIChat/Conversation/Save.js
  2. 11 2
      apis/AIChat/Message/Send.js
  3. 39 11
      lib/AIChat/ConversationService.js

+ 0 - 27
apis/AIChat/Conversation/Save.js

@@ -1,27 +0,0 @@
-const API = require('../../../lib/API')
-const { BaseStdResponse } = require('../../../BaseStdResponse')
-const AccessControl = require('../../../lib/AccessControl')
-const { ConversationService } = require('../../../lib/AIChat/ConversationService')
-
-class SaveConversation extends API {
-    constructor() {
-        super()
-        this.setPath('/AIChat/Conversation')
-        this.setMethod('POST')
-    }
-
-    async onRequest(req, res) {
-        const { uuid, session, title } = req.body
-        if ([uuid, session].some(v => v === '' || v === null || v === undefined)) {
-            return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
-        }
-        if (!await AccessControl.checkSession(uuid, session)) {
-            return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })
-        }
-        const data = await ConversationService.createConversation({ uuid, title })
-        if (!data?.id) return res.json({ ...BaseStdResponse.DATABASE_ERR })
-        return res.json({ ...BaseStdResponse.OK, data })
-    }
-}
-
-module.exports.SaveConversation = SaveConversation

+ 11 - 2
apis/AIChat/Message/Send.js

@@ -13,7 +13,7 @@ class SendMessage extends API {
 
     async onRequest(req, res) {
         const { uuid, session, conversation_id, content, images = [] } = req.body
-        if ([uuid, session, conversation_id].some(v => v === '' || v === null || v === undefined)) {
+        if ([uuid, session].some(v => v === '' || v === null || v === undefined)) {
             return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
         }
         if (!await AccessControl.checkSession(uuid, session)) {
@@ -29,7 +29,16 @@ class SendMessage extends API {
         if (!saved) return res.json({ ...BaseStdResponse.ERR, msg: '会话不存在或无权发送' })
         if (saved.missingContent) return res.json({ ...BaseStdResponse.MISSING_PARAMETER, msg: '请输入消息或上传图片' })
 
-        res.json({ ...BaseStdResponse.OK, data: { message_id: saved.messageId } })
+        res.json({
+            ...BaseStdResponse.OK,
+            data: {
+                message_id: saved.messageId,
+                conversation_id: saved.conversationId,
+                conversation_no: saved.conversationNo,
+                conversation: saved.conversation,
+                message: saved.message
+            }
+        })
 
         try {
             await OneBotV11.sendAiChatMessage({

+ 39 - 11
lib/AIChat/ConversationService.js

@@ -4,6 +4,7 @@ const db = require('../../plugin/DataBase/db')
 const ACTIVE_STATE = 1
 const DELETED_STATE = 2
 const ASSISTANT_UUID = 'e4fe0277-0b1a-41a1-b25f-8b6e4cec3281'
+const DEFAULT_TITLE = '新对话'
 
 function toPositiveInt(value, fallback = null) {
     const n = Number(value)
@@ -67,9 +68,11 @@ async function generateConversationNo() {
 }
 
 async function assertUserConversation(conversationId, uuid) {
+    const id = toPositiveInt(conversationId)
+    if (!id) return null
     const rows = await db.query(
         'SELECT id, conversation_no, create_user, title, state FROM ai_chat_conversation WHERE id = ? AND create_user = ? AND state = ? LIMIT 1',
-        [conversationId, uuid, ACTIVE_STATE]
+        [id, uuid, ACTIVE_STATE]
     )
     return rows && rows.length === 1 ? rows[0] : null
 }
@@ -113,7 +116,7 @@ class ConversationService {
         }
 
         const now = Date.now()
-        const safeTitle = normalizeText(title, 80) || '新对话'
+        const safeTitle = normalizeText(title, 80) || DEFAULT_TITLE
         const conversationNo = await generateConversationNo()
         const result = await db.query(
             `INSERT INTO ai_chat_conversation
@@ -184,32 +187,57 @@ class ConversationService {
     }
 
     async addUserMessage({ uuid, conversationId, content, images }) {
-        const conv = await assertUserConversation(conversationId, uuid)
-        if (!conv) return null
-
         const text = normalizeText(content, 2000)
         const imgs = normalizeImages(images)
         if (!text && imgs.length === 0) return { missingContent: true }
 
+        const preview = buildPreview(text, imgs)
+        const conv = conversationId
+            ? await assertUserConversation(conversationId, uuid)
+            : await this.createConversation({ uuid, title: preview ? preview.slice(0, 40) : DEFAULT_TITLE })
+        if (!conv) return null
+
         const now = Date.now()
         const result = await db.query(
             `INSERT INTO ai_chat_message
              (conversation_id, create_user, role, content, images, status, error_msg, create_time, update_time)
              VALUES (?, ?, 'user', ?, ?, 'done', '', ?, ?)`,
-            [conversationId, uuid, text, JSON.stringify(imgs), now, now]
+            [conv.id, uuid, text, JSON.stringify(imgs), now, now]
         )
-        const preview = buildPreview(text, imgs)
-        const title = conv.title === '新对话' && preview ? preview.slice(0, 40) : conv.title
+        const title = (!conv.title || conv.title === DEFAULT_TITLE || Number(conv.last_message_time || 0) === 0) && preview
+            ? preview.slice(0, 40)
+            : conv.title
         await db.query(
             'UPDATE ai_chat_conversation SET title = ?, last_message_preview = ?, last_message_time = ?, update_time = ? WHERE id = ?',
-            [title, preview, now, now, conversationId]
+            [title, preview, now, now, conv.id]
         )
         return {
-            conversationId,
+            conversationId: conv.id,
             conversationNo: conv.conversation_no,
             messageId: result?.insertId,
             content: text,
-            images: imgs
+            images: imgs,
+            conversation: {
+                id: conv.id,
+                conversation_no: conv.conversation_no,
+                title,
+                state: ACTIVE_STATE,
+                last_message_preview: preview,
+                last_message_time: now,
+                create_time: conv.create_time || now,
+                update_time: now
+            },
+            message: {
+                id: result?.insertId,
+                conversation_id: conv.id,
+                role: 'user',
+                content: text,
+                images: imgs,
+                status: 'done',
+                error_msg: '',
+                create_time: now,
+                update_time: now
+            }
         }
     }