File size: 14,496 Bytes
1a0fce6 8a4bb0c 74ade83 09502ac eedc75d 71b7e06 8a4bb0c 1a0fce6 e08f767 2052ec7 4ea925e 7b030d6 15052fd cb33b9e a432686 8207a08 88e5a61 eedc75d db736e5 9d3ef9c 598945f 71b7e06 88e5a61 d8f8ecb 88e5a61 598945f 88e5a61 74ade83 88e5a61 bd39551 36b496a d8f8ecb 9d3ef9c d8f8ecb 9d3ef9c d8f8ecb 9d3ef9c d8f8ecb 9d3ef9c d8f8ecb 9d3ef9c d8f8ecb 36b496a bd39551 36b496a bd39551 36b496a bd39551 36b496a bd39551 36b496a bd39551 36b496a bd39551 15052fd 1a0fce6 cb33b9e 48b3292 1a0fce6 e68f488 48b3292 e68f488 1a0fce6 09502ac 809dc5c 09502ac cb33b9e 809dc5c cb33b9e 09502ac cb33b9e 3927930 48b3292 3927930 cb33b9e e68f488 18da36c cb33b9e 48b3292 09502ac cb33b9e 48b3292 809dc5c cb33b9e 1a0fce6 48b3292 1a0fce6 e68f488 1a0fce6 8207a08 a7e962d 4ea925e a7e962d 4ea925e 196c662 4ea925e a7e962d 8207a08 8441328 8207a08 8441328 8207a08 8441328 8207a08 8a4bb0c 2052ec7 8a4bb0c 16e3fae a432686 8a4bb0c 2052ec7 8a4bb0c 7d8f5e6 eedc75d 8a4bb0c eedc75d 8a4bb0c eedc75d 8207a08 9ee6e3a b2b0160 598945f b2b0160 7b030d6 de9090d |
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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 |
import { Authorization } from '@/constants/authorization';
import { MessageType } from '@/constants/chat';
import { LanguageTranslationMap } from '@/constants/common';
import { ResponseType } from '@/interfaces/database/base';
import { IAnswer, Message } from '@/interfaces/database/chat';
import { IKnowledgeFile } from '@/interfaces/database/knowledge';
import { IClientConversation, IMessage } from '@/pages/chat/interface';
import api from '@/utils/api';
import { getAuthorization } from '@/utils/authorization-util';
import { buildMessageUuid } from '@/utils/chat';
import { PaginationProps, message } from 'antd';
import { FormInstance } from 'antd/lib';
import axios from 'axios';
import { EventSourceParserStream } from 'eventsource-parser/stream';
import { omit } from 'lodash';
import {
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { v4 as uuid } from 'uuid';
import { useTranslate } from './common-hooks';
import { useSetPaginationParams } from './route-hook';
import { useFetchTenantInfo, useSaveSetting } from './user-setting-hooks';
export const useSetSelectedRecord = <T = IKnowledgeFile>() => {
const [currentRecord, setCurrentRecord] = useState<T>({} as T);
const setRecord = (record: T) => {
setCurrentRecord(record);
};
return { currentRecord, setRecord };
};
export const useHandleSearchChange = () => {
const [searchString, setSearchString] = useState('');
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const value = e.target.value;
setSearchString(value);
},
[],
);
return { handleInputChange, searchString };
};
export const useChangeLanguage = () => {
const { i18n } = useTranslation();
const { saveSetting } = useSaveSetting();
const changeLanguage = (lng: string) => {
i18n.changeLanguage(
LanguageTranslationMap[lng as keyof typeof LanguageTranslationMap],
);
saveSetting({ language: lng });
};
return changeLanguage;
};
export const useGetPaginationWithRouter = () => {
const { t } = useTranslate('common');
const {
setPaginationParams,
page,
size: pageSize,
} = useSetPaginationParams();
const onPageChange: PaginationProps['onChange'] = useCallback(
(pageNumber: number, pageSize: number) => {
setPaginationParams(pageNumber, pageSize);
},
[setPaginationParams],
);
const setCurrentPagination = useCallback(
(pagination: { page: number; pageSize?: number }) => {
setPaginationParams(pagination.page, pagination.pageSize);
},
[setPaginationParams],
);
const pagination: PaginationProps = useMemo(() => {
return {
showQuickJumper: true,
total: 0,
showSizeChanger: true,
current: page,
pageSize: pageSize,
pageSizeOptions: [1, 2, 10, 20, 50, 100],
onChange: onPageChange,
showTotal: (total) => `${t('total')} ${total}`,
};
}, [t, onPageChange, page, pageSize]);
return {
pagination,
setPagination: setCurrentPagination,
};
};
export const useGetPagination = () => {
const [pagination, setPagination] = useState({ page: 1, pageSize: 10 });
const { t } = useTranslate('common');
const onPageChange: PaginationProps['onChange'] = useCallback(
(pageNumber: number, pageSize: number) => {
setPagination({ page: pageNumber, pageSize });
},
[],
);
const currentPagination: PaginationProps = useMemo(() => {
return {
showQuickJumper: true,
total: 0,
showSizeChanger: true,
current: pagination.page,
pageSize: pagination.pageSize,
pageSizeOptions: [1, 2, 10, 20, 50, 100],
onChange: onPageChange,
showTotal: (total) => `${t('total')} ${total}`,
};
}, [t, onPageChange, pagination]);
return {
pagination: currentPagination,
};
};
export interface AppConf {
appName: string;
}
export const useFetchAppConf = () => {
const [appConf, setAppConf] = useState<AppConf>({} as AppConf);
const fetchAppConf = useCallback(async () => {
const ret = await axios.get('/conf.json');
setAppConf(ret.data);
}, []);
useEffect(() => {
fetchAppConf();
}, [fetchAppConf]);
return appConf;
};
export const useSendMessageWithSse = (
url: string = api.completeConversation,
) => {
const [answer, setAnswer] = useState<IAnswer>({} as IAnswer);
const [done, setDone] = useState(true);
const timer = useRef<any>();
const resetAnswer = useCallback(() => {
if (timer.current) {
clearTimeout(timer.current);
}
timer.current = setTimeout(() => {
setAnswer({} as IAnswer);
clearTimeout(timer.current);
}, 1000);
}, []);
const send = useCallback(
async (
body: any,
controller?: AbortController,
): Promise<{ response: Response; data: ResponseType } | undefined> => {
try {
setDone(false);
const response = await fetch(url, {
method: 'POST',
headers: {
[Authorization]: getAuthorization(),
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
signal: controller?.signal,
});
const res = response.clone().json();
const reader = response?.body
?.pipeThrough(new TextDecoderStream())
.pipeThrough(new EventSourceParserStream())
.getReader();
while (true) {
const x = await reader?.read();
if (x) {
const { done, value } = x;
if (done) {
console.info('done');
resetAnswer();
break;
}
try {
const val = JSON.parse(value?.data || '');
const d = val?.data;
if (typeof d !== 'boolean') {
console.info('data:', d);
setAnswer({
...d,
conversationId: body?.conversation_id,
});
}
} catch (e) {
console.warn(e);
}
}
}
console.info('done?');
setDone(true);
resetAnswer();
return { data: await res, response };
} catch (e) {
setDone(true);
resetAnswer();
console.warn(e);
}
},
[url, resetAnswer],
);
return { send, answer, done, setDone, resetAnswer };
};
export const useSpeechWithSse = (url: string = api.tts) => {
const read = useCallback(
async (body: any) => {
const response = await fetch(url, {
method: 'POST',
headers: {
[Authorization]: getAuthorization(),
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
try {
const res = await response.clone().json();
if (res?.code !== 0) {
message.error(res?.message);
}
} catch (error) {
console.warn('🚀 ~ error:', error);
}
return response;
},
[url],
);
return { read };
};
//#region chat hooks
export const useScrollToBottom = (messages?: unknown) => {
const ref = useRef<HTMLDivElement>(null);
const scrollToBottom = useCallback(() => {
if (messages) {
ref.current?.scrollIntoView({ behavior: 'instant' });
}
}, [messages]); // If the message changes, scroll to the bottom
useEffect(() => {
scrollToBottom();
}, [scrollToBottom]);
return ref;
};
export const useHandleMessageInputChange = () => {
const [value, setValue] = useState('');
const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
const value = e.target.value;
const nextValue = value.replaceAll('\\n', '\n').replaceAll('\\t', '\t');
setValue(nextValue);
};
return {
handleInputChange,
value,
setValue,
};
};
export const useSelectDerivedMessages = () => {
const [derivedMessages, setDerivedMessages] = useState<IMessage[]>([]);
const ref = useScrollToBottom(derivedMessages);
const addNewestQuestion = useCallback(
(message: Message, answer: string = '') => {
setDerivedMessages((pre) => {
return [
...pre,
{
...message,
id: buildMessageUuid(message), // The message id is generated on the front end,
// and the message id returned by the back end is the same as the question id,
// so that the pair of messages can be deleted together when deleting the message
},
{
role: MessageType.Assistant,
content: answer,
id: buildMessageUuid({ ...message, role: MessageType.Assistant }),
},
];
});
},
[],
);
// Add the streaming message to the last item in the message list
const addNewestAnswer = useCallback((answer: IAnswer) => {
setDerivedMessages((pre) => {
return [
...(pre?.slice(0, -1) ?? []),
{
role: MessageType.Assistant,
content: answer.answer,
reference: answer.reference,
id: buildMessageUuid({
id: answer.id,
role: MessageType.Assistant,
}),
prompt: answer.prompt,
audio_binary: answer.audio_binary,
...omit(answer, 'reference'),
},
];
});
}, []);
const removeLatestMessage = useCallback(() => {
setDerivedMessages((pre) => {
const nextMessages = pre?.slice(0, -2) ?? [];
return nextMessages;
});
}, []);
const removeMessageById = useCallback(
(messageId: string) => {
setDerivedMessages((pre) => {
const nextMessages = pre?.filter((x) => x.id !== messageId) ?? [];
return nextMessages;
});
},
[setDerivedMessages],
);
const removeMessagesAfterCurrentMessage = useCallback(
(messageId: string) => {
setDerivedMessages((pre) => {
const index = pre.findIndex((x) => x.id === messageId);
if (index !== -1) {
let nextMessages = pre.slice(0, index + 2) ?? [];
const latestMessage = nextMessages.at(-1);
nextMessages = latestMessage
? [
...nextMessages.slice(0, -1),
{
...latestMessage,
content: '',
reference: undefined,
prompt: undefined,
},
]
: nextMessages;
return nextMessages;
}
return pre;
});
},
[setDerivedMessages],
);
return {
ref,
derivedMessages,
setDerivedMessages,
addNewestQuestion,
addNewestAnswer,
removeLatestMessage,
removeMessageById,
removeMessagesAfterCurrentMessage,
};
};
export interface IRemoveMessageById {
removeMessageById(messageId: string): void;
}
export const useRemoveMessagesAfterCurrentMessage = (
setCurrentConversation: (
callback: (state: IClientConversation) => IClientConversation,
) => void,
) => {
const removeMessagesAfterCurrentMessage = useCallback(
(messageId: string) => {
setCurrentConversation((pre) => {
const index = pre.message?.findIndex((x) => x.id === messageId);
if (index !== -1) {
let nextMessages = pre.message?.slice(0, index + 2) ?? [];
const latestMessage = nextMessages.at(-1);
nextMessages = latestMessage
? [
...nextMessages.slice(0, -1),
{
...latestMessage,
content: '',
reference: undefined,
prompt: undefined,
},
]
: nextMessages;
return {
...pre,
message: nextMessages,
};
}
return pre;
});
},
[setCurrentConversation],
);
return { removeMessagesAfterCurrentMessage };
};
export interface IRegenerateMessage {
regenerateMessage?: (message: Message) => void;
}
export const useRegenerateMessage = ({
removeMessagesAfterCurrentMessage,
sendMessage,
messages,
}: {
removeMessagesAfterCurrentMessage(messageId: string): void;
sendMessage({
message,
}: {
message: Message;
messages?: Message[];
}): void | Promise<any>;
messages: Message[];
}) => {
const regenerateMessage = useCallback(
async (message: Message) => {
if (message.id) {
removeMessagesAfterCurrentMessage(message.id);
const index = messages.findIndex((x) => x.id === message.id);
let nextMessages;
if (index !== -1) {
nextMessages = messages.slice(0, index);
}
sendMessage({
message: { ...message, id: uuid() },
messages: nextMessages,
});
}
},
[removeMessagesAfterCurrentMessage, sendMessage, messages],
);
return { regenerateMessage };
};
// #endregion
/**
*
* @param defaultId
* used to switch between different items, similar to radio
* @returns
*/
export const useSelectItem = (defaultId?: string) => {
const [selectedId, setSelectedId] = useState('');
const handleItemClick = useCallback(
(id: string) => () => {
setSelectedId(id);
},
[],
);
useEffect(() => {
if (defaultId) {
setSelectedId(defaultId);
}
}, [defaultId]);
return { selectedId, handleItemClick };
};
export const useFetchModelId = () => {
const { data: tenantInfo } = useFetchTenantInfo();
return tenantInfo?.llm_id ?? '';
};
const ChunkTokenNumMap = {
naive: 128,
knowledge_graph: 8192,
};
export const useHandleChunkMethodSelectChange = (form: FormInstance) => {
// const form = Form.useFormInstance();
const handleChange = useCallback(
(value: string) => {
if (value in ChunkTokenNumMap) {
form.setFieldValue(
['parser_config', 'chunk_token_num'],
ChunkTokenNumMap[value as keyof typeof ChunkTokenNumMap],
);
}
},
[form],
);
return handleChange;
};
// reset form fields when modal is form, closed
export const useResetFormOnCloseModal = ({
form,
visible,
}: {
form: FormInstance;
visible?: boolean;
}) => {
const prevOpenRef = useRef<boolean>();
useEffect(() => {
prevOpenRef.current = visible;
}, [visible]);
const prevOpen = prevOpenRef.current;
useEffect(() => {
if (!visible && prevOpen) {
form.resetFields();
}
}, [form, prevOpen, visible]);
};
|