You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

logic-hooks.ts 8.6KB

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