hooks.ts 13 KB

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