hooks.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. import {
  2. useCallback,
  3. useEffect,
  4. useMemo,
  5. useRef,
  6. useState,
  7. } from 'react'
  8. import { useTranslation } from 'react-i18next'
  9. import { produce, setAutoFreeze } from 'immer'
  10. import { uniqBy } from 'lodash-es'
  11. import { useWorkflowRun } from '../../hooks'
  12. import { NodeRunningStatus, WorkflowRunningStatus } from '../../types'
  13. import { useWorkflowStore } from '../../store'
  14. import { DEFAULT_ITER_TIMES, DEFAULT_LOOP_TIMES } from '../../constants'
  15. import type {
  16. ChatItem,
  17. ChatItemInTree,
  18. Inputs,
  19. } from '@/app/components/base/chat/types'
  20. import type { InputForm } from '@/app/components/base/chat/chat/type'
  21. import {
  22. getProcessedInputs,
  23. processOpeningStatement,
  24. } from '@/app/components/base/chat/chat/utils'
  25. import { useToastContext } from '@/app/components/base/toast'
  26. import { TransferMethod } from '@/types/app'
  27. import {
  28. getProcessedFiles,
  29. getProcessedFilesFromResponse,
  30. } from '@/app/components/base/file-uploader/utils'
  31. import type { FileEntity } from '@/app/components/base/file-uploader/types'
  32. import { getThreadMessages } from '@/app/components/base/chat/utils'
  33. type GetAbortController = (abortController: AbortController) => void
  34. type SendCallback = {
  35. onGetSuggestedQuestions?: (responseItemId: string, getAbortController: GetAbortController) => Promise<any>
  36. }
  37. export const useChat = (
  38. config: any,
  39. formSettings?: {
  40. inputs: Inputs
  41. inputsForm: InputForm[]
  42. },
  43. prevChatTree?: ChatItemInTree[],
  44. stopChat?: (taskId: string) => void,
  45. ) => {
  46. const { t } = useTranslation()
  47. const { notify } = useToastContext()
  48. const { handleRun } = useWorkflowRun()
  49. const hasStopResponded = useRef(false)
  50. const workflowStore = useWorkflowStore()
  51. const conversationId = useRef('')
  52. const taskIdRef = useRef('')
  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. setLoopTimes,
  60. } = workflowStore.getState()
  61. const handleResponding = useCallback((isResponding: boolean) => {
  62. setIsResponding(isResponding)
  63. isRespondingRef.current = isResponding
  64. }, [])
  65. const [chatTree, setChatTree] = useState<ChatItemInTree[]>(prevChatTree || [])
  66. const chatTreeRef = useRef<ChatItemInTree[]>(chatTree)
  67. const [targetMessageId, setTargetMessageId] = useState<string>()
  68. const threadMessages = useMemo(() => getThreadMessages(chatTree, targetMessageId), [chatTree, targetMessageId])
  69. const getIntroduction = useCallback((str: string) => {
  70. return processOpeningStatement(str, formSettings?.inputs || {}, formSettings?.inputsForm || [])
  71. }, [formSettings?.inputs, formSettings?.inputsForm])
  72. /** Final chat list that will be rendered */
  73. const chatList = useMemo(() => {
  74. const ret = [...threadMessages]
  75. if (config?.opening_statement) {
  76. const index = threadMessages.findIndex(item => item.isOpeningStatement)
  77. if (index > -1) {
  78. ret[index] = {
  79. ...ret[index],
  80. content: getIntroduction(config.opening_statement),
  81. suggestedQuestions: config.suggested_questions,
  82. }
  83. }
  84. else {
  85. ret.unshift({
  86. id: `${Date.now()}`,
  87. content: getIntroduction(config.opening_statement),
  88. isAnswer: true,
  89. isOpeningStatement: true,
  90. suggestedQuestions: config.suggested_questions,
  91. })
  92. }
  93. }
  94. return ret
  95. }, [threadMessages, config?.opening_statement, getIntroduction, config?.suggested_questions])
  96. useEffect(() => {
  97. setAutoFreeze(false)
  98. return () => {
  99. setAutoFreeze(true)
  100. }
  101. }, [])
  102. /** Find the target node by bfs and then operate on it */
  103. const produceChatTreeNode = useCallback((targetId: string, operation: (node: ChatItemInTree) => void) => {
  104. return produce(chatTreeRef.current, (draft) => {
  105. const queue: ChatItemInTree[] = [...draft]
  106. while (queue.length > 0) {
  107. const current = queue.shift()!
  108. if (current.id === targetId) {
  109. operation(current)
  110. break
  111. }
  112. if (current.children)
  113. queue.push(...current.children)
  114. }
  115. })
  116. }, [])
  117. const handleStop = useCallback(() => {
  118. hasStopResponded.current = true
  119. handleResponding(false)
  120. if (stopChat && taskIdRef.current)
  121. stopChat(taskIdRef.current)
  122. setIterTimes(DEFAULT_ITER_TIMES)
  123. setLoopTimes(DEFAULT_LOOP_TIMES)
  124. if (suggestedQuestionsAbortControllerRef.current)
  125. suggestedQuestionsAbortControllerRef.current.abort()
  126. }, [handleResponding, setIterTimes, setLoopTimes, stopChat])
  127. const handleRestart = useCallback(() => {
  128. conversationId.current = ''
  129. taskIdRef.current = ''
  130. handleStop()
  131. setIterTimes(DEFAULT_ITER_TIMES)
  132. setLoopTimes(DEFAULT_LOOP_TIMES)
  133. setChatTree([])
  134. setSuggestQuestions([])
  135. }, [
  136. handleStop,
  137. setIterTimes,
  138. setLoopTimes,
  139. ])
  140. const updateCurrentQAOnTree = useCallback(({
  141. parentId,
  142. responseItem,
  143. placeholderQuestionId,
  144. questionItem,
  145. }: {
  146. parentId?: string
  147. responseItem: ChatItem
  148. placeholderQuestionId: string
  149. questionItem: ChatItem
  150. }) => {
  151. let nextState: ChatItemInTree[]
  152. const currentQA = { ...questionItem, children: [{ ...responseItem, children: [] }] }
  153. if (!parentId && !chatTree.some(item => [placeholderQuestionId, questionItem.id].includes(item.id))) {
  154. // QA whose parent is not provided is considered as a first message of the conversation,
  155. // and it should be a root node of the chat tree
  156. nextState = produce(chatTree, (draft) => {
  157. draft.push(currentQA)
  158. })
  159. }
  160. else {
  161. // find the target QA in the tree and update it; if not found, insert it to its parent node
  162. nextState = produceChatTreeNode(parentId!, (parentNode) => {
  163. const questionNodeIndex = parentNode.children!.findIndex(item => [placeholderQuestionId, questionItem.id].includes(item.id))
  164. if (questionNodeIndex === -1)
  165. parentNode.children!.push(currentQA)
  166. else
  167. parentNode.children![questionNodeIndex] = currentQA
  168. })
  169. }
  170. setChatTree(nextState)
  171. chatTreeRef.current = nextState
  172. }, [chatTree, produceChatTreeNode])
  173. const handleSend = useCallback((
  174. params: {
  175. query: string
  176. files?: FileEntity[]
  177. parent_message_id?: string
  178. [key: string]: any
  179. },
  180. {
  181. onGetSuggestedQuestions,
  182. }: SendCallback,
  183. ) => {
  184. if (isRespondingRef.current) {
  185. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  186. return false
  187. }
  188. const parentMessage = threadMessages.find(item => item.id === params.parent_message_id)
  189. const placeholderQuestionId = `question-${Date.now()}`
  190. const questionItem = {
  191. id: placeholderQuestionId,
  192. content: params.query,
  193. isAnswer: false,
  194. message_files: params.files,
  195. parentMessageId: params.parent_message_id,
  196. }
  197. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  198. const placeholderAnswerItem = {
  199. id: placeholderAnswerId,
  200. content: '',
  201. isAnswer: true,
  202. parentMessageId: questionItem.id,
  203. siblingIndex: parentMessage?.children?.length ?? chatTree.length,
  204. }
  205. setTargetMessageId(parentMessage?.id)
  206. updateCurrentQAOnTree({
  207. parentId: params.parent_message_id,
  208. responseItem: placeholderAnswerItem,
  209. placeholderQuestionId,
  210. questionItem,
  211. })
  212. // answer
  213. const responseItem: ChatItem = {
  214. id: placeholderAnswerId,
  215. content: '',
  216. agent_thoughts: [],
  217. message_files: [],
  218. isAnswer: true,
  219. parentMessageId: questionItem.id,
  220. siblingIndex: parentMessage?.children?.length ?? chatTree.length,
  221. }
  222. handleResponding(true)
  223. const { files, inputs, ...restParams } = params
  224. const bodyParams = {
  225. files: getProcessedFiles(files || []),
  226. inputs: getProcessedInputs(inputs || {}, formSettings?.inputsForm || []),
  227. ...restParams,
  228. }
  229. if (bodyParams?.files?.length) {
  230. bodyParams.files = bodyParams.files.map((item) => {
  231. if (item.transfer_method === TransferMethod.local_file) {
  232. return {
  233. ...item,
  234. url: '',
  235. }
  236. }
  237. return item
  238. })
  239. }
  240. let hasSetResponseId = false
  241. handleRun(
  242. bodyParams,
  243. {
  244. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  245. responseItem.content = responseItem.content + message
  246. if (messageId && !hasSetResponseId) {
  247. questionItem.id = `question-${messageId}`
  248. responseItem.id = messageId
  249. responseItem.parentMessageId = questionItem.id
  250. hasSetResponseId = true
  251. }
  252. if (isFirstMessage && newConversationId)
  253. conversationId.current = newConversationId
  254. taskIdRef.current = taskId
  255. if (messageId)
  256. responseItem.id = messageId
  257. updateCurrentQAOnTree({
  258. placeholderQuestionId,
  259. questionItem,
  260. responseItem,
  261. parentId: params.parent_message_id,
  262. })
  263. },
  264. async onCompleted(hasError?: boolean, errorMessage?: string) {
  265. handleResponding(false)
  266. if (hasError) {
  267. if (errorMessage) {
  268. responseItem.content = errorMessage
  269. responseItem.isError = true
  270. updateCurrentQAOnTree({
  271. placeholderQuestionId,
  272. questionItem,
  273. responseItem,
  274. parentId: params.parent_message_id,
  275. })
  276. }
  277. return
  278. }
  279. if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  280. try {
  281. const { data }: any = await onGetSuggestedQuestions(
  282. responseItem.id,
  283. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  284. )
  285. setSuggestQuestions(data)
  286. }
  287. // eslint-disable-next-line unused-imports/no-unused-vars
  288. catch (error) {
  289. setSuggestQuestions([])
  290. }
  291. }
  292. },
  293. onMessageEnd: (messageEnd) => {
  294. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  295. const processedFilesFromResponse = getProcessedFilesFromResponse(messageEnd.files || [])
  296. responseItem.allFiles = uniqBy([...(responseItem.allFiles || []), ...(processedFilesFromResponse || [])], 'id')
  297. updateCurrentQAOnTree({
  298. placeholderQuestionId,
  299. questionItem,
  300. responseItem,
  301. parentId: params.parent_message_id,
  302. })
  303. },
  304. onMessageReplace: (messageReplace) => {
  305. responseItem.content = messageReplace.answer
  306. },
  307. onError() {
  308. handleResponding(false)
  309. },
  310. onWorkflowStarted: ({ workflow_run_id, task_id }) => {
  311. taskIdRef.current = task_id
  312. responseItem.workflow_run_id = workflow_run_id
  313. responseItem.workflowProcess = {
  314. status: WorkflowRunningStatus.Running,
  315. tracing: [],
  316. }
  317. updateCurrentQAOnTree({
  318. placeholderQuestionId,
  319. questionItem,
  320. responseItem,
  321. parentId: params.parent_message_id,
  322. })
  323. },
  324. onWorkflowFinished: ({ data }) => {
  325. responseItem.workflowProcess!.status = data.status as WorkflowRunningStatus
  326. updateCurrentQAOnTree({
  327. placeholderQuestionId,
  328. questionItem,
  329. responseItem,
  330. parentId: params.parent_message_id,
  331. })
  332. },
  333. onIterationStart: ({ data }) => {
  334. responseItem.workflowProcess!.tracing!.push({
  335. ...data,
  336. status: NodeRunningStatus.Running,
  337. })
  338. updateCurrentQAOnTree({
  339. placeholderQuestionId,
  340. questionItem,
  341. responseItem,
  342. parentId: params.parent_message_id,
  343. })
  344. },
  345. onIterationFinish: ({ data }) => {
  346. const currentTracingIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.id === data.id)
  347. if (currentTracingIndex > -1) {
  348. responseItem.workflowProcess!.tracing[currentTracingIndex] = {
  349. ...responseItem.workflowProcess!.tracing[currentTracingIndex],
  350. ...data,
  351. }
  352. updateCurrentQAOnTree({
  353. placeholderQuestionId,
  354. questionItem,
  355. responseItem,
  356. parentId: params.parent_message_id,
  357. })
  358. }
  359. },
  360. onLoopStart: ({ data }) => {
  361. responseItem.workflowProcess!.tracing!.push({
  362. ...data,
  363. status: NodeRunningStatus.Running,
  364. })
  365. updateCurrentQAOnTree({
  366. placeholderQuestionId,
  367. questionItem,
  368. responseItem,
  369. parentId: params.parent_message_id,
  370. })
  371. },
  372. onLoopFinish: ({ data }) => {
  373. const currentTracingIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.id === data.id)
  374. if (currentTracingIndex > -1) {
  375. responseItem.workflowProcess!.tracing[currentTracingIndex] = {
  376. ...responseItem.workflowProcess!.tracing[currentTracingIndex],
  377. ...data,
  378. }
  379. updateCurrentQAOnTree({
  380. placeholderQuestionId,
  381. questionItem,
  382. responseItem,
  383. parentId: params.parent_message_id,
  384. })
  385. }
  386. },
  387. onNodeStarted: ({ data }) => {
  388. if (data.iteration_id || data.loop_id)
  389. return
  390. responseItem.workflowProcess!.tracing!.push({
  391. ...data,
  392. status: NodeRunningStatus.Running,
  393. } as any)
  394. updateCurrentQAOnTree({
  395. placeholderQuestionId,
  396. questionItem,
  397. responseItem,
  398. parentId: params.parent_message_id,
  399. })
  400. },
  401. onNodeRetry: ({ data }) => {
  402. if (data.iteration_id || data.loop_id)
  403. return
  404. responseItem.workflowProcess!.tracing!.push(data)
  405. updateCurrentQAOnTree({
  406. placeholderQuestionId,
  407. questionItem,
  408. responseItem,
  409. parentId: params.parent_message_id,
  410. })
  411. },
  412. onNodeFinished: ({ data }) => {
  413. if (data.iteration_id || data.loop_id)
  414. return
  415. const currentTracingIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.id === data.id)
  416. if (currentTracingIndex > -1) {
  417. responseItem.workflowProcess!.tracing[currentTracingIndex] = {
  418. ...responseItem.workflowProcess!.tracing[currentTracingIndex],
  419. ...data,
  420. }
  421. updateCurrentQAOnTree({
  422. placeholderQuestionId,
  423. questionItem,
  424. responseItem,
  425. parentId: params.parent_message_id,
  426. })
  427. }
  428. },
  429. onAgentLog: ({ data }) => {
  430. const currentNodeIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
  431. if (currentNodeIndex > -1) {
  432. const current = responseItem.workflowProcess!.tracing![currentNodeIndex]
  433. if (current.execution_metadata) {
  434. if (current.execution_metadata.agent_log) {
  435. const currentLogIndex = current.execution_metadata.agent_log.findIndex(log => log.id === data.id)
  436. if (currentLogIndex > -1) {
  437. current.execution_metadata.agent_log[currentLogIndex] = {
  438. ...current.execution_metadata.agent_log[currentLogIndex],
  439. ...data,
  440. }
  441. }
  442. else {
  443. current.execution_metadata.agent_log.push(data)
  444. }
  445. }
  446. else {
  447. current.execution_metadata.agent_log = [data]
  448. }
  449. }
  450. else {
  451. current.execution_metadata = {
  452. agent_log: [data],
  453. } as any
  454. }
  455. responseItem.workflowProcess!.tracing[currentNodeIndex] = {
  456. ...current,
  457. }
  458. updateCurrentQAOnTree({
  459. placeholderQuestionId,
  460. questionItem,
  461. responseItem,
  462. parentId: params.parent_message_id,
  463. })
  464. }
  465. },
  466. },
  467. )
  468. }, [threadMessages, chatTree.length, updateCurrentQAOnTree, handleResponding, formSettings?.inputsForm, handleRun, notify, t, config?.suggested_questions_after_answer?.enabled])
  469. return {
  470. conversationId: conversationId.current,
  471. chatList,
  472. setTargetMessageId,
  473. handleSend,
  474. handleStop,
  475. handleRestart,
  476. isResponding,
  477. suggestedQuestions,
  478. }
  479. }