File size: 8,762 Bytes
81d8726 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | import { ref, onUnmounted, computed, watch } from 'vue'
import { AIChatService } from '@/utils/aiChatService'
import { ElMessage } from 'element-plus'
import useStore from '@/store'
import $api from '@/api'
import { randomStr } from '@/utils'
// const titlePrompt = '使用四到五个字直接返回这句话的简要主题,不要解释、不要标点、不要语气词、不要多余文本,不要加粗,如果没有主题,请直接返回"闲聊"'
const defaultChatList = () => {
return [{
id: 1,
content: '您好,我是小助手,有什么可以帮您的吗?',
role: 'assistant',
timestamp: new Date(),
isStreaming: false,
error: false
},]
}
const defaultCurChat = () => {
return {
id: '',
describe: '新对话',
chatList: defaultChatList()
}
}
export function useAIChat() {
const $store = useStore()
const aiService = ref(null)
const curChat = ref(defaultCurChat())
const chatId = computed(() => curChat.value.id)
const chatList = computed(() => curChat.value.chatList)
const aiConfig = computed(() => $store.aiConfig)
const titleGenMedel = computed(() => aiConfig.value.titleGenMedel)
const chatHistory = computed(() => $store.chatHistory)
watch(() => aiConfig.value, (newConfig) => {
if (newConfig && typeof newConfig === 'object') {
const { apiUrl, apiKey } = newConfig
if (apiUrl && apiKey) {
aiService.value = new AIChatService(apiUrl, apiKey)
console.log('aiService created:', apiUrl)
}
}
}, { immediate: true, deep: true })
const isConnecting = ref(false)
const loading = ref(false)
const error = ref(null)
const isReasoning = ref(false)
const sendMessage = async (messageContent, model, options = {}) => {
if (!aiService.value) {
error.value = '请先配置API参数'
ElMessage.error(error.value)
return
}
error.value = null
loading.value = true
isConnecting.value = true
isReasoning.value = false
const userMessage = {
id: Date.now(),
content: messageContent,
role: 'user',
timestamp: new Date()
}
chatList.value.push(userMessage)
const aiMessageId = Date.now() + 1 // 确保AI消息ID与用户消息ID不会重复
const aiMessage = {
id: aiMessageId,
content: '',
reasoning: '',
reasoningTime: 0,
role: 'assistant',
timestamp: new Date(),
isStreaming: true
}
chatList.value.push(aiMessage)
const apiMessages = chatList.value
.slice(1) // 排除第一条消息
.slice(0, -1) // 排除最后一条空的AI消息
.filter(msg => msg.role === 'user' || msg.role === 'assistant')
.map(msg => ({
role: msg.role,
content: msg.content
}))
try {
await aiService.value.startChat(
apiMessages,
model,
options,
{
onOpen: () => {
isConnecting.value = false
},
onMessage: (content) => {
const aiMessage = chatList.value.find(msg => msg.id === aiMessageId)
if (aiMessage) {
aiMessage.content += content
}
},
onReasoning: (reasoning) => {
isReasoning.value = true
const aiMessage = chatList.value.find(msg => msg.id === aiMessageId)
if (aiMessage) {
aiMessage.reasoning += reasoning
}
},
onReasoningComplete: (reasoningTime) => {
isReasoning.value = false
const aiMessage = chatList.value.find(msg => msg.id === aiMessageId)
if (aiMessage) {
aiMessage.reasoningTime = reasoningTime
}
},
onError: (err) => {
error.value = err?.message || err || '连接到 AI 服务时出错'
loading.value = false
const aiMessage = chatList.value.find(msg => msg.id === aiMessageId)
if (aiMessage) {
aiMessage.error = true
aiMessage.isStreaming = false
aiMessage.content = error.value // 将错误信息设置为消息内容
}
}
}
)
loading.value = false
isConnecting.value = false
isReasoning.value = false
const aiMessage = chatList.value.find(msg => msg.id === aiMessageId)
if (aiMessage) {
aiMessage.isStreaming = false
}
saveChat() // 保存对话
} catch (err) {
error.value = err?.message || err || '发送消息时出错'
loading.value = false
isConnecting.value = false
isReasoning.value = false
const aiMessage = chatList.value.find(msg => msg.id === aiMessageId)
if (aiMessage) {
aiMessage.error = true
aiMessage.isStreaming = false
aiMessage.content = error.value // 将错误信息设置为消息内容
}
}
}
const clearChat = async () => {
if (loading.value) return
chatList.value.length = 1
error.value = null
await saveChat() // 保存清空后的状态
ElMessage.success('清除成功')
}
const stopGeneration = () => {
aiService.value?.closeConnection()
loading.value = false
const streamingMessage = chatList.value.find(msg => msg.isStreaming)
if (streamingMessage) {
streamingMessage.isStreaming = false
}
}
const deleteMessage = (messageId) => {
if (loading.value) return
const index = chatList.value.findIndex(msg => msg.id === messageId)
if (index !== -1) {
chatList.value.splice(index, Infinity)
saveChat() // 保存删除后的状态
}
}
const regenerateMessage = async (messageId, model) => {
if (loading.value) return
const index = chatList.value.findIndex(msg => msg.id === messageId)
if (index === -1) return
chatList.value.splice(index + 1, Infinity) // 删除当前消息的后续消息
const lastMessage = chatList.value[index]
const { content, role } = lastMessage
if (role === 'user') {
chatList.value.pop()
await sendMessage(content, model)
} else if (role === 'assistant') {
chatList.value.pop()
const lastUserMessage = chatList.value.pop()
await sendMessage(lastUserMessage.content, model)
}
}
const addChat = async () => {
curChat.value = defaultCurChat()
}
const removeChat = async (id) => {
await $api.removeChatHistory(id)
ElMessage.success('删除成功')
await $store.getChatHistory()
if (chatHistory.value.length > 0) {
changeChat(chatHistory.value[0].id)
} else {
addChat()
}
}
const changeChat = (id) => {
const chatItem = chatHistory.value.find(item => item.id === id)
if (!chatItem) return ElMessage.error('对话id不存在')
curChat.value = chatItem
}
const saveChat = async () => {
if (curChat.value.chatList.length === 3) {
const title = await aiService.value.generateTitle(curChat.value.chatList, titleGenMedel.value)
curChat.value.describe = title
}
const { data } = await $api.saveChatHistory(curChat.value)
if (!data.updateChat) ElMessage.error('对话保存失败')
else {
curChat.value.id = data.updateChat.id
curChat.value.createdAt = data.updateChat.createdAt
curChat.value.updatedAt = data.updateChat.updatedAt
// curChat.value = {
// id: data.updateChat._id,
// ...data.updateChat
// }
}
$store.getChatHistory()
}
const startEditMessage = (messageId) => {
if (loading.value) return
const message = chatList.value.find(msg => msg.id === messageId)
if (message) {
message.isEditing = true
message.editingContent = message.content
}
}
const cancelEditMessage = (messageId) => {
const message = chatList.value.find(msg => msg.id === messageId)
if (message) {
message.isEditing = false
message.editingContent = ''
}
}
const confirmEditMessage = async (messageId, newContent, model) => {
if (loading.value) return
const messageIndex = chatList.value.findIndex(msg => msg.id === messageId)
if (messageIndex === -1) return
const message = chatList.value[messageIndex]
message.content = newContent
message.isEditing = false
message.editingContent = ''
chatList.value.splice(messageIndex)
await sendMessage(newContent, model)
}
onUnmounted(() => {
aiService.value?.closeConnection()
})
return {
chatId,
chatList,
isConnecting,
isReasoning,
loading,
error,
sendMessage,
clearChat,
stopGeneration,
deleteMessage,
regenerateMessage,
changeChat,
removeChat,
addChat,
startEditMessage,
cancelEditMessage,
confirmEditMessage
}
}
|