|
|
@@ -171,29 +171,75 @@ const sendMessage = async () => {
|
|
|
isTyping.value = true
|
|
|
scrollToBottom()
|
|
|
|
|
|
- // 调用 AI 接口获取回复
|
|
|
- const reply = await sendChatMessage(content)
|
|
|
- isTyping.value = false
|
|
|
- messages.value.push({
|
|
|
- role: 'assistant',
|
|
|
- content: reply,
|
|
|
- time: new Date().toLocaleString()
|
|
|
- })
|
|
|
- isSending.value = false
|
|
|
- scrollToBottom()
|
|
|
-}
|
|
|
-
|
|
|
-// AI 对话接口
|
|
|
-const sendChatMessage = async (question: string): Promise<string> => {
|
|
|
+ // 调用 AI 接口获取流式回复
|
|
|
try {
|
|
|
- const res = await http.post<{ reply: string }>('/upms/ai/chat', { question })
|
|
|
- return res.reply
|
|
|
+ await sendChatMessage(content)
|
|
|
} catch (error) {
|
|
|
- console.error('AI 接口调用失败:', error)
|
|
|
- return '抱歉,AI 服务暂时不可用,请稍后再试。'
|
|
|
+ console.error('AI 对话失败:', error)
|
|
|
+ } finally {
|
|
|
+ isTyping.value = false
|
|
|
+ isSending.value = false
|
|
|
+ scrollToBottom()
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+// AI 对话接口 (SSE 流式输出)
|
|
|
+const sendChatMessage = async (question: string): Promise<void> => {
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
+ try {
|
|
|
+ // 先添加一个空的 AI 消息
|
|
|
+ const aiMessageIndex = messages.value.length
|
|
|
+ messages.value.push({
|
|
|
+ role: 'assistant',
|
|
|
+ content: '',
|
|
|
+ time: new Date().toLocaleString()
|
|
|
+ })
|
|
|
+
|
|
|
+ // 创建 SSE 连接
|
|
|
+ const eventSource = new EventSource(`/api/upms/ai/chat?question=${encodeURIComponent(question)}`)
|
|
|
+
|
|
|
+ eventSource.onmessage = (event) => {
|
|
|
+ try {
|
|
|
+ const data = JSON.parse(event.data)
|
|
|
+
|
|
|
+ // 追加内容到 AI 消息
|
|
|
+ if (messages.value[aiMessageIndex]) {
|
|
|
+ messages.value[aiMessageIndex].content += data.content
|
|
|
+ }
|
|
|
+
|
|
|
+ // 滚动到底部
|
|
|
+ scrollToBottom()
|
|
|
+
|
|
|
+ // 如果完成了,关闭连接
|
|
|
+ if (data.done) {
|
|
|
+ eventSource.close()
|
|
|
+ resolve()
|
|
|
+ }
|
|
|
+ } catch (error) {
|
|
|
+ console.error('解析 SSE 数据失败:', error)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ eventSource.onerror = (error) => {
|
|
|
+ console.error('SSE 连接错误:', error)
|
|
|
+ eventSource.close()
|
|
|
+
|
|
|
+ // 如果有内容,则认为是正常结束
|
|
|
+ if (messages.value[aiMessageIndex]?.content) {
|
|
|
+ resolve()
|
|
|
+ } else {
|
|
|
+ // 如果没有内容,显示错误信息
|
|
|
+ messages.value[aiMessageIndex].content = '抱歉,AI 服务暂时不可用,请稍后再试。'
|
|
|
+ reject(error)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (error) {
|
|
|
+ console.error('创建 SSE 连接失败:', error)
|
|
|
+ reject(error)
|
|
|
+ }
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
// 选择快捷问题
|
|
|
const selectQuestion = (question: string) => {
|
|
|
inputMessage.value = question
|