hooks.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. log: [
  291. ...newResponseItem.message,
  292. ...(newResponseItem.message[newResponseItem.message.length - 1].role !== 'assistant'
  293. ? [
  294. {
  295. role: 'assistant',
  296. text: newResponseItem.answer,
  297. files: newResponseItem.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  298. },
  299. ]
  300. : []),
  301. ],
  302. more: {
  303. time: dayjs.unix(newResponseItem.created_at).format('hh:mm A'),
  304. tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
  305. latency: newResponseItem.provider_response_latency.toFixed(2),
  306. },
  307. }
  308. }
  309. })
  310. handleUpdateChatList(newChatList)
  311. }
  312. if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  313. const { data }: any = await onGetSuggestedQuestions(
  314. responseItem.id,
  315. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  316. )
  317. setSuggestQuestions(data)
  318. }
  319. },
  320. onFile(file) {
  321. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  322. if (lastThought)
  323. responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(lastThought as any).message_files, file]
  324. updateCurrentQA({
  325. responseItem,
  326. questionId,
  327. placeholderAnswerId,
  328. questionItem,
  329. })
  330. },
  331. onThought(thought) {
  332. isAgentMode = true
  333. const response = responseItem as any
  334. if (thought.message_id && !hasSetResponseId)
  335. response.id = thought.message_id
  336. if (response.agent_thoughts.length === 0) {
  337. response.agent_thoughts.push(thought)
  338. }
  339. else {
  340. const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
  341. // thought changed but still the same thought, so update.
  342. if (lastThought.id === thought.id) {
  343. thought.thought = lastThought.thought
  344. thought.message_files = lastThought.message_files
  345. responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
  346. }
  347. else {
  348. responseItem.agent_thoughts!.push(thought)
  349. }
  350. }
  351. updateCurrentQA({
  352. responseItem,
  353. questionId,
  354. placeholderAnswerId,
  355. questionItem,
  356. })
  357. },
  358. onMessageEnd: (messageEnd) => {
  359. if (messageEnd.metadata?.annotation_reply) {
  360. responseItem.id = messageEnd.id
  361. responseItem.annotation = ({
  362. id: messageEnd.metadata.annotation_reply.id,
  363. authorName: messageEnd.metadata.annotation_reply.account.name,
  364. })
  365. const baseState = chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId)
  366. const newListWithAnswer = produce(
  367. baseState,
  368. (draft) => {
  369. if (!draft.find(item => item.id === questionId))
  370. draft.push({ ...questionItem })
  371. draft.push({
  372. ...responseItem,
  373. })
  374. })
  375. handleUpdateChatList(newListWithAnswer)
  376. return
  377. }
  378. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  379. const newListWithAnswer = produce(
  380. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  381. (draft) => {
  382. if (!draft.find(item => item.id === questionId))
  383. draft.push({ ...questionItem })
  384. draft.push({ ...responseItem })
  385. })
  386. handleUpdateChatList(newListWithAnswer)
  387. },
  388. onMessageReplace: (messageReplace) => {
  389. responseItem.content = messageReplace.answer
  390. },
  391. onError() {
  392. handleResponding(false)
  393. const newChatList = produce(chatListRef.current, (draft) => {
  394. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  395. })
  396. handleUpdateChatList(newChatList)
  397. },
  398. onWorkflowStarted: ({ workflow_run_id, task_id }) => {
  399. taskIdRef.current = task_id
  400. responseItem.workflow_run_id = workflow_run_id
  401. responseItem.workflowProcess = {
  402. status: WorkflowRunningStatus.Running,
  403. tracing: [],
  404. }
  405. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  406. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  407. draft[currentIndex] = {
  408. ...draft[currentIndex],
  409. ...responseItem,
  410. }
  411. }))
  412. },
  413. onWorkflowFinished: ({ data }) => {
  414. responseItem.workflowProcess!.status = data.status as WorkflowRunningStatus
  415. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  416. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  417. draft[currentIndex] = {
  418. ...draft[currentIndex],
  419. ...responseItem,
  420. }
  421. }))
  422. },
  423. onNodeStarted: ({ data }) => {
  424. responseItem.workflowProcess!.tracing!.push(data as any)
  425. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  426. const currentIndex = draft.findIndex(item => item.id === responseItem.id)
  427. draft[currentIndex] = {
  428. ...draft[currentIndex],
  429. ...responseItem,
  430. }
  431. }))
  432. },
  433. onNodeFinished: ({ data }) => {
  434. const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
  435. responseItem.workflowProcess!.tracing[currentIndex] = data 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. })
  445. return true
  446. }, [
  447. checkPromptVariables,
  448. config?.suggested_questions_after_answer,
  449. updateCurrentQA,
  450. t,
  451. notify,
  452. promptVariablesConfig,
  453. handleUpdateChatList,
  454. handleResponding,
  455. ])
  456. const handleAnnotationEdited = useCallback((query: string, answer: string, index: number) => {
  457. handleUpdateChatList(chatListRef.current.map((item, i) => {
  458. if (i === index - 1) {
  459. return {
  460. ...item,
  461. content: query,
  462. }
  463. }
  464. if (i === index) {
  465. return {
  466. ...item,
  467. content: answer,
  468. annotation: {
  469. ...item.annotation,
  470. logAnnotation: undefined,
  471. } as any,
  472. }
  473. }
  474. return item
  475. }))
  476. }, [handleUpdateChatList])
  477. const handleAnnotationAdded = useCallback((annotationId: string, authorName: string, query: string, answer: string, index: number) => {
  478. handleUpdateChatList(chatListRef.current.map((item, i) => {
  479. if (i === index - 1) {
  480. return {
  481. ...item,
  482. content: query,
  483. }
  484. }
  485. if (i === index) {
  486. const answerItem = {
  487. ...item,
  488. content: item.content,
  489. annotation: {
  490. id: annotationId,
  491. authorName,
  492. logAnnotation: {
  493. content: answer,
  494. account: {
  495. id: '',
  496. name: authorName,
  497. email: '',
  498. },
  499. },
  500. } as Annotation,
  501. }
  502. return answerItem
  503. }
  504. return item
  505. }))
  506. }, [handleUpdateChatList])
  507. const handleAnnotationRemoved = useCallback((index: number) => {
  508. handleUpdateChatList(chatListRef.current.map((item, i) => {
  509. if (i === index) {
  510. return {
  511. ...item,
  512. content: item.content,
  513. annotation: {
  514. ...(item.annotation || {}),
  515. id: '',
  516. } as Annotation,
  517. }
  518. }
  519. return item
  520. }))
  521. }, [handleUpdateChatList])
  522. return {
  523. chatList,
  524. setChatList,
  525. conversationId: connversationId.current,
  526. isResponding,
  527. setIsResponding,
  528. handleSend,
  529. suggestedQuestions,
  530. handleRestart,
  531. handleStop,
  532. handleAnnotationEdited,
  533. handleAnnotationAdded,
  534. handleAnnotationRemoved,
  535. }
  536. }