From 80428e625f0387435de5dc6c44c7b9a0b10503a3 Mon Sep 17 00:00:00 2001 From: jinhhanhan <1683105490@qq.com> Date: Sat, 13 Dec 2025 16:19:29 +0800 Subject: [PATCH] =?UTF-8?q?chore=EF=BC=9A=E5=8F=AF=E4=BB=A5=E7=9C=8B?= =?UTF-8?q?=E5=88=B0=E4=B9=8B=E5=89=8D=E5=8E=86=E5=8F=B2=E5=AF=B9=E8=AF=9D?= =?UTF-8?q?=E4=BA=86=EF=BC=8C=E4=BD=86=E6=98=AF=E8=8E=B7=E5=8F=96=E6=97=B6?= =?UTF-8?q?=E4=BC=9A=E6=99=83=E5=8A=A8=E4=B8=8D=E5=AE=8C=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/js/ai-service.js | 60 +++++-- .../ai-chat-message/ai-chat-message.vue | 148 ++++++++++++++---- 2 files changed, 166 insertions(+), 42 deletions(-) diff --git a/common/js/ai-service.js b/common/js/ai-service.js index 2a48d26..7b47481 100644 --- a/common/js/ai-service.js +++ b/common/js/ai-service.js @@ -1,7 +1,18 @@ import Config from './config.js' import http from './http.js' import store from '@/store/index.js' +let currentConversationId = null; +const CONVERSATION_KEY = 'ai_conversation_id'; +// 初始化时从本地读取 +try { + const saved = uni.getStorageSync(CONVERSATION_KEY); + if (saved) { + currentConversationId = saved; + } +} catch (e) { + console.warn('读取会话ID失败:', e); +} export default { /** * 发送消息到Dify API @@ -20,7 +31,8 @@ export default { inputs: {}, query: message, response_mode: options.stream ? 'streaming' : 'blocking', - user: store.state.memberInfo?.id || 'anonymous' + user: store.state.memberInfo?.id || 'anonymous', + conversation_id: this.getConversationId() || '' }, header: { 'Content-Type': 'application/json' @@ -33,12 +45,17 @@ export default { ...params, async: false }) - return this.handleResponse(response, options) - } catch (error) { - console.error('Dify API请求失败:', error) - throw new Error('AI服务暂时不可用,请稍后重试') - } - }, + + const result = this.handleResponse(response, options); + if (result.conversationId) { + this.setConversationId(result.conversationId); + } + return result; + } catch (error) { + console.error('Dify API请求失败:', error) + throw new Error('AI服务暂时不可用,请稍后重试') + } + }, /** * 流式消息处理 @@ -296,8 +313,9 @@ export default { } }); } - if (onComplete) onComplete(content) - return content + + if (onComplete) onComplete({ content, conversation_id: conversationId }); + return { content, conversation_id: conversationId }; } catch (error) { console.error('HTTP流式请求失败:', error) throw error @@ -403,6 +421,30 @@ export default { return false } }, + getConversationId() { + return currentConversationId; + }, + + setConversationId(id) { + if (id && id !== currentConversationId) { + currentConversationId = id; + try { + uni.setStorageSync(CONVERSATION_KEY, id); + } catch (e) { + console.error('保存会话ID失败:', e); + } + } + }, + + clearConversationId() { + currentConversationId = null; + try { + uni.removeStorageSync(CONVERSATION_KEY); + } catch (e) { + console.error('清除会话ID失败:', e); + } + }, + /** * 获取会话历史 */ diff --git a/components/ai-chat-message/ai-chat-message.vue b/components/ai-chat-message/ai-chat-message.vue index e1e5895..406798c 100644 --- a/components/ai-chat-message/ai-chat-message.vue +++ b/components/ai-chat-message/ai-chat-message.vue @@ -436,9 +436,24 @@ export default { // Dify API相关 currentConversationId: null, isAIServiceAvailable: true, - aiServiceError: null + aiServiceError: null, + isLoadingHistory: false, // 新增:标记历史加载状态 + } }, + onShow() { + // 优先读取本地缓存的会话 ID + const localConvId = this.getConversationIdFromLocal(); + if (localConvId) { + this.currentConversationId = localConvId; + aiService.setConversationId(localConvId); + } else { + this.currentConversationId = aiService.getConversationId(); + } + this.loadChatHistoryIfExist(); + + + }, created() { this.messages = [...this.initialMessages] this.messageId = this.messages.length @@ -447,6 +462,7 @@ export default { this.initUserAvatarData() // 初始化用户昵称(缓存优先) this.initUserNicknameData() + this.currentConversationId = aiService.getConversationId(); }, mounted() { this.scrollToBottom() @@ -462,6 +478,18 @@ export default { } }, methods: { + // 【新增:会话 ID 本地缓存方法】 + saveConversationIdToLocal(convId) { + if (convId) { + uni.setStorageSync('dify_conversation_id', convId); + } + }, + getConversationIdFromLocal() { + return uni.getStorageSync('dify_conversation_id') || null; + }, + clearConversationIdFromLocal() { + uni.removeStorageSync('dify_conversation_id'); + }, // 初始化音频上下文 initAudioContext() { // #ifdef H5 @@ -490,7 +518,39 @@ export default { this.localUserAvatar = this.defaultAvatar } }, + // 👇 新增:加载历史记录 + async loadChatHistoryIfExist() { + const convId = aiService.getConversationId(); + if (convId) { + try { + const history = await aiService.getConversationHistory({ + conversation_id: convId, + uniacid: this.$store.state.uniacid, + user_id: this.$store.state.memberInfo?.id || 'anonymous' + }); + if (history.success && history.messages?.length > 0) { + // 格式化消息 + this.messages = history.messages.map(msg => ({ + id: msg.message_id || Date.now() + Math.random(), + role: msg.role === 'user' ? 'user' : 'assistant', + content: msg.content || msg.answer || msg.text || '', + timestamp: msg.created_at, + actions: msg.role !== 'user' ? [ + { id: 1, text: '有帮助', type: 'like' }, + { id: 2, text: '没帮助', type: 'dislike' } + ] : [] + })); + } + } catch (error) { + console.error('加载历史记录失败:', error); + // 可选:清除无效ID + aiService.clearConversationId(); + this.clearConversationIdFromLocal(); + this.currentConversationId = null; + } + } + }, // 新增:初始化用户昵称(支持缓存持久化) initUserNicknameData() { // 1. 优先读取本地缓存的昵称 @@ -697,7 +757,9 @@ export default { // 更新会话ID if (response.conversationId) { - this.currentConversationId = response.conversationId + this.currentConversationId = response.conversationId; + aiService.setConversationId(response.conversationId); + this.saveConversationIdToLocal(response.conversationId); } const aiMessage = { @@ -734,32 +796,49 @@ export default { this.messages = this.messages.filter(msg => msg.type !== 'loading') this.messages.push(streamMessage) - // 开始流式响应 - await aiService.sendStreamMessage( - userMessage, - // 流式数据回调 - (chunk) => { - streamMessage.content += chunk - // 触发内容更新 - this.$forceUpdate() - }, - // 完成回调 - (completeContent) => { - streamMessage.isStreaming = false - streamMessage.content = completeContent - - // 添加操作按钮 - streamMessage.actions = [ - { id: 1, text: '有帮助', type: 'like' }, - { id: 2, text: '没帮助', type: 'dislike' } - ] - - this.$emit('ai-response', streamMessage) - } - ) - }, - - // 生成AI回复(模拟) + // 开始流式响应 + await aiService.sendStreamMessage( + userMessage, + // 流式数据回调 + (chunk) => { + streamMessage.content += chunk + this.$forceUpdate() // 或 this.$nextTick() + }, + // 完成回调:处理对象或字符串 + (completeResult) => { + let finalContent = ''; + let convId = ''; + + // 判断是对象还是字符串 + if (typeof completeResult === 'string') { + finalContent = completeResult; + } else { + finalContent = completeResult.content || ''; + convId = completeResult.conversation_id || ''; // 👈 关键:提取 conversation_id + } + + // 更新消息状态 + streamMessage.isStreaming = false; + streamMessage.content = finalContent; + + // 添加操作按钮 + streamMessage.actions = [ + { id: 1, text: '有帮助', type: 'like' }, + { id: 2, text: '没帮助', type: 'dislike' } + ]; + + // 保存 conversation_id 到本地 + if (convId) { + aiService.setConversationId(convId); + } + + // 触发事件 + this.$emit('ai-response', streamMessage); + this.saveConversationIdToLocal(convId); + this.currentConversationId = convId; + } + ); + }, generateAIResponse(userMessage) { const responses = { '你好': '您好!我是AI智能客服,很高兴为您服务!有什么可以帮助您的吗?', @@ -767,16 +846,15 @@ export default { '发货': '一般情况下,订单会在24小时内发货,具体时效请查看物流信息。', '退货': '支持7天无理由退货,请确保商品完好无损。', '客服': '我们的客服工作时间是9:00-18:00,有问题可以随时联系我们。' - } - + }; for (let key in responses) { if (userMessage.includes(key)) { - return responses[key] + return responses[key]; } } - - return `感谢您的咨询!关于"${userMessage}"的问题,我们的专业客服会尽快为您解答。您也可以查看我们的帮助文档获取更多信息。` + return `感谢您的咨询!关于"${userMessage}"的问题,我们的专业客服会尽快为您解答。您也可以查看我们的帮助文档获取更多信息。`; }, + // 解析Markdown parseMarkdown(content) { @@ -838,6 +916,10 @@ export default { // 加载更多历史消息 async loadMoreHistory() { + if (!this.currentConversationId) { + this.currentConversationId = this.getConversationIdFromLocal(); + aiService.setConversationId(this.currentConversationId); + } if (!this.showLoadMore || !this.currentConversationId || this.isLoadingHistory) { return }