hooks.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import {
  2. useCallback,
  3. useEffect,
  4. useRef,
  5. useState,
  6. } from 'react'
  7. import { useTranslation } from 'react-i18next'
  8. import { produce, setAutoFreeze } from 'immer'
  9. import { uniqBy } from 'lodash-es'
  10. import { useWorkflowRun } from '../../hooks'
  11. import { NodeRunningStatus, WorkflowRunningStatus } from '../../types'
  12. import { useWorkflowStore } from '../../store'
  13. import { DEFAULT_ITER_TIMES } from '../../constants'
  14. import type {
  15. ChatItem,
  16. Inputs,
  17. } from '@/app/components/base/chat/types'
  18. import type { InputForm } from '@/app/components/base/chat/chat/type'
  19. import {
  20. getProcessedInputs,
  21. processOpeningStatement,
  22. } from '@/app/components/base/chat/chat/utils'
  23. import { useToastContext } from '@/app/components/base/toast'
  24. import { TransferMethod } from '@/types/app'
  25. import {
  26. getProcessedFiles,
  27. getProcessedFilesFromResponse,
  28. } from '@/app/components/base/file-uploader/utils'
  29. import type { FileEntity } from '@/app/components/base/file-uploader/types'
  30. import type { NodeTracing } from '@/types/workflow'
  31. type GetAbortController = (abortController: AbortController) => void
  32. type SendCallback = {
  33. onGetSuggestedQuestions?: (responseItemId: string, getAbortController: GetAbortController) => Promise<any>
  34. }
  35. export const useChat = (
  36. config: any,
  37. formSettings?: {
  38. inputs: Inputs
  39. inputsForm: InputForm[]
  40. },
  41. prevChatList?: ChatItem[],
  42. stopChat?: (taskId: string) => void,
  43. ) => {
  44. const { t } = useTranslation()
  45. const { notify } = useToastContext()
  46. const { handleRun } = useWorkflowRun()
  47. const hasStopResponded = useRef(false)
  48. const workflowStore = useWorkflowStore()
  49. const conversationId = useRef('')
  50. const taskIdRef = useRef('')
  51. const [chatList, setChatList] = useState<ChatItem[]>(prevChatList || [])
  52. const chatListRef = useRef<ChatItem[]>(prevChatList || [])
  53. const [isResponding, setIsResponding] = useState(false)
  54. const isRespondingRef = useRef(false)
  55. const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
  56. const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null)
  57. const {
  58. setIterTimes,
  59. } = workflowStore.getState()
  60. useEffect(() => {
  61. setAutoFreeze(false)
  62. return () => {
  63. setAutoFreeze(true)
  64. }
  65. }, [])
  66. const handleUpdateChatList = useCallback((newChatList: ChatItem[]) => {
  67. setChatList(newChatList)
  68. chatListRef.current = newChatList
  69. }, [])
  70. const handleResponding = useCallback((isResponding: boolean) => {
  71. setIsResponding(isResponding)
  72. isRespondingRef.current = isResponding
  73. }, [])
  74. const getIntroduction = useCallback((str: string) => {
  75. return processOpeningStatement(str, formSettings?.inputs || {}, formSettings?.inputsForm || [])
  76. }, [formSettings?.inputs, formSettings?.inputsForm])
  77. useEffect(() => {
  78. if (config?.opening_statement) {
  79. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  80. const index = draft.findIndex(item => item.isOpeningStatement)
  81. if (index > -1) {
  82. draft[index] = {
  83. ...draft[index],
  84. content: getIntroduction(config.opening_statement),
  85. suggestedQuestions: config.suggested_questions,
  86. }
  87. }
  88. else {
  89. draft.unshift({
  90. id: `${Date.now()}`,
  91. content: getIntroduction(config.opening_statement),
  92. isAnswer: true,
  93. isOpeningStatement: true,
  94. suggestedQuestions: config.suggested_questions,
  95. })
  96. }
  97. }))
  98. }
  99. }, [config?.opening_statement, getIntroduction, config?.suggested_questions, handleUpdateChatList])
  100. const handleStop = useCallback(() => {
  101. hasStopResponded.current = true
  102. handleResponding(false)
  103. if (stopChat && taskIdRef.current)
  104. stopChat(taskIdRef.current)
  105. setIterTimes(DEFAULT_ITER_TIMES)
  106. if (suggestedQuestionsAbortControllerRef.current)
  107. suggestedQuestionsAbortControllerRef.current.abort()
  108. }, [handleResponding, setIterTimes, stopChat])
  109. const handleRestart = useCallback(() => {
  110. conversationId.current = ''
  111. taskIdRef.current = ''
  112. handleStop()
  113. setIterTimes(DEFAULT_ITER_TIMES)
  114. const newChatList = config?.opening_statement
  115. ? [{
  116. id: `${Date.now()}`,
  117. content: config.opening_statement,
  118. isAnswer: true,
  119. isOpeningStatement: true,
  120. suggestedQuestions: config.suggested_questions,
  121. }]
  122. : []
  123. handleUpdateChatList(newChatList)
  124. setSuggestQuestions([])
  125. }, [
  126. config,
  127. handleStop,
  128. handleUpdateChatList,
  129. setIterTimes,
  130. ])
  131. const updateCurrentQA = useCallback(({
  132. responseItem,
  133. questionId,
  134. placeholderAnswerId,
  135. questionItem,
  136. }: {
  137. responseItem: ChatItem
  138. questionId: string
  139. placeholderAnswerId: string
  140. questionItem: ChatItem
  141. }) => {
  142. const newListWithAnswer = produce(
  143. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  144. (draft) => {
  145. if (!draft.find(item => item.id === questionId))
  146. draft.push({ ...questionItem })
  147. draft.push({ ...responseItem })
  148. })
  149. handleUpdateChatList(newListWithAnswer)
  150. }, [handleUpdateChatList])
  151. const handleSend = useCallback((
  152. params: {
  153. query: string
  154. files?: FileEntity[]
  155. [key: string]: any
  156. },
  157. {
  158. onGetSuggestedQuestions,
  159. }: SendCallback,
  160. ) => {
  161. if (isRespondingRef.current) {
  162. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  163. return false
  164. }
  165. const questionId = `question-${Date.now()}`
  166. const questionItem = {
  167. id: questionId,
  168. content: params.query,
  169. isAnswer: false,
  170. message_files: params.files,
  171. }
  172. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  173. const placeholderAnswerItem = {
  174. id: placeholderAnswerId,
  175. content: '',
  176. isAnswer: true,
  177. }
  178. const newList = [...chatListRef.current, questionItem, placeholderAnswerItem]
  179. handleUpdateChatList(newList)
  180. // answer
  181. const responseItem: ChatItem = {
  182. id: placeholderAnswerId,
  183. content: '',
  184. agent_thoughts: [],
  185. message_files: [],
  186. isAnswer: true,
  187. }
  188. handleResponding(true)
  189. const { files, inputs, ...restParams } = params
  190. const bodyParams = {
  191. files: getProcessedFiles(files || []),
  192. inputs: getProcessedInputs(inputs || {}, formSettings?.inputsForm || []),
  193. ...restParams,
  194. }
  195. if (bodyParams?.files?.length) {
  196. bodyParams.files = bodyParams.files.map((item) => {
  197. if (item.transfer_method === TransferMethod.local_file) {
  198. return {
  199. ...item,
  200. url: '',
  201. }
  202. }
  203. return item
  204. })
  205. }
  206. let hasSetResponseId = false
  207. handleRun(
  208. bodyParams,
  209. {
  210. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  211. responseItem.content = responseItem.content + message
  212. if (messageId && !hasSetResponseId) {
  213. responseItem.id = messageId
  214. hasSetResponseId = true
  215. }
  216. if (isFirstMessage && newConversationId)
  217. conversationId.current = newConversationId
  218. taskIdRef.current = taskId
  219. if (messageId)
  220. responseItem.id = messageId
  221. updateCurrentQA({
  222. responseItem,
  223. questionId,
  224. placeholderAnswerId,
  225. questionItem,
  226. })
  227. },
  228. async onCompleted(hasError?: boolean, errorMessage?: string) {
  229. handleResponding(false)
  230. if (hasError) {
  231. if (errorMessage) {
  232. responseItem.content = errorMessage
  233. responseItem.isError = true
  234. const newListWithAnswer = produce(
  235. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  236. (draft) => {
  237. if (!draft.find(item => item.id === questionId))
  238. draft.push({ ...questionItem })
  239. draft.push({ ...responseItem })
  240. })
  241. handleUpdateChatList(newListWithAnswer)
  242. }
  243. return
  244. }
  245. if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  246. try {
  247. const { data }: any = await onGetSuggestedQuestions(
  248. responseItem.id,
  249. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  250. )
  251. setSuggestQuestions(data)
  252. }
  253. catch (error) {
  254. setSuggestQuestions([])
  255. }
  256. }
  257. },
  258. onMessageEnd: (messageEnd) => {
  259. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  260. const processedFilesFromResponse = getProcessedFilesFromResponse(messageEnd.files || [])
  261. responseItem.allFiles = uniqBy([...(responseItem.allFiles || []), ...(processedFilesFromResponse || [])], 'id')
  262. const newListWithAnswer = produce(
  263. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  264. (draft) => {
  265. if (!draft.find(item => item.id === questionId))
  266. draft.push({ ...questionItem })
  267. draft.push({ ...responseItem })
  268. })
  269. handleUpdateChatList(newListWithAnswer)
  270. },
  271. onMessageReplace: (messageReplace) => {
  272. responseItem.content = messageReplace.answer
  273. },
  274. onError() {
  275. handleResponding(false)
  276. },
  277. onWorkflowStarted: ({ workflow_run_id, task_id }) => {
  278. taskIdRef.current = task_id
  279. responseItem.workflow_run_id = workflow_run_id
  280. responseItem.workflowProcess = {
  281. status: WorkflowRunningStatus.Running,
  282. tracing: [],
  283. }
  284. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  285. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  286. draft[currentIndex] = {
  287. ...draft[currentIndex],
  288. ...responseItem,
  289. }
  290. }))
  291. },
  292. onWorkflowFinished: ({ data }) => {
  293. responseItem.workflowProcess!.status = data.status as WorkflowRunningStatus
  294. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  295. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  296. draft[currentIndex] = {
  297. ...draft[currentIndex],
  298. ...responseItem,
  299. }
  300. }))
  301. },
  302. onIterationStart: ({ data }) => {
  303. responseItem.workflowProcess!.tracing!.push({
  304. ...data,
  305. status: NodeRunningStatus.Running,
  306. details: [],
  307. } as any)
  308. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  309. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  310. draft[currentIndex] = {
  311. ...draft[currentIndex],
  312. ...responseItem,
  313. }
  314. }))
  315. },
  316. onIterationNext: ({ data }) => {
  317. const tracing = responseItem.workflowProcess!.tracing!
  318. const iterations = tracing.find(item => item.node_id === data.node_id
  319. && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
  320. iterations.details!.push([])
  321. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  322. const currentIndex = draft.length - 1
  323. draft[currentIndex] = responseItem
  324. }))
  325. },
  326. onIterationFinish: ({ data }) => {
  327. const tracing = responseItem.workflowProcess!.tracing!
  328. const iterationsIndex = tracing.findIndex(item => item.node_id === data.node_id
  329. && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
  330. tracing[iterationsIndex] = {
  331. ...tracing[iterationsIndex],
  332. ...data,
  333. status: NodeRunningStatus.Succeeded,
  334. } as any
  335. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  336. const currentIndex = draft.length - 1
  337. draft[currentIndex] = responseItem
  338. }))
  339. },
  340. onNodeStarted: ({ data }) => {
  341. if (data.iteration_id)
  342. return
  343. responseItem.workflowProcess!.tracing!.push({
  344. ...data,
  345. status: NodeRunningStatus.Running,
  346. } as any)
  347. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  348. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  349. draft[currentIndex] = {
  350. ...draft[currentIndex],
  351. ...responseItem,
  352. }
  353. }))
  354. },
  355. onNodeRetry: ({ data }) => {
  356. if (data.iteration_id)
  357. return
  358. const currentIndex = responseItem.workflowProcess!.tracing!.findIndex((item) => {
  359. if (!item.execution_metadata?.parallel_id)
  360. return item.node_id === data.node_id
  361. return item.node_id === data.node_id && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id)
  362. })
  363. if (responseItem.workflowProcess!.tracing[currentIndex].retryDetail)
  364. responseItem.workflowProcess!.tracing[currentIndex].retryDetail?.push(data as NodeTracing)
  365. else
  366. responseItem.workflowProcess!.tracing[currentIndex].retryDetail = [data as NodeTracing]
  367. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  368. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  369. draft[currentIndex] = {
  370. ...draft[currentIndex],
  371. ...responseItem,
  372. }
  373. }))
  374. },
  375. onNodeFinished: ({ data }) => {
  376. if (data.iteration_id)
  377. return
  378. const currentIndex = responseItem.workflowProcess!.tracing!.findIndex((item) => {
  379. if (!item.execution_metadata?.parallel_id)
  380. return item.node_id === data.node_id
  381. return item.node_id === data.node_id && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id)
  382. })
  383. responseItem.workflowProcess!.tracing[currentIndex] = {
  384. ...(responseItem.workflowProcess!.tracing[currentIndex]?.extras
  385. ? { extras: responseItem.workflowProcess!.tracing[currentIndex].extras }
  386. : {}),
  387. ...(responseItem.workflowProcess!.tracing[currentIndex]?.retryDetail
  388. ? { retryDetail: responseItem.workflowProcess!.tracing[currentIndex].retryDetail }
  389. : {}),
  390. ...data,
  391. } as any
  392. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  393. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  394. draft[currentIndex] = {
  395. ...draft[currentIndex],
  396. ...responseItem,
  397. }
  398. }))
  399. },
  400. },
  401. )
  402. }, [handleRun, handleResponding, handleUpdateChatList, notify, t, updateCurrentQA, config.suggested_questions_after_answer?.enabled, formSettings])
  403. return {
  404. conversationId: conversationId.current,
  405. chatList,
  406. chatListRef,
  407. handleUpdateChatList,
  408. handleSend,
  409. handleStop,
  410. handleRestart,
  411. isResponding,
  412. suggestedQuestions,
  413. }
  414. }