hooks.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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 type {
  10. ChatConfig,
  11. ChatItem,
  12. Inputs,
  13. PromptVariable,
  14. VisionFile,
  15. } from '../types'
  16. import { TransferMethod } from '@/types/app'
  17. import { useToastContext } from '@/app/components/base/toast'
  18. import { ssePost } from '@/service/base'
  19. import { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
  20. import type { Annotation } from '@/models/log'
  21. import { WorkflowRunningStatus } from '@/app/components/workflow/types'
  22. import useTimestamp from '@/hooks/use-timestamp'
  23. type GetAbortController = (abortController: AbortController) => void
  24. type SendCallback = {
  25. onGetConvesationMessages?: (conversationId: string, getAbortController: GetAbortController) => Promise<any>
  26. onGetSuggestedQuestions?: (responseItemId: string, getAbortController: GetAbortController) => Promise<any>
  27. onConversationComplete?: (conversationId: string) => void
  28. isPublicAPI?: boolean
  29. }
  30. export const useCheckPromptVariables = () => {
  31. const { t } = useTranslation()
  32. const { notify } = useToastContext()
  33. const checkPromptVariables = useCallback((promptVariablesConfig: {
  34. inputs: Inputs
  35. promptVariables: PromptVariable[]
  36. }) => {
  37. const {
  38. promptVariables,
  39. inputs,
  40. } = promptVariablesConfig
  41. let hasEmptyInput = ''
  42. const requiredVars = promptVariables.filter(({ key, name, required, type }) => {
  43. if (type !== 'string' && type !== 'paragraph' && type !== 'select')
  44. return false
  45. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  46. return res
  47. })
  48. if (requiredVars?.length) {
  49. requiredVars.forEach(({ key, name }) => {
  50. if (hasEmptyInput)
  51. return
  52. if (!inputs[key])
  53. hasEmptyInput = name
  54. })
  55. }
  56. if (hasEmptyInput) {
  57. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  58. return false
  59. }
  60. }, [notify, t])
  61. return checkPromptVariables
  62. }
  63. export const useChat = (
  64. config?: ChatConfig,
  65. promptVariablesConfig?: {
  66. inputs: Inputs
  67. promptVariables: PromptVariable[]
  68. },
  69. prevChatList?: ChatItem[],
  70. stopChat?: (taskId: string) => void,
  71. ) => {
  72. const { t } = useTranslation()
  73. const { formatTime } = useTimestamp()
  74. const { notify } = useToastContext()
  75. const connversationId = useRef('')
  76. const hasStopResponded = useRef(false)
  77. const [isResponding, setIsResponding] = useState(false)
  78. const isRespondingRef = useRef(false)
  79. const [chatList, setChatList] = useState<ChatItem[]>(prevChatList || [])
  80. const chatListRef = useRef<ChatItem[]>(prevChatList || [])
  81. const taskIdRef = useRef('')
  82. const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
  83. const conversationMessagesAbortControllerRef = useRef<AbortController | null>(null)
  84. const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null)
  85. const checkPromptVariables = useCheckPromptVariables()
  86. useEffect(() => {
  87. setAutoFreeze(false)
  88. return () => {
  89. setAutoFreeze(true)
  90. }
  91. }, [])
  92. const handleUpdateChatList = useCallback((newChatList: ChatItem[]) => {
  93. setChatList(newChatList)
  94. chatListRef.current = newChatList
  95. }, [])
  96. const handleResponding = useCallback((isResponding: boolean) => {
  97. setIsResponding(isResponding)
  98. isRespondingRef.current = isResponding
  99. }, [])
  100. const getIntroduction = useCallback((str: string) => {
  101. return replaceStringWithValues(str, promptVariablesConfig?.promptVariables || [], promptVariablesConfig?.inputs || {})
  102. }, [promptVariablesConfig?.inputs, promptVariablesConfig?.promptVariables])
  103. useEffect(() => {
  104. if (config?.opening_statement) {
  105. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  106. const index = draft.findIndex(item => item.isOpeningStatement)
  107. if (index > -1) {
  108. draft[index] = {
  109. ...draft[index],
  110. content: getIntroduction(config.opening_statement),
  111. suggestedQuestions: config.suggested_questions,
  112. }
  113. }
  114. else {
  115. draft.unshift({
  116. id: `${Date.now()}`,
  117. content: getIntroduction(config.opening_statement),
  118. isAnswer: true,
  119. isOpeningStatement: true,
  120. suggestedQuestions: config.suggested_questions,
  121. })
  122. }
  123. }))
  124. }
  125. }, [config?.opening_statement, getIntroduction, config?.suggested_questions, handleUpdateChatList])
  126. const handleStop = useCallback(() => {
  127. hasStopResponded.current = true
  128. handleResponding(false)
  129. if (stopChat && taskIdRef.current)
  130. stopChat(taskIdRef.current)
  131. if (conversationMessagesAbortControllerRef.current)
  132. conversationMessagesAbortControllerRef.current.abort()
  133. if (suggestedQuestionsAbortControllerRef.current)
  134. suggestedQuestionsAbortControllerRef.current.abort()
  135. }, [stopChat, handleResponding])
  136. const handleRestart = useCallback(() => {
  137. connversationId.current = ''
  138. taskIdRef.current = ''
  139. handleStop()
  140. const newChatList = config?.opening_statement
  141. ? [{
  142. id: `${Date.now()}`,
  143. content: config.opening_statement,
  144. isAnswer: true,
  145. isOpeningStatement: true,
  146. suggestedQuestions: config.suggested_questions,
  147. }]
  148. : []
  149. handleUpdateChatList(newChatList)
  150. setSuggestQuestions([])
  151. }, [
  152. config,
  153. handleStop,
  154. handleUpdateChatList,
  155. ])
  156. const updateCurrentQA = useCallback(({
  157. responseItem,
  158. questionId,
  159. placeholderAnswerId,
  160. questionItem,
  161. }: {
  162. responseItem: ChatItem
  163. questionId: string
  164. placeholderAnswerId: string
  165. questionItem: ChatItem
  166. }) => {
  167. const newListWithAnswer = produce(
  168. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  169. (draft) => {
  170. if (!draft.find(item => item.id === questionId))
  171. draft.push({ ...questionItem })
  172. draft.push({ ...responseItem })
  173. })
  174. handleUpdateChatList(newListWithAnswer)
  175. }, [handleUpdateChatList])
  176. const handleSend = useCallback(async (
  177. url: string,
  178. data: any,
  179. {
  180. onGetConvesationMessages,
  181. onGetSuggestedQuestions,
  182. onConversationComplete,
  183. isPublicAPI,
  184. }: SendCallback,
  185. ) => {
  186. setSuggestQuestions([])
  187. if (isRespondingRef.current) {
  188. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  189. return false
  190. }
  191. if (promptVariablesConfig?.inputs && promptVariablesConfig?.promptVariables)
  192. checkPromptVariables(promptVariablesConfig)
  193. const questionId = `question-${Date.now()}`
  194. const questionItem = {
  195. id: questionId,
  196. content: data.query,
  197. isAnswer: false,
  198. message_files: data.files,
  199. }
  200. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  201. const placeholderAnswerItem = {
  202. id: placeholderAnswerId,
  203. content: '',
  204. isAnswer: true,
  205. }
  206. const newList = [...chatListRef.current, questionItem, placeholderAnswerItem]
  207. handleUpdateChatList(newList)
  208. // answer
  209. const responseItem: ChatItem = {
  210. id: placeholderAnswerId,
  211. content: '',
  212. agent_thoughts: [],
  213. message_files: [],
  214. isAnswer: true,
  215. }
  216. let isInIteration = false
  217. handleResponding(true)
  218. hasStopResponded.current = false
  219. const bodyParams = {
  220. response_mode: 'streaming',
  221. conversation_id: connversationId.current,
  222. ...data,
  223. }
  224. if (bodyParams?.files?.length) {
  225. bodyParams.files = bodyParams.files.map((item: VisionFile) => {
  226. if (item.transfer_method === TransferMethod.local_file) {
  227. return {
  228. ...item,
  229. url: '',
  230. }
  231. }
  232. return item
  233. })
  234. }
  235. let isAgentMode = false
  236. let hasSetResponseId = false
  237. ssePost(
  238. url,
  239. {
  240. body: bodyParams,
  241. },
  242. {
  243. isPublicAPI,
  244. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  245. if (!isAgentMode) {
  246. responseItem.content = responseItem.content + message
  247. }
  248. else {
  249. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  250. if (lastThought)
  251. lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
  252. }
  253. if (messageId && !hasSetResponseId) {
  254. responseItem.id = messageId
  255. hasSetResponseId = true
  256. }
  257. if (isFirstMessage && newConversationId)
  258. connversationId.current = newConversationId
  259. taskIdRef.current = taskId
  260. if (messageId)
  261. responseItem.id = messageId
  262. updateCurrentQA({
  263. responseItem,
  264. questionId,
  265. placeholderAnswerId,
  266. questionItem,
  267. })
  268. },
  269. async onCompleted(hasError?: boolean) {
  270. handleResponding(false)
  271. if (hasError)
  272. return
  273. if (onConversationComplete)
  274. onConversationComplete(connversationId.current)
  275. if (connversationId.current && !hasStopResponded.current && onGetConvesationMessages) {
  276. const { data }: any = await onGetConvesationMessages(
  277. connversationId.current,
  278. newAbortController => conversationMessagesAbortControllerRef.current = newAbortController,
  279. )
  280. const newResponseItem = data.find((item: any) => item.id === responseItem.id)
  281. if (!newResponseItem)
  282. return
  283. const newChatList = produce(chatListRef.current, (draft) => {
  284. const index = draft.findIndex(item => item.id === responseItem.id)
  285. if (index !== -1) {
  286. const requestion = draft[index - 1]
  287. draft[index - 1] = {
  288. ...requestion,
  289. }
  290. draft[index] = {
  291. ...draft[index],
  292. content: newResponseItem.answer,
  293. log: [
  294. ...newResponseItem.message,
  295. ...(newResponseItem.message[newResponseItem.message.length - 1].role !== 'assistant'
  296. ? [
  297. {
  298. role: 'assistant',
  299. text: newResponseItem.answer,
  300. files: newResponseItem.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  301. },
  302. ]
  303. : []),
  304. ],
  305. more: {
  306. time: formatTime(newResponseItem.created_at, 'hh:mm A'),
  307. tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
  308. latency: newResponseItem.provider_response_latency.toFixed(2),
  309. },
  310. // for agent log
  311. conversationId: connversationId.current,
  312. input: {
  313. inputs: newResponseItem.inputs,
  314. query: newResponseItem.query,
  315. },
  316. }
  317. }
  318. })
  319. handleUpdateChatList(newChatList)
  320. }
  321. if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  322. const { data }: any = await onGetSuggestedQuestions(
  323. responseItem.id,
  324. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  325. )
  326. setSuggestQuestions(data)
  327. }
  328. },
  329. onFile(file) {
  330. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  331. if (lastThought)
  332. responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(lastThought as any).message_files, file]
  333. updateCurrentQA({
  334. responseItem,
  335. questionId,
  336. placeholderAnswerId,
  337. questionItem,
  338. })
  339. },
  340. onThought(thought) {
  341. isAgentMode = true
  342. const response = responseItem as any
  343. if (thought.message_id && !hasSetResponseId)
  344. response.id = thought.message_id
  345. if (response.agent_thoughts.length === 0) {
  346. response.agent_thoughts.push(thought)
  347. }
  348. else {
  349. const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
  350. // thought changed but still the same thought, so update.
  351. if (lastThought.id === thought.id) {
  352. thought.thought = lastThought.thought
  353. thought.message_files = lastThought.message_files
  354. responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
  355. }
  356. else {
  357. responseItem.agent_thoughts!.push(thought)
  358. }
  359. }
  360. updateCurrentQA({
  361. responseItem,
  362. questionId,
  363. placeholderAnswerId,
  364. questionItem,
  365. })
  366. },
  367. onMessageEnd: (messageEnd) => {
  368. if (messageEnd.metadata?.annotation_reply) {
  369. responseItem.id = messageEnd.id
  370. responseItem.annotation = ({
  371. id: messageEnd.metadata.annotation_reply.id,
  372. authorName: messageEnd.metadata.annotation_reply.account.name,
  373. })
  374. const baseState = chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId)
  375. const newListWithAnswer = produce(
  376. baseState,
  377. (draft) => {
  378. if (!draft.find(item => item.id === questionId))
  379. draft.push({ ...questionItem })
  380. draft.push({
  381. ...responseItem,
  382. })
  383. })
  384. handleUpdateChatList(newListWithAnswer)
  385. return
  386. }
  387. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  388. const newListWithAnswer = produce(
  389. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  390. (draft) => {
  391. if (!draft.find(item => item.id === questionId))
  392. draft.push({ ...questionItem })
  393. draft.push({ ...responseItem })
  394. })
  395. handleUpdateChatList(newListWithAnswer)
  396. },
  397. onMessageReplace: (messageReplace) => {
  398. responseItem.content = messageReplace.answer
  399. },
  400. onError() {
  401. handleResponding(false)
  402. const newChatList = produce(chatListRef.current, (draft) => {
  403. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  404. })
  405. handleUpdateChatList(newChatList)
  406. },
  407. onWorkflowStarted: ({ workflow_run_id, task_id }) => {
  408. taskIdRef.current = task_id
  409. responseItem.workflow_run_id = workflow_run_id
  410. responseItem.workflowProcess = {
  411. status: WorkflowRunningStatus.Running,
  412. tracing: [],
  413. }
  414. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  415. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  416. draft[currentIndex] = {
  417. ...draft[currentIndex],
  418. ...responseItem,
  419. }
  420. }))
  421. },
  422. onWorkflowFinished: ({ data }) => {
  423. responseItem.workflowProcess!.status = data.status as WorkflowRunningStatus
  424. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  425. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  426. draft[currentIndex] = {
  427. ...draft[currentIndex],
  428. ...responseItem,
  429. }
  430. }))
  431. },
  432. onIterationStart: ({ data }) => {
  433. responseItem.workflowProcess!.tracing!.push({
  434. ...data,
  435. status: WorkflowRunningStatus.Running,
  436. } as any)
  437. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  438. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  439. draft[currentIndex] = {
  440. ...draft[currentIndex],
  441. ...responseItem,
  442. }
  443. }))
  444. isInIteration = true
  445. },
  446. onIterationFinish: ({ data }) => {
  447. const tracing = responseItem.workflowProcess!.tracing!
  448. tracing[tracing.length - 1] = {
  449. ...tracing[tracing.length - 1],
  450. ...data,
  451. status: WorkflowRunningStatus.Succeeded,
  452. } as any
  453. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  454. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  455. draft[currentIndex] = {
  456. ...draft[currentIndex],
  457. ...responseItem,
  458. }
  459. }))
  460. isInIteration = false
  461. },
  462. onNodeStarted: ({ data }) => {
  463. if (isInIteration)
  464. return
  465. responseItem.workflowProcess!.tracing!.push({
  466. ...data,
  467. status: WorkflowRunningStatus.Running,
  468. } as any)
  469. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  470. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  471. draft[currentIndex] = {
  472. ...draft[currentIndex],
  473. ...responseItem,
  474. }
  475. }))
  476. },
  477. onNodeFinished: ({ data }) => {
  478. if (isInIteration)
  479. return
  480. const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
  481. responseItem.workflowProcess!.tracing[currentIndex] = data as any
  482. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  483. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  484. draft[currentIndex] = {
  485. ...draft[currentIndex],
  486. ...responseItem,
  487. }
  488. }))
  489. },
  490. })
  491. return true
  492. }, [
  493. checkPromptVariables,
  494. config?.suggested_questions_after_answer,
  495. updateCurrentQA,
  496. t,
  497. notify,
  498. promptVariablesConfig,
  499. handleUpdateChatList,
  500. handleResponding,
  501. formatTime,
  502. ])
  503. const handleAnnotationEdited = useCallback((query: string, answer: string, index: number) => {
  504. handleUpdateChatList(chatListRef.current.map((item, i) => {
  505. if (i === index - 1) {
  506. return {
  507. ...item,
  508. content: query,
  509. }
  510. }
  511. if (i === index) {
  512. return {
  513. ...item,
  514. content: answer,
  515. annotation: {
  516. ...item.annotation,
  517. logAnnotation: undefined,
  518. } as any,
  519. }
  520. }
  521. return item
  522. }))
  523. }, [handleUpdateChatList])
  524. const handleAnnotationAdded = useCallback((annotationId: string, authorName: string, query: string, answer: string, index: number) => {
  525. handleUpdateChatList(chatListRef.current.map((item, i) => {
  526. if (i === index - 1) {
  527. return {
  528. ...item,
  529. content: query,
  530. }
  531. }
  532. if (i === index) {
  533. const answerItem = {
  534. ...item,
  535. content: item.content,
  536. annotation: {
  537. id: annotationId,
  538. authorName,
  539. logAnnotation: {
  540. content: answer,
  541. account: {
  542. id: '',
  543. name: authorName,
  544. email: '',
  545. },
  546. },
  547. } as Annotation,
  548. }
  549. return answerItem
  550. }
  551. return item
  552. }))
  553. }, [handleUpdateChatList])
  554. const handleAnnotationRemoved = useCallback((index: number) => {
  555. handleUpdateChatList(chatListRef.current.map((item, i) => {
  556. if (i === index) {
  557. return {
  558. ...item,
  559. content: item.content,
  560. annotation: {
  561. ...(item.annotation || {}),
  562. id: '',
  563. } as Annotation,
  564. }
  565. }
  566. return item
  567. }))
  568. }, [handleUpdateChatList])
  569. return {
  570. chatList,
  571. setChatList,
  572. conversationId: connversationId.current,
  573. isResponding,
  574. setIsResponding,
  575. handleSend,
  576. suggestedQuestions,
  577. handleRestart,
  578. handleStop,
  579. handleAnnotationEdited,
  580. handleAnnotationAdded,
  581. handleAnnotationRemoved,
  582. }
  583. }