hooks.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. try {
  224. const { data }: any = await onGetSuggestedQuestions(
  225. responseItem.id,
  226. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  227. )
  228. setSuggestQuestions(data)
  229. }
  230. catch (error) {
  231. setSuggestQuestions([])
  232. }
  233. }
  234. },
  235. onMessageEnd: (messageEnd) => {
  236. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  237. const newListWithAnswer = produce(
  238. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  239. (draft) => {
  240. if (!draft.find(item => item.id === questionId))
  241. draft.push({ ...questionItem })
  242. draft.push({ ...responseItem })
  243. })
  244. handleUpdateChatList(newListWithAnswer)
  245. },
  246. onMessageReplace: (messageReplace) => {
  247. responseItem.content = messageReplace.answer
  248. },
  249. onError() {
  250. handleResponding(false)
  251. },
  252. onWorkflowStarted: ({ workflow_run_id, task_id }) => {
  253. taskIdRef.current = task_id
  254. responseItem.workflow_run_id = workflow_run_id
  255. responseItem.workflowProcess = {
  256. status: WorkflowRunningStatus.Running,
  257. tracing: [],
  258. }
  259. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  260. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  261. draft[currentIndex] = {
  262. ...draft[currentIndex],
  263. ...responseItem,
  264. }
  265. }))
  266. },
  267. onWorkflowFinished: ({ data }) => {
  268. responseItem.workflowProcess!.status = data.status as WorkflowRunningStatus
  269. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  270. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  271. draft[currentIndex] = {
  272. ...draft[currentIndex],
  273. ...responseItem,
  274. }
  275. }))
  276. },
  277. onIterationStart: ({ data }) => {
  278. responseItem.workflowProcess!.tracing!.push({
  279. ...data,
  280. status: NodeRunningStatus.Running,
  281. details: [],
  282. } as any)
  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. isInIteration = true
  291. },
  292. onIterationNext: () => {
  293. const tracing = responseItem.workflowProcess!.tracing!
  294. const iterations = tracing[tracing.length - 1]
  295. iterations.details!.push([])
  296. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  297. const currentIndex = draft.length - 1
  298. draft[currentIndex] = responseItem
  299. }))
  300. },
  301. onIterationFinish: ({ data }) => {
  302. const tracing = responseItem.workflowProcess!.tracing!
  303. const iterations = tracing[tracing.length - 1]
  304. tracing[tracing.length - 1] = {
  305. ...iterations,
  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. isInIteration = false
  314. },
  315. onNodeStarted: ({ data }) => {
  316. if (isInIteration) {
  317. const tracing = responseItem.workflowProcess!.tracing!
  318. const iterations = tracing[tracing.length - 1]
  319. const currIteration = iterations.details![iterations.details!.length - 1]
  320. currIteration.push({
  321. ...data,
  322. status: NodeRunningStatus.Running,
  323. } as any)
  324. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  325. const currentIndex = draft.length - 1
  326. draft[currentIndex] = responseItem
  327. }))
  328. }
  329. else {
  330. responseItem.workflowProcess!.tracing!.push({
  331. ...data,
  332. status: NodeRunningStatus.Running,
  333. } as any)
  334. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  335. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  336. draft[currentIndex] = {
  337. ...draft[currentIndex],
  338. ...responseItem,
  339. }
  340. }))
  341. }
  342. },
  343. onNodeFinished: ({ data }) => {
  344. if (isInIteration) {
  345. const tracing = responseItem.workflowProcess!.tracing!
  346. const iterations = tracing[tracing.length - 1]
  347. const currIteration = iterations.details![iterations.details!.length - 1]
  348. currIteration[currIteration.length - 1] = {
  349. ...data,
  350. status: NodeRunningStatus.Succeeded,
  351. } as any
  352. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  353. const currentIndex = draft.length - 1
  354. draft[currentIndex] = responseItem
  355. }))
  356. }
  357. else {
  358. const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
  359. responseItem.workflowProcess!.tracing[currentIndex] = {
  360. ...(responseItem.workflowProcess!.tracing[currentIndex].extras
  361. ? { extras: responseItem.workflowProcess!.tracing[currentIndex].extras }
  362. : {}),
  363. ...data,
  364. } as any
  365. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  366. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  367. draft[currentIndex] = {
  368. ...draft[currentIndex],
  369. ...responseItem,
  370. }
  371. }))
  372. }
  373. },
  374. },
  375. )
  376. }, [handleRun, handleResponding, handleUpdateChatList, notify, t, updateCurrentQA, config.suggested_questions_after_answer?.enabled])
  377. return {
  378. conversationId: conversationId.current,
  379. chatList,
  380. handleSend,
  381. handleStop,
  382. handleRestart,
  383. isResponding,
  384. suggestedQuestions,
  385. }
  386. }