hooks.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. handleResponding(true)
  217. hasStopResponded.current = false
  218. const bodyParams = {
  219. response_mode: 'streaming',
  220. conversation_id: connversationId.current,
  221. ...data,
  222. }
  223. if (bodyParams?.files?.length) {
  224. bodyParams.files = bodyParams.files.map((item: VisionFile) => {
  225. if (item.transfer_method === TransferMethod.local_file) {
  226. return {
  227. ...item,
  228. url: '',
  229. }
  230. }
  231. return item
  232. })
  233. }
  234. let isAgentMode = false
  235. let hasSetResponseId = false
  236. ssePost(
  237. url,
  238. {
  239. body: bodyParams,
  240. },
  241. {
  242. isPublicAPI,
  243. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  244. if (!isAgentMode) {
  245. responseItem.content = responseItem.content + message
  246. }
  247. else {
  248. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  249. if (lastThought)
  250. lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
  251. }
  252. if (messageId && !hasSetResponseId) {
  253. responseItem.id = messageId
  254. hasSetResponseId = true
  255. }
  256. if (isFirstMessage && newConversationId)
  257. connversationId.current = newConversationId
  258. taskIdRef.current = taskId
  259. if (messageId)
  260. responseItem.id = messageId
  261. updateCurrentQA({
  262. responseItem,
  263. questionId,
  264. placeholderAnswerId,
  265. questionItem,
  266. })
  267. },
  268. async onCompleted(hasError?: boolean) {
  269. handleResponding(false)
  270. if (hasError)
  271. return
  272. if (onConversationComplete)
  273. onConversationComplete(connversationId.current)
  274. if (connversationId.current && !hasStopResponded.current && onGetConvesationMessages) {
  275. const { data }: any = await onGetConvesationMessages(
  276. connversationId.current,
  277. newAbortController => conversationMessagesAbortControllerRef.current = newAbortController,
  278. )
  279. const newResponseItem = data.find((item: any) => item.id === responseItem.id)
  280. if (!newResponseItem)
  281. return
  282. const newChatList = produce(chatListRef.current, (draft) => {
  283. const index = draft.findIndex(item => item.id === responseItem.id)
  284. if (index !== -1) {
  285. const requestion = draft[index - 1]
  286. draft[index - 1] = {
  287. ...requestion,
  288. }
  289. draft[index] = {
  290. ...draft[index],
  291. content: newResponseItem.answer,
  292. log: [
  293. ...newResponseItem.message,
  294. ...(newResponseItem.message[newResponseItem.message.length - 1].role !== 'assistant'
  295. ? [
  296. {
  297. role: 'assistant',
  298. text: newResponseItem.answer,
  299. files: newResponseItem.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  300. },
  301. ]
  302. : []),
  303. ],
  304. more: {
  305. time: formatTime(newResponseItem.created_at, 'hh:mm A'),
  306. tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
  307. latency: newResponseItem.provider_response_latency.toFixed(2),
  308. },
  309. // for agent log
  310. conversationId: connversationId.current,
  311. input: {
  312. inputs: newResponseItem.inputs,
  313. query: newResponseItem.query,
  314. },
  315. }
  316. }
  317. })
  318. handleUpdateChatList(newChatList)
  319. }
  320. if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  321. const { data }: any = await onGetSuggestedQuestions(
  322. responseItem.id,
  323. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  324. )
  325. setSuggestQuestions(data)
  326. }
  327. },
  328. onFile(file) {
  329. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  330. if (lastThought)
  331. responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(lastThought as any).message_files, file]
  332. updateCurrentQA({
  333. responseItem,
  334. questionId,
  335. placeholderAnswerId,
  336. questionItem,
  337. })
  338. },
  339. onThought(thought) {
  340. isAgentMode = true
  341. const response = responseItem as any
  342. if (thought.message_id && !hasSetResponseId)
  343. response.id = thought.message_id
  344. if (response.agent_thoughts.length === 0) {
  345. response.agent_thoughts.push(thought)
  346. }
  347. else {
  348. const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
  349. // thought changed but still the same thought, so update.
  350. if (lastThought.id === thought.id) {
  351. thought.thought = lastThought.thought
  352. thought.message_files = lastThought.message_files
  353. responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
  354. }
  355. else {
  356. responseItem.agent_thoughts!.push(thought)
  357. }
  358. }
  359. updateCurrentQA({
  360. responseItem,
  361. questionId,
  362. placeholderAnswerId,
  363. questionItem,
  364. })
  365. },
  366. onMessageEnd: (messageEnd) => {
  367. if (messageEnd.metadata?.annotation_reply) {
  368. responseItem.id = messageEnd.id
  369. responseItem.annotation = ({
  370. id: messageEnd.metadata.annotation_reply.id,
  371. authorName: messageEnd.metadata.annotation_reply.account.name,
  372. })
  373. const baseState = chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId)
  374. const newListWithAnswer = produce(
  375. baseState,
  376. (draft) => {
  377. if (!draft.find(item => item.id === questionId))
  378. draft.push({ ...questionItem })
  379. draft.push({
  380. ...responseItem,
  381. })
  382. })
  383. handleUpdateChatList(newListWithAnswer)
  384. return
  385. }
  386. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  387. const newListWithAnswer = produce(
  388. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  389. (draft) => {
  390. if (!draft.find(item => item.id === questionId))
  391. draft.push({ ...questionItem })
  392. draft.push({ ...responseItem })
  393. })
  394. handleUpdateChatList(newListWithAnswer)
  395. },
  396. onMessageReplace: (messageReplace) => {
  397. responseItem.content = messageReplace.answer
  398. },
  399. onError() {
  400. handleResponding(false)
  401. const newChatList = produce(chatListRef.current, (draft) => {
  402. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  403. })
  404. handleUpdateChatList(newChatList)
  405. },
  406. onWorkflowStarted: ({ workflow_run_id, task_id }) => {
  407. taskIdRef.current = task_id
  408. responseItem.workflow_run_id = workflow_run_id
  409. responseItem.workflowProcess = {
  410. status: WorkflowRunningStatus.Running,
  411. tracing: [],
  412. }
  413. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  414. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  415. draft[currentIndex] = {
  416. ...draft[currentIndex],
  417. ...responseItem,
  418. }
  419. }))
  420. },
  421. onWorkflowFinished: ({ data }) => {
  422. responseItem.workflowProcess!.status = data.status as WorkflowRunningStatus
  423. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  424. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  425. draft[currentIndex] = {
  426. ...draft[currentIndex],
  427. ...responseItem,
  428. }
  429. }))
  430. },
  431. onNodeStarted: ({ data }) => {
  432. responseItem.workflowProcess!.tracing!.push({
  433. ...data,
  434. status: WorkflowRunningStatus.Running,
  435. } as any)
  436. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  437. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  438. draft[currentIndex] = {
  439. ...draft[currentIndex],
  440. ...responseItem,
  441. }
  442. }))
  443. },
  444. onNodeFinished: ({ data }) => {
  445. const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
  446. responseItem.workflowProcess!.tracing[currentIndex] = data as any
  447. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  448. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  449. draft[currentIndex] = {
  450. ...draft[currentIndex],
  451. ...responseItem,
  452. }
  453. }))
  454. },
  455. })
  456. return true
  457. }, [
  458. checkPromptVariables,
  459. config?.suggested_questions_after_answer,
  460. updateCurrentQA,
  461. t,
  462. notify,
  463. promptVariablesConfig,
  464. handleUpdateChatList,
  465. handleResponding,
  466. formatTime,
  467. ])
  468. const handleAnnotationEdited = useCallback((query: string, answer: string, index: number) => {
  469. handleUpdateChatList(chatListRef.current.map((item, i) => {
  470. if (i === index - 1) {
  471. return {
  472. ...item,
  473. content: query,
  474. }
  475. }
  476. if (i === index) {
  477. return {
  478. ...item,
  479. content: answer,
  480. annotation: {
  481. ...item.annotation,
  482. logAnnotation: undefined,
  483. } as any,
  484. }
  485. }
  486. return item
  487. }))
  488. }, [handleUpdateChatList])
  489. const handleAnnotationAdded = useCallback((annotationId: string, authorName: string, query: string, answer: string, index: number) => {
  490. handleUpdateChatList(chatListRef.current.map((item, i) => {
  491. if (i === index - 1) {
  492. return {
  493. ...item,
  494. content: query,
  495. }
  496. }
  497. if (i === index) {
  498. const answerItem = {
  499. ...item,
  500. content: item.content,
  501. annotation: {
  502. id: annotationId,
  503. authorName,
  504. logAnnotation: {
  505. content: answer,
  506. account: {
  507. id: '',
  508. name: authorName,
  509. email: '',
  510. },
  511. },
  512. } as Annotation,
  513. }
  514. return answerItem
  515. }
  516. return item
  517. }))
  518. }, [handleUpdateChatList])
  519. const handleAnnotationRemoved = useCallback((index: number) => {
  520. handleUpdateChatList(chatListRef.current.map((item, i) => {
  521. if (i === index) {
  522. return {
  523. ...item,
  524. content: item.content,
  525. annotation: {
  526. ...(item.annotation || {}),
  527. id: '',
  528. } as Annotation,
  529. }
  530. }
  531. return item
  532. }))
  533. }, [handleUpdateChatList])
  534. return {
  535. chatList,
  536. setChatList,
  537. conversationId: connversationId.current,
  538. isResponding,
  539. setIsResponding,
  540. handleSend,
  541. suggestedQuestions,
  542. handleRestart,
  543. handleStop,
  544. handleAnnotationEdited,
  545. handleAnnotationAdded,
  546. handleAnnotationRemoved,
  547. }
  548. }