Files
sionrui/frontend/app/web-gold/src/api/chat.js
2025-11-10 00:59:40 +08:00

75 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
})
},
}