Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

logic-hooks.ts 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import { Authorization } from '@/constants/authorization';
  2. import { LanguageTranslationMap } from '@/constants/common';
  3. import { Pagination } from '@/interfaces/common';
  4. import { ResponseType } from '@/interfaces/database/base';
  5. import { IAnswer } from '@/interfaces/database/chat';
  6. import { IKnowledgeFile } from '@/interfaces/database/knowledge';
  7. import { IChangeParserConfigRequestBody } from '@/interfaces/request/document';
  8. import api from '@/utils/api';
  9. import { getAuthorization } from '@/utils/authorization-util';
  10. import { PaginationProps } from 'antd';
  11. import { FormInstance } from 'antd/lib';
  12. import axios from 'axios';
  13. import { EventSourceParserStream } from 'eventsource-parser/stream';
  14. import {
  15. ChangeEventHandler,
  16. useCallback,
  17. useEffect,
  18. useMemo,
  19. useRef,
  20. useState,
  21. } from 'react';
  22. import { useTranslation } from 'react-i18next';
  23. import { useDispatch } from 'umi';
  24. import { useSetModalState, useTranslate } from './common-hooks';
  25. import { useSetDocumentParser } from './document-hooks';
  26. import { useSetPaginationParams } from './route-hook';
  27. import { useOneNamespaceEffectsLoading } from './store-hooks';
  28. import { useFetchTenantInfo, useSaveSetting } from './user-setting-hooks';
  29. export const useChangeDocumentParser = (documentId: string) => {
  30. const setDocumentParser = useSetDocumentParser();
  31. const {
  32. visible: changeParserVisible,
  33. hideModal: hideChangeParserModal,
  34. showModal: showChangeParserModal,
  35. } = useSetModalState();
  36. const loading = useOneNamespaceEffectsLoading('kFModel', [
  37. 'document_change_parser',
  38. ]);
  39. const onChangeParserOk = useCallback(
  40. async (parserId: string, parserConfig: IChangeParserConfigRequestBody) => {
  41. const ret = await setDocumentParser(parserId, documentId, parserConfig);
  42. if (ret === 0) {
  43. hideChangeParserModal();
  44. }
  45. },
  46. [hideChangeParserModal, setDocumentParser, documentId],
  47. );
  48. return {
  49. changeParserLoading: loading,
  50. onChangeParserOk,
  51. changeParserVisible,
  52. hideChangeParserModal,
  53. showChangeParserModal,
  54. };
  55. };
  56. export const useSetSelectedRecord = <T = IKnowledgeFile>() => {
  57. const [currentRecord, setCurrentRecord] = useState<T>({} as T);
  58. const setRecord = (record: T) => {
  59. setCurrentRecord(record);
  60. };
  61. return { currentRecord, setRecord };
  62. };
  63. export const useHandleSearchChange = () => {
  64. const [searchString, setSearchString] = useState('');
  65. const handleInputChange = useCallback(
  66. (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
  67. const value = e.target.value;
  68. setSearchString(value);
  69. },
  70. [],
  71. );
  72. return { handleInputChange, searchString };
  73. };
  74. export const useChangeLanguage = () => {
  75. const { i18n } = useTranslation();
  76. const { saveSetting } = useSaveSetting();
  77. const changeLanguage = (lng: string) => {
  78. i18n.changeLanguage(
  79. LanguageTranslationMap[lng as keyof typeof LanguageTranslationMap],
  80. );
  81. saveSetting({ language: lng });
  82. };
  83. return changeLanguage;
  84. };
  85. export const useGetPaginationWithRouter = () => {
  86. const { t } = useTranslate('common');
  87. const {
  88. setPaginationParams,
  89. page,
  90. size: pageSize,
  91. } = useSetPaginationParams();
  92. const onPageChange: PaginationProps['onChange'] = useCallback(
  93. (pageNumber: number, pageSize: number) => {
  94. setPaginationParams(pageNumber, pageSize);
  95. },
  96. [setPaginationParams],
  97. );
  98. const setCurrentPagination = useCallback(
  99. (pagination: { page: number; pageSize?: number }) => {
  100. setPaginationParams(pagination.page, pagination.pageSize);
  101. },
  102. [setPaginationParams],
  103. );
  104. const pagination: PaginationProps = useMemo(() => {
  105. return {
  106. showQuickJumper: true,
  107. total: 0,
  108. showSizeChanger: true,
  109. current: page,
  110. pageSize: pageSize,
  111. pageSizeOptions: [1, 2, 10, 20, 50, 100],
  112. onChange: onPageChange,
  113. showTotal: (total) => `${t('total')} ${total}`,
  114. };
  115. }, [t, onPageChange, page, pageSize]);
  116. return {
  117. pagination,
  118. setPagination: setCurrentPagination,
  119. };
  120. };
  121. export const useGetPagination = () => {
  122. const [pagination, setPagination] = useState({ page: 1, pageSize: 10 });
  123. const { t } = useTranslate('common');
  124. const onPageChange: PaginationProps['onChange'] = useCallback(
  125. (pageNumber: number, pageSize: number) => {
  126. setPagination({ page: pageNumber, pageSize });
  127. },
  128. [],
  129. );
  130. const currentPagination: PaginationProps = useMemo(() => {
  131. return {
  132. showQuickJumper: true,
  133. total: 0,
  134. showSizeChanger: true,
  135. current: pagination.page,
  136. pageSize: pagination.pageSize,
  137. pageSizeOptions: [1, 2, 10, 20, 50, 100],
  138. onChange: onPageChange,
  139. showTotal: (total) => `${t('total')} ${total}`,
  140. };
  141. }, [t, onPageChange, pagination]);
  142. return {
  143. pagination: currentPagination,
  144. };
  145. };
  146. export const useSetPagination = (namespace: string) => {
  147. const dispatch = useDispatch();
  148. const setPagination = useCallback(
  149. (pageNumber = 1, pageSize?: number) => {
  150. const pagination: Pagination = {
  151. current: pageNumber,
  152. } as Pagination;
  153. if (pageSize) {
  154. pagination.pageSize = pageSize;
  155. }
  156. dispatch({
  157. type: `${namespace}/setPagination`,
  158. payload: pagination,
  159. });
  160. },
  161. [dispatch, namespace],
  162. );
  163. return setPagination;
  164. };
  165. export interface AppConf {
  166. appName: string;
  167. }
  168. export const useFetchAppConf = () => {
  169. const [appConf, setAppConf] = useState<AppConf>({} as AppConf);
  170. const fetchAppConf = useCallback(async () => {
  171. const ret = await axios.get('/conf.json');
  172. setAppConf(ret.data);
  173. }, []);
  174. useEffect(() => {
  175. fetchAppConf();
  176. }, [fetchAppConf]);
  177. return appConf;
  178. };
  179. export const useSendMessageWithSse = (
  180. url: string = api.completeConversation,
  181. ) => {
  182. const [answer, setAnswer] = useState<IAnswer>({} as IAnswer);
  183. const [done, setDone] = useState(true);
  184. const send = useCallback(
  185. async (
  186. body: any,
  187. ): Promise<{ response: Response; data: ResponseType } | undefined> => {
  188. try {
  189. setDone(false);
  190. const response = await fetch(url, {
  191. method: 'POST',
  192. headers: {
  193. [Authorization]: getAuthorization(),
  194. 'Content-Type': 'application/json',
  195. },
  196. body: JSON.stringify(body),
  197. });
  198. const res = response.clone().json();
  199. const reader = response?.body
  200. ?.pipeThrough(new TextDecoderStream())
  201. .pipeThrough(new EventSourceParserStream())
  202. .getReader();
  203. while (true) {
  204. const x = await reader?.read();
  205. if (x) {
  206. const { done, value } = x;
  207. try {
  208. const val = JSON.parse(value?.data || '');
  209. const d = val?.data;
  210. if (typeof d !== 'boolean') {
  211. console.info('data:', d);
  212. setAnswer({
  213. ...d,
  214. conversationId: body?.conversation_id,
  215. });
  216. }
  217. } catch (e) {
  218. console.warn(e);
  219. }
  220. if (done) {
  221. console.info('done');
  222. break;
  223. }
  224. }
  225. }
  226. console.info('done?');
  227. setDone(true);
  228. return { data: await res, response };
  229. } catch (e) {
  230. setDone(true);
  231. console.warn(e);
  232. }
  233. },
  234. [url],
  235. );
  236. return { send, answer, done, setDone };
  237. };
  238. //#region chat hooks
  239. export const useScrollToBottom = (messages?: unknown) => {
  240. const ref = useRef<HTMLDivElement>(null);
  241. const scrollToBottom = useCallback(() => {
  242. if (messages) {
  243. ref.current?.scrollIntoView({ behavior: 'instant' });
  244. }
  245. }, [messages]); // If the message changes, scroll to the bottom
  246. useEffect(() => {
  247. scrollToBottom();
  248. }, [scrollToBottom]);
  249. return ref;
  250. };
  251. export const useHandleMessageInputChange = () => {
  252. const [value, setValue] = useState('');
  253. const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
  254. const value = e.target.value;
  255. const nextValue = value.replaceAll('\\n', '\n').replaceAll('\\t', '\t');
  256. setValue(nextValue);
  257. };
  258. return {
  259. handleInputChange,
  260. value,
  261. setValue,
  262. };
  263. };
  264. // #endregion
  265. /**
  266. *
  267. * @param defaultId
  268. * used to switch between different items, similar to radio
  269. * @returns
  270. */
  271. export const useSelectItem = (defaultId?: string) => {
  272. const [selectedId, setSelectedId] = useState('');
  273. const handleItemClick = useCallback(
  274. (id: string) => () => {
  275. setSelectedId(id);
  276. },
  277. [],
  278. );
  279. useEffect(() => {
  280. if (defaultId) {
  281. setSelectedId(defaultId);
  282. }
  283. }, [defaultId]);
  284. return { selectedId, handleItemClick };
  285. };
  286. export const useFetchModelId = () => {
  287. const { data: tenantInfo } = useFetchTenantInfo();
  288. return tenantInfo?.llm_id ?? '';
  289. };
  290. const ChunkTokenNumMap = {
  291. naive: 128,
  292. knowledge_graph: 8192,
  293. };
  294. export const useHandleChunkMethodSelectChange = (form: FormInstance) => {
  295. // const form = Form.useFormInstance();
  296. const handleChange = useCallback(
  297. (value: string) => {
  298. if (value in ChunkTokenNumMap) {
  299. form.setFieldValue(
  300. ['parser_config', 'chunk_token_num'],
  301. ChunkTokenNumMap[value as keyof typeof ChunkTokenNumMap],
  302. );
  303. }
  304. },
  305. [form],
  306. );
  307. return handleChange;
  308. };