yt-chat-components 2.0.6 → 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,285 +1,308 @@
1
- // @ts-nocheck
2
- import axios from "axios";
3
- import {InputValueType} from "../types/chatWidget";
4
-
5
-
6
- /**
7
- * 发送消息
8
- * @param input_value_type
9
- * @param isStream
10
- * @param embed_app_extend 扩展参数 * @param isStream 是否启用流式传输
11
- * @param handleMessageContent 处理消息内容的回调函数
12
- * @param signal 用于主动关闭请求流
13
- * @param baseUrl 接口地址
14
- * @param flowId AI应用ID
15
- * @param message 消息内容
16
- * @param input_type 输入类型
17
- * @param output_type 输出类型
18
- * @param sessionId 对话ID
19
- * @param output_component
20
- * @param tweaks
21
- * @param api_key 接口密钥
22
- * @param additional_headers
23
- */
24
- export async function sendMessage(
25
- input_value_type: string = InputValueType.text,
26
- embed_app_extend: object,
27
- isStream: boolean,
28
- handleMessageContent: Function,
29
- signal,
30
- baseUrl: string,
31
- flowId: string,
32
- message: string,
33
- input_type: string,
34
- output_type: string,
35
- sessionId: React.MutableRefObject<string>,
36
- output_component?: string,
37
- tweaks?: Object,
38
- api_key?: string,
39
- additional_headers?: {
40
- [key: string]: string;
41
- },
42
- ) {
43
- let data: any;
44
- data = {input_value_type, input_type, input_value: message, output_type};
45
- if (tweaks) {
46
- data['tweaks'] = tweaks;
47
- }
48
- if (output_component) {
49
- data['output_component'] = output_component;
50
- }
51
- if (embed_app_extend) {
52
- data['embed_app_extend'] = embed_app_extend;
53
- }
54
- let headers: { [key: string]: string } = {'Content-Type': 'application/json', 'timeout': 600000};
55
- if (api_key) {
56
- headers['x-api-key'] = api_key;
57
- }
58
- if (additional_headers) {
59
- headers = Object.assign(headers, additional_headers);
60
- // headers = {...headers, ...additional_headers};
61
- }
62
- // @ts-ignore
63
- if (sessionId && sessionId != '') {
64
- data.session_id = sessionId;
65
- }
66
-
67
- if (isStream) {
68
- return await fetchCustomStream(
69
- `${baseUrl}/api/v1/run/${flowId}?stream=true`,
70
- data,
71
- headers,
72
- handleMessageContent,
73
- signal,
74
- );
75
- } else {
76
- let response = axios.post(`${baseUrl}/api/v1/run/${flowId}`, data, { headers });
77
- return response;
78
- }
79
- }
80
-
81
- // 缓冲区用于累积未完成的 JSON 数据
82
- // let buffer = '';
83
-
84
- const fetchCustomStream = async (url, body, headers, handleMessageContent, signal) => {
85
- const response = await fetch(url, {
86
- method: 'POST',
87
- headers: {...headers, timeout: 600000},
88
- body: JSON.stringify(body),
89
- signal: signal,
90
- });
91
-
92
- if (!response.ok) {
93
- throw new Error('请求失败');
94
- }
95
-
96
- // 手动读取响应体作为可读流
97
- const reader = response.body.getReader();
98
- const decoder = new TextDecoder();
99
- let buffer = '';
100
-
101
- while (true) {
102
- const {done, value} = await reader.read();
103
- if (done) break;
104
-
105
- // 将二进制数据解码为字符串,并累积到缓冲区
106
- const chunk = decoder.decode(value, {stream: true});
107
- buffer += chunk;
108
-
109
- // 提取并解析 JSON
110
- const {parsedData, remainingBuffer} = extractAndParseJSON(buffer, handleMessageContent);
111
-
112
- // 更新缓冲区为剩余未处理的数据
113
- buffer = remainingBuffer;
114
- }
115
-
116
- // 如果缓冲区中还有剩余数据,可能是不完整的 JSON
117
- if (buffer.trim() !== '') {
118
- console.warn('缓冲区中存在未完成的 JSON 数据:', buffer);
119
- }
120
- }
121
-
122
- // 辅助函数:从缓冲区中提取并解析所有完整的 JSON 对象
123
- const extractAndParseJSON = (buffer, handleMessageContent) => {
124
- let remainingBuffer = buffer; // 剩余未处理的数据
125
- const parsedData = []; // 存储解析成功的 JSON 对象
126
- let bracketCount = 0; // 记录大括号的嵌套层次
127
- let jsonStartIndex = -1; // 当前 JSON 对象的起始索引
128
- let inString = false; // 是否处于字符串内部
129
- let escapeChar = false; // 是否遇到转义字符
130
-
131
- for (let i = 0; i < remainingBuffer.length; i++) {
132
- const char = remainingBuffer[i];
133
-
134
- if (escapeChar) {
135
- escapeChar = false; // 跳过转义字符后的下一个字符
136
- continue;
137
- }
138
-
139
- if (char === '\\') {
140
- escapeChar = true; // 标记转义字符
141
- continue;
142
- }
143
-
144
- if (char === '"' && !escapeChar) {
145
- inString = !inString; // 切换字符串状态
146
- continue;
147
- }
148
-
149
- if (!inString) {
150
- if (char === '{') {
151
- if (bracketCount === 0) {
152
- jsonStartIndex = i; // 标记 JSON 开始位置
153
- }
154
- bracketCount++;
155
- } else if (char === '}') {
156
- bracketCount--;
157
- if (bracketCount === 0 && jsonStartIndex !== -1) {
158
- // 找到一个完整的 JSON 对象
159
- const jsonString = remainingBuffer.slice(jsonStartIndex, i + 1);
160
-
161
- try {
162
- const parsedJson = JSON.parse(jsonString); // 解析 JSON
163
- handleMessageContent(parsedJson['event'], parsedJson['data']);
164
- parsedData.push(parsedJson); // 添加到解析结果中
165
- } catch (error) {
166
- console.warn('无法解析 JSON 数据:', error, jsonString);
167
- }
168
-
169
- // 更新剩余缓冲区的起始位置
170
- remainingBuffer = remainingBuffer.slice(i + 1);
171
- i = -1; // 重置索引以重新开始扫描
172
- jsonStartIndex = -1; // 重置 JSON 起始索引
173
- }
174
- }
175
- }
176
- }
177
-
178
- return {parsedData, remainingBuffer}; // 返回解析结果和剩余缓冲区
179
- }
180
-
181
- /**
182
- * 获取对话历史列表
183
- * @param baseUrl
184
- * @param flowId
185
- * @param operatorId
186
- */
187
- export async function getHistoryList(baseUrl: string, flowId: string, operatorId: string) {
188
- return axios.get(`${baseUrl}/api/v1/embed/chat_history_list/${flowId}/${operatorId}`, {timeout: 600000});
189
- }
190
-
191
- /**
192
- * 获取对话历史记录
193
- * @param baseUrl
194
- * @param flowI
195
- * @param sessionId
196
- * @param operatorId
197
- */
198
- export const getChatHistory = (
199
- baseUrl: string,
200
- flowId: string,
201
- sessionId: string,
202
- operatorId: string,
203
- ) => {
204
- return axios.get(`${baseUrl}/api/v1/embed/chat_history/${flowId}/${sessionId}/${operatorId}`);
205
- }
206
-
207
-
208
- /**
209
- * 上传文件
210
- * @param baseUrl
211
- * @param file
212
- * @param flowId
213
- * @param api_key
214
- */
215
- export async function fetchUploadFile(baseUrl: string, file: File, flowId: string, api_key: string, sessionId: string) {
216
- const headers = {
217
- 'Content-Type': 'multipart/form-data',
218
- 'x-api-key': api_key,
219
- timeout:600000
220
- };
221
- const formData = new FormData();
222
- formData.append('file', file);
223
- formData.append('folder', flowId);
224
- formData.append('session_id', sessionId);
225
-
226
- return axios.post(`${baseUrl}/api/t1/file/upload`, formData, {headers});
227
- }
228
-
229
- /**
230
- * 删除文件
231
- * @param baseUrl
232
- * @param fileUrl
233
- * @param flowId
234
- * @param api_key
235
- */
236
- export async function fetchDeleteFile(baseUrl: string, file_url: string, flowId: string, api_key: string, sessionId: string) {
237
- const headers = {
238
- 'Content-Type': 'multipart/form-data',
239
- 'x-api-key': api_key,
240
- timeout: 600000
241
- };
242
- return axios.get(`${baseUrl}/api/t1/file/delete_file?session_id=${sessionId}&file_url=${file_url}`, {headers});
243
- }
244
-
245
- /**
246
- * 获取场景信息
247
- * @param baseUrl
248
- * @param sceneId
249
- * @param api_key
250
- */
251
- export async function getSceneInfo(baseUrl: string, sceneId: string, api_key: string) {
252
- const headers = {
253
- 'Content-Type': 'multipart/form-data',
254
- 'x-api-key': api_key,
255
- timeout:600000
256
- };
257
- return axios.get(`${baseUrl}/api/t1/scene/detail/${sceneId}`,{headers});
258
- }
259
-
260
- export async function getFlowInfo(baseUrl: string, flowId: string, api_key: string) {
261
- const headers = {
262
- 'Content-Type': 'multipart/form-data',
263
- 'x-api-key': api_key,
264
- timeout:600000
265
- };
266
- return axios.get(`${baseUrl}/api/t1/flow/detail/${flowId}`,{headers});
267
- }
268
-
269
- export async function getQaInfo(baseUrl: string, flowId: string, api_key: string) {
270
- const headers = {
271
- 'Content-Type': 'multipart/form-data',
272
- 'x-api-key': api_key,
273
- timeout:600000
274
- };
275
- return axios.get(`${baseUrl}/api/t1/qa_doc/find_doc_by_flow_id/${flowId}`,{headers});
276
- }
277
-
278
- export async function getAsrToken(baseUrl: string, flowId: string) {
279
- const headers = {
280
- 'Content-Type': 'multipart/form-data',
281
- // 'x-api-key': api_key,
282
- timeout:10000
283
- };
284
- return axios.get(`${baseUrl}/api/v1/token/${flowId}`,{headers});
1
+ // @ts-nocheck
2
+ import axios from "axios";
3
+ import {InputValueType} from "../types/chatWidget";
4
+
5
+
6
+ /**
7
+ * 发送消息
8
+ * @param input_value_type
9
+ * @param isStream
10
+ * @param embed_app_extend 扩展参数 * @param isStream 是否启用流式传输
11
+ * @param handleMessageContent 处理消息内容的回调函数
12
+ * @param signal 用于主动关闭请求流
13
+ * @param baseUrl 接口地址
14
+ * @param flowId AI应用ID
15
+ * @param message 消息内容
16
+ * @param input_type 输入类型
17
+ * @param output_type 输出类型
18
+ * @param sessionId 对话ID
19
+ * @param output_component
20
+ * @param tweaks
21
+ * @param api_key 接口密钥
22
+ * @param additional_headers
23
+ */
24
+ export async function sendMessage(
25
+ input_value_type: string = InputValueType.text,
26
+ embed_app_extend: object,
27
+ isStream: boolean,
28
+ handleMessageContent: Function,
29
+ signal,
30
+ baseUrl: string,
31
+ flowId: string,
32
+ message: string,
33
+ input_type: string,
34
+ output_type: string,
35
+ sessionId: React.MutableRefObject<string>,
36
+ output_component?: string,
37
+ tweaks?: Object,
38
+ api_key?: string,
39
+ additional_headers?: {
40
+ [key: string]: string;
41
+ },
42
+ ) {
43
+ let data: any;
44
+ data = {input_value_type, input_type, input_value: message, output_type};
45
+ if (tweaks) {
46
+ data['tweaks'] = tweaks;
47
+ }
48
+ if (output_component) {
49
+ data['output_component'] = output_component;
50
+ }
51
+ if (embed_app_extend) {
52
+ data['embed_app_extend'] = embed_app_extend;
53
+ }
54
+ let headers: { [key: string]: string } = {'Content-Type': 'application/json', 'timeout': 600000};
55
+ if (api_key) {
56
+ headers['x-api-key'] = api_key;
57
+ }
58
+ if (additional_headers) {
59
+ headers = Object.assign(headers, additional_headers);
60
+ // headers = {...headers, ...additional_headers};
61
+ }
62
+ // @ts-ignore
63
+ if (sessionId && sessionId != '') {
64
+ data.session_id = sessionId;
65
+ }
66
+
67
+ if (isStream) {
68
+ return await fetchCustomStream(
69
+ `${baseUrl}/api/v1/run/${flowId}?stream=true`,
70
+ data,
71
+ headers,
72
+ handleMessageContent,
73
+ signal,
74
+ );
75
+ } else {
76
+ let response = axios.post(`${baseUrl}/api/v1/run/${flowId}`, data, { headers });
77
+ return response;
78
+ }
79
+ }
80
+
81
+ // 缓冲区用于累积未完成的 JSON 数据
82
+ // let buffer = '';
83
+
84
+ const fetchCustomStream = async (url, body, headers, handleMessageContent, signal) => {
85
+ const response = await fetch(url, {
86
+ method: 'POST',
87
+ headers: {...headers, timeout: 600000},
88
+ body: JSON.stringify(body),
89
+ signal: signal,
90
+ });
91
+
92
+ if (!response.ok) {
93
+ throw new Error('请求失败');
94
+ }
95
+
96
+ // 手动读取响应体作为可读流
97
+ const reader = response.body.getReader();
98
+ const decoder = new TextDecoder();
99
+ let buffer = '';
100
+
101
+ while (true) {
102
+ const {done, value} = await reader.read();
103
+ if (done) break;
104
+
105
+ // 将二进制数据解码为字符串,并累积到缓冲区
106
+ const chunk = decoder.decode(value, {stream: true});
107
+ buffer += chunk;
108
+
109
+ // 提取并解析 JSON
110
+ const {parsedData, remainingBuffer} = extractAndParseJSON(buffer, handleMessageContent);
111
+
112
+ // 更新缓冲区为剩余未处理的数据
113
+ buffer = remainingBuffer;
114
+ }
115
+
116
+ // 如果缓冲区中还有剩余数据,可能是不完整的 JSON
117
+ if (buffer.trim() !== '') {
118
+ console.warn('缓冲区中存在未完成的 JSON 数据:', buffer);
119
+ }
120
+ }
121
+
122
+ // 辅助函数:从缓冲区中提取并解析所有完整的 JSON 对象
123
+ const extractAndParseJSON = (buffer, handleMessageContent) => {
124
+ let remainingBuffer = buffer; // 剩余未处理的数据
125
+ const parsedData = []; // 存储解析成功的 JSON 对象
126
+ let bracketCount = 0; // 记录大括号的嵌套层次
127
+ let jsonStartIndex = -1; // 当前 JSON 对象的起始索引
128
+ let inString = false; // 是否处于字符串内部
129
+ let escapeChar = false; // 是否遇到转义字符
130
+
131
+ for (let i = 0; i < remainingBuffer.length; i++) {
132
+ const char = remainingBuffer[i];
133
+
134
+ if (escapeChar) {
135
+ escapeChar = false; // 跳过转义字符后的下一个字符
136
+ continue;
137
+ }
138
+
139
+ if (char === '\\') {
140
+ escapeChar = true; // 标记转义字符
141
+ continue;
142
+ }
143
+
144
+ if (char === '"' && !escapeChar) {
145
+ inString = !inString; // 切换字符串状态
146
+ continue;
147
+ }
148
+
149
+ if (!inString) {
150
+ if (char === '{') {
151
+ if (bracketCount === 0) {
152
+ jsonStartIndex = i; // 标记 JSON 开始位置
153
+ }
154
+ bracketCount++;
155
+ } else if (char === '}') {
156
+ bracketCount--;
157
+ if (bracketCount === 0 && jsonStartIndex !== -1) {
158
+ // 找到一个完整的 JSON 对象
159
+ const jsonString = remainingBuffer.slice(jsonStartIndex, i + 1);
160
+
161
+ try {
162
+ const parsedJson = JSON.parse(jsonString); // 解析 JSON
163
+ handleMessageContent(parsedJson['event'], parsedJson['data']);
164
+ parsedData.push(parsedJson); // 添加到解析结果中
165
+ } catch (error) {
166
+ console.warn('无法解析 JSON 数据:', error, jsonString);
167
+ }
168
+
169
+ // 更新剩余缓冲区的起始位置
170
+ remainingBuffer = remainingBuffer.slice(i + 1);
171
+ i = -1; // 重置索引以重新开始扫描
172
+ jsonStartIndex = -1; // 重置 JSON 起始索引
173
+ }
174
+ }
175
+ }
176
+ }
177
+
178
+ return {parsedData, remainingBuffer}; // 返回解析结果和剩余缓冲区
179
+ }
180
+
181
+ /**
182
+ * 获取对话历史列表
183
+ * @param baseUrl
184
+ * @param flowId
185
+ * @param operatorId
186
+ */
187
+ export async function getHistoryList(baseUrl: string, flowId: string, operatorId: string) {
188
+ return axios.get(`${baseUrl}/api/v1/embed/chat_history_list/${flowId}/${operatorId}`, {timeout: 600000});
189
+ }
190
+
191
+ /**
192
+ * 获取对话历史记录
193
+ * @param baseUrl
194
+ * @param flowI
195
+ * @param sessionId
196
+ * @param operatorId
197
+ */
198
+ export const getChatHistory = (
199
+ baseUrl: string,
200
+ flowId: string,
201
+ sessionId: string,
202
+ operatorId: string,
203
+ ) => {
204
+ return axios.get(`${baseUrl}/api/v1/embed/chat_history/${flowId}/${sessionId}/${operatorId}`);
205
+ }
206
+
207
+
208
+ /**
209
+ * 上传文件
210
+ * @param baseUrl
211
+ * @param file
212
+ * @param flowId
213
+ * @param api_key
214
+ */
215
+ export async function fetchUploadFile(baseUrl: string, file: File, flowId: string, api_key: string, sessionId: string) {
216
+ const headers = {
217
+ 'Content-Type': 'multipart/form-data',
218
+ 'x-api-key': api_key,
219
+ timeout:600000
220
+ };
221
+ const formData = new FormData();
222
+ formData.append('file', file);
223
+ formData.append('folder', flowId);
224
+ formData.append('session_id', sessionId);
225
+
226
+ return axios.post(`${baseUrl}/api/t1/file/upload`, formData, {headers});
227
+ }
228
+
229
+ /**
230
+ * 删除文件
231
+ * @param baseUrl
232
+ * @param fileUrl
233
+ * @param flowId
234
+ * @param api_key
235
+ */
236
+ export async function fetchDeleteFile(baseUrl: string, file_url: string, flowId: string, api_key: string, sessionId: string) {
237
+ const headers = {
238
+ 'Content-Type': 'multipart/form-data',
239
+ 'x-api-key': api_key,
240
+ timeout: 600000
241
+ };
242
+ return axios.get(`${baseUrl}/api/t1/file/delete_file?session_id=${sessionId}&file_url=${file_url}`, {headers});
243
+ }
244
+
245
+ /**
246
+ * 获取场景信息
247
+ * @param baseUrl
248
+ * @param sceneId
249
+ * @param api_key
250
+ */
251
+ export async function getSceneInfo(baseUrl: string, sceneId: string, api_key: string) {
252
+ const headers = {
253
+ 'Content-Type': 'multipart/form-data',
254
+ 'x-api-key': api_key,
255
+ timeout:600000
256
+ };
257
+ return axios.get(`${baseUrl}/api/t1/scene/detail/${sceneId}`,{headers});
258
+ }
259
+
260
+ export async function getFlowInfo(baseUrl: string, flowId: string, api_key: string) {
261
+ const headers = {
262
+ 'Content-Type': 'multipart/form-data',
263
+ 'x-api-key': api_key,
264
+ timeout:600000
265
+ };
266
+ return axios.get(`${baseUrl}/api/t1/flow/detail/${flowId}`,{headers});
267
+ }
268
+
269
+ export async function getQaInfo(baseUrl: string, flowId: string, api_key: string) {
270
+ const headers = {
271
+ 'Content-Type': 'multipart/form-data',
272
+ 'x-api-key': api_key,
273
+ timeout:600000
274
+ };
275
+ return axios.get(`${baseUrl}/api/t1/qa_doc/find_doc_by_flow_id/${flowId}`,{headers});
276
+ }
277
+
278
+ export async function getAsrToken(baseUrl: string, flowId: string) {
279
+ const headers = {
280
+ 'Content-Type': 'multipart/form-data',
281
+ // 'x-api-key': api_key,
282
+ timeout:10000
283
+ };
284
+ return axios.get(`${baseUrl}/api/v1/token/${flowId}`,{headers});
285
+ }
286
+
287
+ export async function getFlowPage(baseUrl: string, api_key: string) {
288
+ const headers = {
289
+ 'Content-Type': 'application/json',
290
+ 'x-api-key': api_key,
291
+ timeout: 600000
292
+ };
293
+ let data = {};
294
+ data['condition'] = [];
295
+ data['page'] = 0;
296
+ data['page_size'] = 999;
297
+ return axios.post(`${baseUrl}/api/t1/flow/page`, JSON.stringify(data), {headers});
298
+ }
299
+
300
+ export async function modifyScene(baseUrl: string, api_key: string, scene) {
301
+ const headers = {
302
+ 'Content-Type': 'application/json',
303
+ 'x-api-key': api_key,
304
+ timeout: 600000
305
+ };
306
+ let data = {...scene};
307
+ return axios.post(`${baseUrl}/api/t1/scene/modify/${scene.id}`, JSON.stringify(data), {headers});
285
308
  }