hooks.ts 19 KB

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