Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

logic-hooks.ts 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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/authorizationUtil';
  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 './commonHooks';
  24. import { useSetDocumentParser } from './documentHooks';
  25. import { useFetchLlmList } from './llmHooks';
  26. import { useOneNamespaceEffectsLoading } from './storeHooks';
  27. import {
  28. useFetchTenantInfo,
  29. useSaveSetting,
  30. useSelectTenantInfo,
  31. } from './userSettingHook';
  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 useChangeLanguage = () => {
  67. const { i18n } = useTranslation();
  68. const saveSetting = useSaveSetting();
  69. const changeLanguage = (lng: string) => {
  70. i18n.changeLanguage(
  71. LanguageTranslationMap[lng as keyof typeof LanguageTranslationMap],
  72. );
  73. saveSetting({ language: lng });
  74. };
  75. return changeLanguage;
  76. };
  77. export const useGetPagination = (
  78. total: number,
  79. page: number,
  80. pageSize: number,
  81. onPageChange: PaginationProps['onChange'],
  82. ) => {
  83. const { t } = useTranslate('common');
  84. const pagination: PaginationProps = useMemo(() => {
  85. return {
  86. showQuickJumper: true,
  87. total,
  88. showSizeChanger: true,
  89. current: page,
  90. pageSize: pageSize,
  91. pageSizeOptions: [1, 2, 10, 20, 50, 100],
  92. onChange: onPageChange,
  93. showTotal: (total) => `${t('total')} ${total}`,
  94. };
  95. }, [t, onPageChange, page, pageSize, total]);
  96. return {
  97. pagination,
  98. };
  99. };
  100. export const useSetPagination = (namespace: string) => {
  101. const dispatch = useDispatch();
  102. const setPagination = useCallback(
  103. (pageNumber = 1, pageSize?: number) => {
  104. const pagination: Pagination = {
  105. current: pageNumber,
  106. } as Pagination;
  107. if (pageSize) {
  108. pagination.pageSize = pageSize;
  109. }
  110. dispatch({
  111. type: `${namespace}/setPagination`,
  112. payload: pagination,
  113. });
  114. },
  115. [dispatch, namespace],
  116. );
  117. return setPagination;
  118. };
  119. export interface AppConf {
  120. appName: string;
  121. }
  122. export const useFetchAppConf = () => {
  123. const [appConf, setAppConf] = useState<AppConf>({} as AppConf);
  124. const fetchAppConf = useCallback(async () => {
  125. const ret = await axios.get('/conf.json');
  126. setAppConf(ret.data);
  127. }, []);
  128. useEffect(() => {
  129. fetchAppConf();
  130. }, [fetchAppConf]);
  131. return appConf;
  132. };
  133. export const useSendMessageWithSse = (
  134. url: string = api.completeConversation,
  135. ) => {
  136. const [answer, setAnswer] = useState<IAnswer>({} as IAnswer);
  137. const [done, setDone] = useState(true);
  138. const send = useCallback(
  139. async (
  140. body: any,
  141. ): Promise<{ response: Response; data: ResponseType } | undefined> => {
  142. try {
  143. setDone(false);
  144. const response = await fetch(url, {
  145. method: 'POST',
  146. headers: {
  147. [Authorization]: getAuthorization(),
  148. 'Content-Type': 'application/json',
  149. },
  150. body: JSON.stringify(body),
  151. });
  152. const res = response.clone().json();
  153. const reader = response?.body
  154. ?.pipeThrough(new TextDecoderStream())
  155. .pipeThrough(new EventSourceParserStream())
  156. .getReader();
  157. while (true) {
  158. const x = await reader?.read();
  159. if (x) {
  160. const { done, value } = x;
  161. try {
  162. const val = JSON.parse(value?.data || '');
  163. const d = val?.data;
  164. if (typeof d !== 'boolean') {
  165. console.info('data:', d);
  166. setAnswer({
  167. ...d,
  168. conversationId: body?.conversation_id,
  169. });
  170. }
  171. } catch (e) {
  172. console.warn(e);
  173. }
  174. if (done) {
  175. console.info('done');
  176. break;
  177. }
  178. }
  179. }
  180. console.info('done?');
  181. setDone(true);
  182. return { data: await res, response };
  183. } catch (e) {
  184. setDone(true);
  185. console.warn(e);
  186. }
  187. },
  188. [url],
  189. );
  190. return { send, answer, done, setDone };
  191. };
  192. //#region chat hooks
  193. export const useScrollToBottom = (messages?: unknown) => {
  194. const ref = useRef<HTMLDivElement>(null);
  195. const scrollToBottom = useCallback(() => {
  196. if (messages) {
  197. ref.current?.scrollIntoView({ behavior: 'instant' });
  198. }
  199. }, [messages]); // If the message changes, scroll to the bottom
  200. useEffect(() => {
  201. scrollToBottom();
  202. }, [scrollToBottom]);
  203. return ref;
  204. };
  205. export const useHandleMessageInputChange = () => {
  206. const [value, setValue] = useState('');
  207. const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
  208. const value = e.target.value;
  209. const nextValue = value.replaceAll('\\n', '\n').replaceAll('\\t', '\t');
  210. setValue(nextValue);
  211. };
  212. return {
  213. handleInputChange,
  214. value,
  215. setValue,
  216. };
  217. };
  218. // #endregion
  219. /**
  220. *
  221. * @param defaultId
  222. * used to switch between different items, similar to radio
  223. * @returns
  224. */
  225. export const useSelectItem = (defaultId?: string) => {
  226. const [selectedId, setSelectedId] = useState('');
  227. const handleItemClick = useCallback(
  228. (id: string) => () => {
  229. setSelectedId(id);
  230. },
  231. [],
  232. );
  233. useEffect(() => {
  234. if (defaultId) {
  235. setSelectedId(defaultId);
  236. }
  237. }, [defaultId]);
  238. return { selectedId, handleItemClick };
  239. };
  240. export const useFetchModelId = (visible: boolean) => {
  241. const fetchTenantInfo = useFetchTenantInfo(false);
  242. const tenantInfo = useSelectTenantInfo();
  243. useEffect(() => {
  244. if (visible) {
  245. fetchTenantInfo();
  246. }
  247. }, [visible, fetchTenantInfo]);
  248. return tenantInfo?.llm_id ?? '';
  249. };
  250. export const useFetchLlmModelOnVisible = (visible: boolean) => {
  251. const fetchLlmList = useFetchLlmList();
  252. useEffect(() => {
  253. if (visible) {
  254. fetchLlmList();
  255. }
  256. }, [fetchLlmList, visible]);
  257. };