ZdyRag.api.ts
2.2 KB
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
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useUserStore } from '/@/store/modules/user'; // 引入用户store获取token
const { createMessage } = useMessage();
enum Api {
send = '/airag/zdyRag/send',
buttonList = '/airagbutton/airagButton/buttonList',
}
/**
* 发送消息(流式处理)
* @param params
*/
export const sendMessage = async (params: { questionText: string }) => {
try {
const userStore = useUserStore();
const token = userStore.getToken;
const response = await fetch(
`/jeecgboot/airag/zdyRag/sendStream?questionText=${encodeURIComponent(params.questionText)}`,
{
method: 'GET',
headers: {
'x-access-token': token,
'Accept': 'text/event-stream'
},
credentials: 'include',
}
);
if (!response.ok || !response.body) {
throw new Error(`请求失败: ${response.status} ${response.statusText}`);
}
// 返回异步生成器函数
return (async function* () {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data:')) {
try {
const jsonStr = line.substring(5).trim();
if (jsonStr) {
yield JSON.parse(jsonStr); // 直接 yield 解析后的数据
}
} catch (e) {
console.error('JSON解析错误:', e);
}
}
}
}
} finally {
reader.releaseLock();
}
})();
} catch (error) {
console.error('Error sending message:', error);
createMessage.error('发送消息失败');
throw error; // 抛出错误让调用方处理
}
};
export const getButtonList = async () => {
const res = await defHttp.get({
url: Api.buttonList,
});
if (res) {
return res;
}
return null;
}