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 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);
}
},
/**
* 获取会话历史
*/

View File

@@ -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
}