hooks.ts 14 KB

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