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 { 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. let isInIteration = false
  167. handleResponding(true)
  168. const bodyParams = {
  169. conversation_id: conversationId.current,
  170. ...params,
  171. }
  172. if (bodyParams?.files?.length) {
  173. bodyParams.files = bodyParams.files.map((item: VisionFile) => {
  174. if (item.transfer_method === TransferMethod.local_file) {
  175. return {
  176. ...item,
  177. url: '',
  178. }
  179. }
  180. return item
  181. })
  182. }
  183. let hasSetResponseId = false
  184. handleRun(
  185. params,
  186. {
  187. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  188. responseItem.content = responseItem.content + message
  189. if (messageId && !hasSetResponseId) {
  190. responseItem.id = messageId
  191. hasSetResponseId = true
  192. }
  193. if (isFirstMessage && newConversationId)
  194. conversationId.current = newConversationId
  195. taskIdRef.current = taskId
  196. if (messageId)
  197. responseItem.id = messageId
  198. updateCurrentQA({
  199. responseItem,
  200. questionId,
  201. placeholderAnswerId,
  202. questionItem,
  203. })
  204. },
  205. async onCompleted(hasError?: boolean, errorMessage?: string) {
  206. handleResponding(false)
  207. if (hasError) {
  208. if (errorMessage) {
  209. responseItem.content = errorMessage
  210. responseItem.isError = true
  211. const newListWithAnswer = produce(
  212. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  213. (draft) => {
  214. if (!draft.find(item => item.id === questionId))
  215. draft.push({ ...questionItem })
  216. draft.push({ ...responseItem })
  217. })
  218. handleUpdateChatList(newListWithAnswer)
  219. }
  220. return
  221. }
  222. if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  223. const { data }: any = await onGetSuggestedQuestions(
  224. responseItem.id,
  225. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  226. )
  227. setSuggestQuestions(data)
  228. }
  229. },
  230. onMessageEnd: (messageEnd) => {
  231. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  232. const newListWithAnswer = produce(
  233. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  234. (draft) => {
  235. if (!draft.find(item => item.id === questionId))
  236. draft.push({ ...questionItem })
  237. draft.push({ ...responseItem })
  238. })
  239. handleUpdateChatList(newListWithAnswer)
  240. },
  241. onMessageReplace: (messageReplace) => {
  242. responseItem.content = messageReplace.answer
  243. },
  244. onError() {
  245. handleResponding(false)
  246. },
  247. onWorkflowStarted: ({ workflow_run_id, task_id }) => {
  248. taskIdRef.current = task_id
  249. responseItem.workflow_run_id = workflow_run_id
  250. responseItem.workflowProcess = {
  251. status: WorkflowRunningStatus.Running,
  252. tracing: [],
  253. }
  254. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  255. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  256. draft[currentIndex] = {
  257. ...draft[currentIndex],
  258. ...responseItem,
  259. }
  260. }))
  261. },
  262. onWorkflowFinished: ({ data }) => {
  263. responseItem.workflowProcess!.status = data.status as WorkflowRunningStatus
  264. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  265. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  266. draft[currentIndex] = {
  267. ...draft[currentIndex],
  268. ...responseItem,
  269. }
  270. }))
  271. },
  272. onIterationStart: ({ data }) => {
  273. responseItem.workflowProcess!.tracing!.push({
  274. ...data,
  275. status: NodeRunningStatus.Running,
  276. details: [],
  277. } as any)
  278. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  279. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  280. draft[currentIndex] = {
  281. ...draft[currentIndex],
  282. ...responseItem,
  283. }
  284. }))
  285. isInIteration = true
  286. },
  287. onIterationNext: () => {
  288. const tracing = responseItem.workflowProcess!.tracing!
  289. const iterations = tracing[tracing.length - 1]
  290. iterations.details!.push([])
  291. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  292. const currentIndex = draft.length - 1
  293. draft[currentIndex] = responseItem
  294. }))
  295. },
  296. onIterationFinish: ({ data }) => {
  297. const tracing = responseItem.workflowProcess!.tracing!
  298. const iterations = tracing[tracing.length - 1]
  299. tracing[tracing.length - 1] = {
  300. ...iterations,
  301. ...data,
  302. status: NodeRunningStatus.Succeeded,
  303. } as any
  304. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  305. const currentIndex = draft.length - 1
  306. draft[currentIndex] = responseItem
  307. }))
  308. isInIteration = false
  309. },
  310. onNodeStarted: ({ data }) => {
  311. if (isInIteration) {
  312. const tracing = responseItem.workflowProcess!.tracing!
  313. const iterations = tracing[tracing.length - 1]
  314. const currIteration = iterations.details![iterations.details!.length - 1]
  315. currIteration.push({
  316. ...data,
  317. status: NodeRunningStatus.Running,
  318. } as any)
  319. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  320. const currentIndex = draft.length - 1
  321. draft[currentIndex] = responseItem
  322. }))
  323. }
  324. else {
  325. responseItem.workflowProcess!.tracing!.push({
  326. ...data,
  327. status: NodeRunningStatus.Running,
  328. } as any)
  329. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  330. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  331. draft[currentIndex] = {
  332. ...draft[currentIndex],
  333. ...responseItem,
  334. }
  335. }))
  336. }
  337. },
  338. onNodeFinished: ({ data }) => {
  339. if (isInIteration) {
  340. const tracing = responseItem.workflowProcess!.tracing!
  341. const iterations = tracing[tracing.length - 1]
  342. const currIteration = iterations.details![iterations.details!.length - 1]
  343. currIteration[currIteration.length - 1] = {
  344. ...data,
  345. status: NodeRunningStatus.Succeeded,
  346. } as any
  347. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  348. const currentIndex = draft.length - 1
  349. draft[currentIndex] = responseItem
  350. }))
  351. }
  352. else {
  353. const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
  354. responseItem.workflowProcess!.tracing[currentIndex] = {
  355. ...(responseItem.workflowProcess!.tracing[currentIndex].extras
  356. ? { extras: responseItem.workflowProcess!.tracing[currentIndex].extras }
  357. : {}),
  358. ...data,
  359. } as any
  360. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  361. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  362. draft[currentIndex] = {
  363. ...draft[currentIndex],
  364. ...responseItem,
  365. }
  366. }))
  367. }
  368. },
  369. },
  370. )
  371. }, [handleRun, handleResponding, handleUpdateChatList, notify, t, updateCurrentQA, config.suggested_questions_after_answer?.enabled])
  372. return {
  373. conversationId: conversationId.current,
  374. chatList,
  375. handleSend,
  376. handleStop,
  377. handleRestart,
  378. isResponding,
  379. suggestedQuestions,
  380. }
  381. }