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.

use-agent-request.ts 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. import { FileUploadProps } from '@/components/file-upload';
  2. import message from '@/components/ui/message';
  3. import { AgentGlobals } from '@/constants/agent';
  4. import {
  5. DSL,
  6. IAgentLogsRequest,
  7. IAgentLogsResponse,
  8. IFlow,
  9. IFlowTemplate,
  10. ITraceData,
  11. } from '@/interfaces/database/agent';
  12. import { IDebugSingleRequestBody } from '@/interfaces/request/agent';
  13. import i18n from '@/locales/config';
  14. import { BeginId } from '@/pages/agent/constant';
  15. import { IInputs } from '@/pages/agent/interface';
  16. import { useGetSharedChatSearchParams } from '@/pages/chat/shared-hooks';
  17. import agentService, {
  18. fetchAgentLogsByCanvasId,
  19. fetchTrace,
  20. } from '@/services/agent-service';
  21. import api from '@/utils/api';
  22. import { buildMessageListWithUuid } from '@/utils/chat';
  23. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  24. import { useDebounce } from 'ahooks';
  25. import { get, set } from 'lodash';
  26. import { useCallback, useState } from 'react';
  27. import { useTranslation } from 'react-i18next';
  28. import { useParams } from 'umi';
  29. import { v4 as uuid } from 'uuid';
  30. import {
  31. useGetPaginationWithRouter,
  32. useHandleSearchChange,
  33. } from './logic-hooks';
  34. export const enum AgentApiAction {
  35. FetchAgentList = 'fetchAgentList',
  36. UpdateAgentSetting = 'updateAgentSetting',
  37. DeleteAgent = 'deleteAgent',
  38. FetchAgentDetail = 'fetchAgentDetail',
  39. ResetAgent = 'resetAgent',
  40. SetAgent = 'setAgent',
  41. FetchAgentTemplates = 'fetchAgentTemplates',
  42. UploadCanvasFile = 'uploadCanvasFile',
  43. UploadCanvasFileWithProgress = 'uploadCanvasFileWithProgress',
  44. Trace = 'trace',
  45. TestDbConnect = 'testDbConnect',
  46. DebugSingle = 'debugSingle',
  47. FetchInputForm = 'fetchInputForm',
  48. FetchVersionList = 'fetchVersionList',
  49. FetchVersion = 'fetchVersion',
  50. FetchAgentAvatar = 'fetchAgentAvatar',
  51. FetchExternalAgentInputs = 'fetchExternalAgentInputs',
  52. SetAgentSetting = 'setAgentSetting',
  53. }
  54. export const EmptyDsl = {
  55. graph: {
  56. nodes: [
  57. {
  58. id: BeginId,
  59. type: 'beginNode',
  60. position: {
  61. x: 50,
  62. y: 200,
  63. },
  64. data: {
  65. label: 'Begin',
  66. name: 'begin',
  67. },
  68. sourcePosition: 'left',
  69. targetPosition: 'right',
  70. },
  71. ],
  72. edges: [],
  73. },
  74. components: {
  75. begin: {
  76. obj: {
  77. component_name: 'Begin',
  78. params: {},
  79. },
  80. downstream: ['Answer:China'], // other edge target is downstream, edge source is current node id
  81. upstream: [], // edge source is upstream, edge target is current node id
  82. },
  83. },
  84. retrieval: [], // reference
  85. history: [],
  86. path: [],
  87. globals: {
  88. [AgentGlobals.SysQuery]: '',
  89. [AgentGlobals.SysUserId]: '',
  90. [AgentGlobals.SysConversationTurns]: 0,
  91. [AgentGlobals.SysFiles]: [],
  92. },
  93. };
  94. export const useFetchAgentTemplates = () => {
  95. const { t } = useTranslation();
  96. const { data } = useQuery<IFlowTemplate[]>({
  97. queryKey: [AgentApiAction.FetchAgentTemplates],
  98. initialData: [],
  99. queryFn: async () => {
  100. const { data } = await agentService.listTemplates();
  101. if (Array.isArray(data?.data)) {
  102. data.data.unshift({
  103. id: uuid(),
  104. title: t('flow.blank'),
  105. description: t('flow.createFromNothing'),
  106. dsl: EmptyDsl,
  107. });
  108. }
  109. return data.data;
  110. },
  111. });
  112. return data;
  113. };
  114. export const useFetchAgentListByPage = () => {
  115. const { searchString, handleInputChange } = useHandleSearchChange();
  116. const { pagination, setPagination } = useGetPaginationWithRouter();
  117. const debouncedSearchString = useDebounce(searchString, { wait: 500 });
  118. const { data, isFetching: loading } = useQuery<{
  119. canvas: IFlow[];
  120. total: number;
  121. }>({
  122. queryKey: [
  123. AgentApiAction.FetchAgentList,
  124. {
  125. debouncedSearchString,
  126. ...pagination,
  127. },
  128. ],
  129. initialData: { canvas: [], total: 0 },
  130. gcTime: 0,
  131. queryFn: async () => {
  132. const { data } = await agentService.listCanvasTeam(
  133. {
  134. params: {
  135. keywords: debouncedSearchString,
  136. page_size: pagination.pageSize,
  137. page: pagination.current,
  138. },
  139. },
  140. true,
  141. );
  142. return data?.data;
  143. },
  144. });
  145. const onInputChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
  146. (e) => {
  147. // setPagination({ page: 1 });
  148. handleInputChange(e);
  149. },
  150. [handleInputChange],
  151. );
  152. return {
  153. data: data.canvas,
  154. loading,
  155. searchString,
  156. handleInputChange: onInputChange,
  157. pagination: { ...pagination, total: data?.total },
  158. setPagination,
  159. };
  160. };
  161. export const useUpdateAgentSetting = () => {
  162. const queryClient = useQueryClient();
  163. const {
  164. data,
  165. isPending: loading,
  166. mutateAsync,
  167. } = useMutation({
  168. mutationKey: [AgentApiAction.UpdateAgentSetting],
  169. mutationFn: async (params: any) => {
  170. const ret = await agentService.settingCanvas(params);
  171. if (ret?.data?.code === 0) {
  172. message.success('success');
  173. queryClient.invalidateQueries({
  174. queryKey: [AgentApiAction.FetchAgentList],
  175. });
  176. } else {
  177. message.error(ret?.data?.data);
  178. }
  179. return ret?.data?.code;
  180. },
  181. });
  182. return { data, loading, updateAgentSetting: mutateAsync };
  183. };
  184. export const useDeleteAgent = () => {
  185. const queryClient = useQueryClient();
  186. const {
  187. data,
  188. isPending: loading,
  189. mutateAsync,
  190. } = useMutation({
  191. mutationKey: [AgentApiAction.DeleteAgent],
  192. mutationFn: async (canvasIds: string[]) => {
  193. const { data } = await agentService.removeCanvas({ canvasIds });
  194. if (data.code === 0) {
  195. queryClient.invalidateQueries({
  196. queryKey: [AgentApiAction.FetchAgentList],
  197. });
  198. }
  199. return data?.data ?? [];
  200. },
  201. });
  202. return { data, loading, deleteAgent: mutateAsync };
  203. };
  204. export const useFetchAgent = (): {
  205. data: IFlow;
  206. loading: boolean;
  207. refetch: () => void;
  208. } => {
  209. const { id } = useParams();
  210. const { sharedId } = useGetSharedChatSearchParams();
  211. const {
  212. data,
  213. isFetching: loading,
  214. refetch,
  215. } = useQuery({
  216. queryKey: [AgentApiAction.FetchAgentDetail],
  217. initialData: {} as IFlow,
  218. refetchOnReconnect: false,
  219. refetchOnMount: false,
  220. refetchOnWindowFocus: false,
  221. gcTime: 0,
  222. queryFn: async () => {
  223. const { data } = await agentService.fetchCanvas(sharedId || id);
  224. const messageList = buildMessageListWithUuid(
  225. get(data, 'data.dsl.messages', []),
  226. );
  227. set(data, 'data.dsl.messages', messageList);
  228. return data?.data ?? {};
  229. },
  230. });
  231. return { data, loading, refetch };
  232. };
  233. export const useResetAgent = () => {
  234. const { id } = useParams();
  235. const {
  236. data,
  237. isPending: loading,
  238. mutateAsync,
  239. } = useMutation({
  240. mutationKey: [AgentApiAction.ResetAgent],
  241. mutationFn: async () => {
  242. const { data } = await agentService.resetCanvas({ id });
  243. return data;
  244. },
  245. });
  246. return { data, loading, resetAgent: mutateAsync };
  247. };
  248. export const useSetAgent = (showMessage: boolean = true) => {
  249. const queryClient = useQueryClient();
  250. const {
  251. data,
  252. isPending: loading,
  253. mutateAsync,
  254. } = useMutation({
  255. mutationKey: [AgentApiAction.SetAgent],
  256. mutationFn: async (params: {
  257. id?: string;
  258. title?: string;
  259. dsl?: DSL;
  260. avatar?: string;
  261. }) => {
  262. const { data = {} } = await agentService.setCanvas(params);
  263. if (data.code === 0) {
  264. if (showMessage) {
  265. message.success(
  266. i18n.t(`message.${params?.id ? 'modified' : 'created'}`),
  267. );
  268. }
  269. queryClient.invalidateQueries({
  270. queryKey: [AgentApiAction.FetchAgentList],
  271. });
  272. }
  273. return data;
  274. },
  275. });
  276. return { data, loading, setAgent: mutateAsync };
  277. };
  278. // Only one file can be uploaded at a time
  279. export const useUploadCanvasFile = () => {
  280. const { id } = useParams();
  281. const {
  282. data,
  283. isPending: loading,
  284. mutateAsync,
  285. } = useMutation({
  286. mutationKey: [AgentApiAction.UploadCanvasFile],
  287. mutationFn: async (body: any) => {
  288. let nextBody = body;
  289. try {
  290. if (Array.isArray(body)) {
  291. nextBody = new FormData();
  292. body.forEach((file: File) => {
  293. nextBody.append('file', file as any);
  294. });
  295. }
  296. const { data } = await agentService.uploadCanvasFile(
  297. { url: api.uploadAgentFile(id), data: nextBody },
  298. true,
  299. );
  300. if (data?.code === 0) {
  301. message.success(i18n.t('message.uploaded'));
  302. }
  303. return data;
  304. } catch (error) {
  305. message.error('error');
  306. }
  307. },
  308. });
  309. return { data, loading, uploadCanvasFile: mutateAsync };
  310. };
  311. export const useUploadCanvasFileWithProgress = (
  312. identifier?: Nullable<string>,
  313. ) => {
  314. const { id } = useParams();
  315. type UploadParameters = Parameters<NonNullable<FileUploadProps['onUpload']>>;
  316. type X = { files: UploadParameters[0]; options: UploadParameters[1] };
  317. const {
  318. data,
  319. isPending: loading,
  320. mutateAsync,
  321. } = useMutation({
  322. mutationKey: [AgentApiAction.UploadCanvasFileWithProgress],
  323. mutationFn: async ({
  324. files,
  325. options: { onError, onSuccess, onProgress },
  326. }: X) => {
  327. const formData = new FormData();
  328. try {
  329. if (Array.isArray(files)) {
  330. files.forEach((file: File) => {
  331. formData.append('file', file);
  332. });
  333. }
  334. const { data } = await agentService.uploadCanvasFile(
  335. {
  336. url: api.uploadAgentFile(identifier || id),
  337. data: formData,
  338. onUploadProgress: ({ progress }) => {
  339. files.forEach((file) => {
  340. onProgress(file, (progress || 0) * 100);
  341. });
  342. },
  343. },
  344. true,
  345. );
  346. if (data?.code === 0) {
  347. files.forEach((file) => {
  348. onSuccess(file);
  349. });
  350. message.success(i18n.t('message.uploaded'));
  351. }
  352. return data;
  353. } catch (error) {
  354. files.forEach((file) => {
  355. onError(file, error as Error);
  356. });
  357. message.error('error', error?.message);
  358. }
  359. },
  360. });
  361. return { data, loading, uploadCanvasFile: mutateAsync };
  362. };
  363. export const useFetchMessageTrace = (
  364. isStopFetchTrace: boolean,
  365. canvasId?: string,
  366. ) => {
  367. const { id } = useParams();
  368. const queryId = id || canvasId;
  369. const [messageId, setMessageId] = useState('');
  370. const {
  371. data,
  372. isFetching: loading,
  373. refetch,
  374. } = useQuery<ITraceData[]>({
  375. queryKey: [AgentApiAction.Trace, queryId, messageId],
  376. refetchOnReconnect: false,
  377. refetchOnMount: false,
  378. refetchOnWindowFocus: false,
  379. gcTime: 0,
  380. enabled: !!queryId && !!messageId,
  381. refetchInterval: !isStopFetchTrace ? 3000 : false,
  382. queryFn: async () => {
  383. const { data } = await fetchTrace({
  384. canvas_id: queryId as string,
  385. message_id: messageId,
  386. });
  387. return data?.data ?? [];
  388. },
  389. });
  390. return { data, loading, refetch, setMessageId };
  391. };
  392. export const useTestDbConnect = () => {
  393. const {
  394. data,
  395. isPending: loading,
  396. mutateAsync,
  397. } = useMutation({
  398. mutationKey: [AgentApiAction.TestDbConnect],
  399. mutationFn: async (params: any) => {
  400. const ret = await agentService.testDbConnect(params);
  401. if (ret?.data?.code === 0) {
  402. message.success(ret?.data?.data);
  403. } else {
  404. message.error(ret?.data?.data);
  405. }
  406. return ret;
  407. },
  408. });
  409. return { data, loading, testDbConnect: mutateAsync };
  410. };
  411. export const useDebugSingle = () => {
  412. const { id } = useParams();
  413. const {
  414. data,
  415. isPending: loading,
  416. mutateAsync,
  417. } = useMutation({
  418. mutationKey: [AgentApiAction.FetchInputForm],
  419. mutationFn: async (params: IDebugSingleRequestBody) => {
  420. const ret = await agentService.debugSingle({ id, ...params });
  421. if (ret?.data?.code !== 0) {
  422. message.error(ret?.data?.message);
  423. }
  424. return ret?.data?.data;
  425. },
  426. });
  427. return { data, loading, debugSingle: mutateAsync };
  428. };
  429. export const useFetchInputForm = (componentId?: string) => {
  430. const { id } = useParams();
  431. const { data } = useQuery<Record<string, any>>({
  432. queryKey: [AgentApiAction.FetchInputForm],
  433. initialData: {},
  434. enabled: !!id && !!componentId,
  435. queryFn: async () => {
  436. const { data } = await agentService.inputForm(
  437. {
  438. params: {
  439. id,
  440. component_id: componentId,
  441. },
  442. },
  443. true,
  444. );
  445. return data.data;
  446. },
  447. });
  448. return data;
  449. };
  450. export const useFetchVersionList = () => {
  451. const { id } = useParams();
  452. const { data, isFetching: loading } = useQuery<
  453. Array<{ created_at: string; title: string; id: string }>
  454. >({
  455. queryKey: [AgentApiAction.FetchVersionList],
  456. initialData: [],
  457. gcTime: 0,
  458. queryFn: async () => {
  459. const { data } = await agentService.fetchVersionList(id);
  460. return data?.data ?? [];
  461. },
  462. });
  463. return { data, loading };
  464. };
  465. export const useFetchVersion = (
  466. version_id?: string,
  467. ): {
  468. data?: IFlow;
  469. loading: boolean;
  470. } => {
  471. const { data, isFetching: loading } = useQuery({
  472. queryKey: [AgentApiAction.FetchVersion, version_id],
  473. initialData: undefined,
  474. gcTime: 0,
  475. enabled: !!version_id, // Only call API when both values are provided
  476. queryFn: async () => {
  477. if (!version_id) return undefined;
  478. const { data } = await agentService.fetchVersion(version_id);
  479. return data?.data ?? undefined;
  480. },
  481. });
  482. return { data, loading };
  483. };
  484. export const useFetchAgentAvatar = (): {
  485. data: IFlow;
  486. loading: boolean;
  487. refetch: () => void;
  488. } => {
  489. const { sharedId } = useGetSharedChatSearchParams();
  490. const {
  491. data,
  492. isFetching: loading,
  493. refetch,
  494. } = useQuery({
  495. queryKey: [AgentApiAction.FetchAgentAvatar],
  496. initialData: {} as IFlow,
  497. refetchOnReconnect: false,
  498. refetchOnMount: false,
  499. refetchOnWindowFocus: false,
  500. gcTime: 0,
  501. queryFn: async () => {
  502. if (!sharedId) return {};
  503. const { data } = await agentService.fetchAgentAvatar(sharedId);
  504. return data?.data ?? {};
  505. },
  506. });
  507. return { data, loading, refetch };
  508. };
  509. export const useFetchAgentLog = (searchParams: IAgentLogsRequest) => {
  510. const { id } = useParams();
  511. const { data, isFetching: loading } = useQuery<IAgentLogsResponse>({
  512. queryKey: ['fetchAgentLog', id, searchParams],
  513. initialData: {} as IAgentLogsResponse,
  514. gcTime: 0,
  515. queryFn: async () => {
  516. console.log('useFetchAgentLog', searchParams);
  517. const { data } = await fetchAgentLogsByCanvasId(id as string, {
  518. ...searchParams,
  519. });
  520. return data?.data ?? [];
  521. },
  522. });
  523. return { data, loading };
  524. };
  525. export const useFetchExternalAgentInputs = () => {
  526. const { sharedId } = useGetSharedChatSearchParams();
  527. const {
  528. data,
  529. isFetching: loading,
  530. refetch,
  531. } = useQuery<IInputs>({
  532. queryKey: [AgentApiAction.FetchExternalAgentInputs],
  533. initialData: {} as IInputs,
  534. refetchOnReconnect: false,
  535. refetchOnMount: false,
  536. refetchOnWindowFocus: false,
  537. gcTime: 0,
  538. enabled: !!sharedId,
  539. queryFn: async () => {
  540. const { data } = await agentService.fetchExternalAgentInputs(sharedId!);
  541. return data?.data ?? {};
  542. },
  543. });
  544. return { data, loading, refetch };
  545. };
  546. export const useSetAgentSetting = () => {
  547. const { id } = useParams();
  548. const queryClient = useQueryClient();
  549. const {
  550. data,
  551. isPending: loading,
  552. mutateAsync,
  553. } = useMutation({
  554. mutationKey: [AgentApiAction.SetAgentSetting],
  555. mutationFn: async (params: any) => {
  556. const ret = await agentService.settingCanvas({ id, ...params });
  557. if (ret?.data?.code === 0) {
  558. message.success('success');
  559. queryClient.invalidateQueries({
  560. queryKey: [AgentApiAction.FetchAgentDetail],
  561. });
  562. } else {
  563. message.error(ret?.data?.data);
  564. }
  565. return ret?.data?.code;
  566. },
  567. });
  568. return { data, loading, setAgentSetting: mutateAsync };
  569. };