Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

logic-hooks.ts 18KB

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