chore:可以看到之前历史对话了,但是获取时会晃动不完整

This commit is contained in:
2025-12-13 16:19:29 +08:00
parent a06ee95482
commit 80428e625f
2 changed files with 166 additions and 42 deletions

View File

@@ -1,7 +1,18 @@
import Config from './config.js' import Config from './config.js'
import http from './http.js' import http from './http.js'
import store from '@/store/index.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 { export default {
/** /**
* 发送消息到Dify API * 发送消息到Dify API
@@ -20,7 +31,8 @@ export default {
inputs: {}, inputs: {},
query: message, query: message,
response_mode: options.stream ? 'streaming' : 'blocking', response_mode: options.stream ? 'streaming' : 'blocking',
user: store.state.memberInfo?.id || 'anonymous' user: store.state.memberInfo?.id || 'anonymous',
conversation_id: this.getConversationId() || ''
}, },
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
@@ -33,12 +45,17 @@ export default {
...params, ...params,
async: false async: false
}) })
return this.handleResponse(response, options)
} catch (error) { const result = this.handleResponse(response, options);
console.error('Dify API请求失败:', error) if (result.conversationId) {
throw new Error('AI服务暂时不可用请稍后重试') 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) { } catch (error) {
console.error('HTTP流式请求失败:', error) console.error('HTTP流式请求失败:', error)
throw error throw error
@@ -403,6 +421,30 @@ export default {
return false 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);
}
},
/** /**
* 获取会话历史 * 获取会话历史
*/ */

View File

@@ -436,9 +436,24 @@ export default {
// Dify API相关 // Dify API相关
currentConversationId: null, currentConversationId: null,
isAIServiceAvailable: true, 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() { created() {
this.messages = [...this.initialMessages] this.messages = [...this.initialMessages]
this.messageId = this.messages.length this.messageId = this.messages.length
@@ -447,6 +462,7 @@ export default {
this.initUserAvatarData() this.initUserAvatarData()
// 初始化用户昵称(缓存优先) // 初始化用户昵称(缓存优先)
this.initUserNicknameData() this.initUserNicknameData()
this.currentConversationId = aiService.getConversationId();
}, },
mounted() { mounted() {
this.scrollToBottom() this.scrollToBottom()
@@ -462,6 +478,18 @@ export default {
} }
}, },
methods: { 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() { initAudioContext() {
// #ifdef H5 // #ifdef H5
@@ -490,7 +518,39 @@ export default {
this.localUserAvatar = this.defaultAvatar 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() { initUserNicknameData() {
// 1. 优先读取本地缓存的昵称 // 1. 优先读取本地缓存的昵称
@@ -697,7 +757,9 @@ export default {
// 更新会话ID // 更新会话ID
if (response.conversationId) { if (response.conversationId) {
this.currentConversationId = response.conversationId this.currentConversationId = response.conversationId;
aiService.setConversationId(response.conversationId);
this.saveConversationIdToLocal(response.conversationId);
} }
const aiMessage = { const aiMessage = {
@@ -734,32 +796,49 @@ export default {
this.messages = this.messages.filter(msg => msg.type !== 'loading') this.messages = this.messages.filter(msg => msg.type !== 'loading')
this.messages.push(streamMessage) this.messages.push(streamMessage)
// 开始流式响应 // 开始流式响应
await aiService.sendStreamMessage( await aiService.sendStreamMessage(
userMessage, userMessage,
// 流式数据回调 // 流式数据回调
(chunk) => { (chunk) => {
streamMessage.content += chunk streamMessage.content += chunk
// 触发内容更新 this.$forceUpdate() // 或 this.$nextTick()
this.$forceUpdate() },
}, // 完成回调:处理对象或字符串
// 完成回调 (completeResult) => {
(completeContent) => { let finalContent = '';
streamMessage.isStreaming = false let convId = '';
streamMessage.content = completeContent
// 判断是对象还是字符串
// 添加操作按钮 if (typeof completeResult === 'string') {
streamMessage.actions = [ finalContent = completeResult;
{ id: 1, text: '有帮助', type: 'like' }, } else {
{ id: 2, text: '没帮助', type: 'dislike' } finalContent = completeResult.content || '';
] convId = completeResult.conversation_id || ''; // 👈 关键:提取 conversation_id
}
this.$emit('ai-response', streamMessage)
} // 更新消息状态
) streamMessage.isStreaming = false;
}, streamMessage.content = finalContent;
// 生成AI回复模拟 // 添加操作按钮
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) { generateAIResponse(userMessage) {
const responses = { const responses = {
'你好': '您好我是AI智能客服很高兴为您服务有什么可以帮助您的吗', '你好': '您好我是AI智能客服很高兴为您服务有什么可以帮助您的吗',
@@ -767,16 +846,15 @@ export default {
'发货': '一般情况下订单会在24小时内发货具体时效请查看物流信息。', '发货': '一般情况下订单会在24小时内发货具体时效请查看物流信息。',
'退货': '支持7天无理由退货请确保商品完好无损。', '退货': '支持7天无理由退货请确保商品完好无损。',
'客服': '我们的客服工作时间是9:00-18:00有问题可以随时联系我们。' '客服': '我们的客服工作时间是9:00-18:00有问题可以随时联系我们。'
} };
for (let key in responses) { for (let key in responses) {
if (userMessage.includes(key)) { if (userMessage.includes(key)) {
return responses[key] return responses[key];
} }
} }
return `感谢您的咨询!关于"${userMessage}"的问题,我们的专业客服会尽快为您解答。您也可以查看我们的帮助文档获取更多信息。`;
return `感谢您的咨询!关于"${userMessage}"的问题,我们的专业客服会尽快为您解答。您也可以查看我们的帮助文档获取更多信息。`
}, },
// 解析Markdown // 解析Markdown
parseMarkdown(content) { parseMarkdown(content) {
@@ -838,6 +916,10 @@ export default {
// 加载更多历史消息 // 加载更多历史消息
async loadMoreHistory() { async loadMoreHistory() {
if (!this.currentConversationId) {
this.currentConversationId = this.getConversationIdFromLocal();
aiService.setConversationId(this.currentConversationId);
}
if (!this.showLoadMore || !this.currentConversationId || this.isLoadingHistory) { if (!this.showLoadMore || !this.currentConversationId || this.isLoadingHistory) {
return return
} }