hooks.ts 14 KB

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