您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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