前端
This commit is contained in:
74
frontend/app/web-gold/src/api/chat.js
Normal file
74
frontend/app/web-gold/src/api/chat.js
Normal file
@@ -0,0 +1,74 @@
|
||||
import request from '@/api/http'
|
||||
import { fetchEventSource } from '@microsoft/fetch-event-source'
|
||||
import { getAccessToken } from '@/utils/auth'
|
||||
const SERVER_BASE_AI= import.meta.env.VITE_BASE_URL + '/admin-api/ai'
|
||||
|
||||
|
||||
|
||||
// AI chat 聊天
|
||||
export const ChatMessageApi = {
|
||||
// 创建【我的】聊天对话
|
||||
createChatConversationMy: async (data) => {
|
||||
return await request.post(`${SERVER_BASE_AI}/chat/conversation/create-my`, data)
|
||||
},
|
||||
|
||||
|
||||
|
||||
// 发送 Stream 消息(对象入参,便于维护)
|
||||
// 为什么不用 axios 呢?因为它不支持 SSE 调用
|
||||
sendChatMessageStream: async (options) => {
|
||||
const {
|
||||
conversationId,
|
||||
content,
|
||||
ctrl,
|
||||
enableContext = true,
|
||||
enableWebSearch = false,
|
||||
onMessage,
|
||||
onError,
|
||||
onClose,
|
||||
attachmentUrls = []
|
||||
} = options || {}
|
||||
const token = getAccessToken()
|
||||
|
||||
let retryCount = 0
|
||||
const maxRetries = 0 // 禁用自动重试
|
||||
|
||||
return fetchEventSource(`${SERVER_BASE_AI}/chat/message/send-stream`, {
|
||||
method: 'post',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
openWhenHidden: true,
|
||||
body: JSON.stringify({
|
||||
conversationId,
|
||||
content,
|
||||
useContext: enableContext,
|
||||
useSearch: enableWebSearch,
|
||||
attachmentUrls: attachmentUrls || []
|
||||
}),
|
||||
onmessage: onMessage,
|
||||
onerror: (err) => {
|
||||
retryCount++
|
||||
console.error('SSE错误,重试次数:', retryCount, err)
|
||||
|
||||
// 调用自定义错误处理
|
||||
if (typeof onError === 'function') {
|
||||
onError(err)
|
||||
}
|
||||
|
||||
// 超过最大重试次数,停止重连
|
||||
if (retryCount > maxRetries) {
|
||||
throw err // 抛出错误,停止自动重连
|
||||
}
|
||||
},
|
||||
onclose: () => {
|
||||
// 调用自定义关闭处理
|
||||
if (typeof onClose === 'function') {
|
||||
onClose()
|
||||
}
|
||||
},
|
||||
signal: ctrl ? ctrl.signal : undefined
|
||||
})
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user