hooks.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. type GetAbortController = (abortController: AbortController) => void
  23. type SendCallback = {
  24. onGetConvesationMessages?: (conversationId: string, getAbortController: GetAbortController) => Promise<any>
  25. onGetSuggestedQuestions?: (responseItemId: string, getAbortController: GetAbortController) => Promise<any>
  26. onConversationComplete?: (conversationId: string) => void
  27. isPublicAPI?: boolean
  28. }
  29. export const useCheckPromptVariables = () => {
  30. const { t } = useTranslation()
  31. const { notify } = useToastContext()
  32. const checkPromptVariables = useCallback((promptVariablesConfig: {
  33. inputs: Inputs
  34. promptVariables: PromptVariable[]
  35. }) => {
  36. const {
  37. promptVariables,
  38. inputs,
  39. } = promptVariablesConfig
  40. let hasEmptyInput = ''
  41. const requiredVars = promptVariables.filter(({ key, name, required, type }) => {
  42. if (type !== 'string' && type !== 'paragraph' && type !== 'select')
  43. return false
  44. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  45. return res
  46. })
  47. if (requiredVars?.length) {
  48. requiredVars.forEach(({ key, name }) => {
  49. if (hasEmptyInput)
  50. return
  51. if (!inputs[key])
  52. hasEmptyInput = name
  53. })
  54. }
  55. if (hasEmptyInput) {
  56. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  57. return false
  58. }
  59. }, [notify, t])
  60. return checkPromptVariables
  61. }
  62. export const useChat = (
  63. config?: ChatConfig,
  64. promptVariablesConfig?: {
  65. inputs: Inputs
  66. promptVariables: PromptVariable[]
  67. },
  68. prevChatList?: ChatItem[],
  69. stopChat?: (taskId: string) => void,
  70. ) => {
  71. const { t } = useTranslation()
  72. const { notify } = useToastContext()
  73. const connversationId = useRef('')
  74. const hasStopResponded = useRef(false)
  75. const [isResponsing, setIsResponsing] = useState(false)
  76. const isResponsingRef = useRef(false)
  77. const [chatList, setChatList] = useState<ChatItem[]>(prevChatList || [])
  78. const chatListRef = useRef<ChatItem[]>(prevChatList || [])
  79. const taskIdRef = useRef('')
  80. const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
  81. const conversationMessagesAbortControllerRef = useRef<AbortController | null>(null)
  82. const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null)
  83. const checkPromptVariables = useCheckPromptVariables()
  84. useEffect(() => {
  85. setAutoFreeze(false)
  86. return () => {
  87. setAutoFreeze(true)
  88. }
  89. }, [])
  90. const handleUpdateChatList = useCallback((newChatList: ChatItem[]) => {
  91. setChatList(newChatList)
  92. chatListRef.current = newChatList
  93. }, [])
  94. const handleResponsing = useCallback((isResponsing: boolean) => {
  95. setIsResponsing(isResponsing)
  96. isResponsingRef.current = isResponsing
  97. }, [])
  98. const getIntroduction = useCallback((str: string) => {
  99. return replaceStringWithValues(str, promptVariablesConfig?.promptVariables || [], promptVariablesConfig?.inputs || {})
  100. }, [promptVariablesConfig?.inputs, promptVariablesConfig?.promptVariables])
  101. useEffect(() => {
  102. if (config?.opening_statement) {
  103. handleUpdateChatList(produce(chatListRef.current, (draft) => {
  104. const index = draft.findIndex(item => item.isOpeningStatement)
  105. if (index > -1) {
  106. draft[index] = {
  107. ...draft[index],
  108. content: getIntroduction(config.opening_statement),
  109. suggestedQuestions: config.suggested_questions,
  110. }
  111. }
  112. else {
  113. draft.unshift({
  114. id: `${Date.now()}`,
  115. content: getIntroduction(config.opening_statement),
  116. isAnswer: true,
  117. isOpeningStatement: true,
  118. suggestedQuestions: config.suggested_questions,
  119. })
  120. }
  121. }))
  122. }
  123. }, [config?.opening_statement, getIntroduction, config?.suggested_questions, handleUpdateChatList])
  124. const handleStop = useCallback(() => {
  125. hasStopResponded.current = true
  126. handleResponsing(false)
  127. if (stopChat && taskIdRef.current)
  128. stopChat(taskIdRef.current)
  129. if (conversationMessagesAbortControllerRef.current)
  130. conversationMessagesAbortControllerRef.current.abort()
  131. if (suggestedQuestionsAbortControllerRef.current)
  132. suggestedQuestionsAbortControllerRef.current.abort()
  133. }, [stopChat, handleResponsing])
  134. const handleRestart = useCallback(() => {
  135. connversationId.current = ''
  136. taskIdRef.current = ''
  137. handleStop()
  138. const newChatList = config?.opening_statement
  139. ? [{
  140. id: `${Date.now()}`,
  141. content: config.opening_statement,
  142. isAnswer: true,
  143. isOpeningStatement: true,
  144. suggestedQuestions: config.suggested_questions,
  145. }]
  146. : []
  147. handleUpdateChatList(newChatList)
  148. setSuggestQuestions([])
  149. }, [
  150. config,
  151. handleStop,
  152. handleUpdateChatList,
  153. ])
  154. const updateCurrentQA = useCallback(({
  155. responseItem,
  156. questionId,
  157. placeholderAnswerId,
  158. questionItem,
  159. }: {
  160. responseItem: ChatItem
  161. questionId: string
  162. placeholderAnswerId: string
  163. questionItem: ChatItem
  164. }) => {
  165. const newListWithAnswer = produce(
  166. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  167. (draft) => {
  168. if (!draft.find(item => item.id === questionId))
  169. draft.push({ ...questionItem })
  170. draft.push({ ...responseItem })
  171. })
  172. handleUpdateChatList(newListWithAnswer)
  173. }, [handleUpdateChatList])
  174. const handleSend = useCallback(async (
  175. url: string,
  176. data: any,
  177. {
  178. onGetConvesationMessages,
  179. onGetSuggestedQuestions,
  180. onConversationComplete,
  181. isPublicAPI,
  182. }: SendCallback,
  183. ) => {
  184. setSuggestQuestions([])
  185. if (isResponsingRef.current) {
  186. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  187. return false
  188. }
  189. if (promptVariablesConfig?.inputs && promptVariablesConfig?.promptVariables)
  190. checkPromptVariables(promptVariablesConfig)
  191. const questionId = `question-${Date.now()}`
  192. const questionItem = {
  193. id: questionId,
  194. content: data.query,
  195. isAnswer: false,
  196. message_files: data.files,
  197. }
  198. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  199. const placeholderAnswerItem = {
  200. id: placeholderAnswerId,
  201. content: '',
  202. isAnswer: true,
  203. }
  204. const newList = [...chatListRef.current, questionItem, placeholderAnswerItem]
  205. handleUpdateChatList(newList)
  206. // answer
  207. const responseItem: ChatItem = {
  208. id: `${Date.now()}`,
  209. content: '',
  210. agent_thoughts: [],
  211. message_files: [],
  212. isAnswer: true,
  213. }
  214. handleResponsing(true)
  215. hasStopResponded.current = false
  216. const bodyParams = {
  217. response_mode: 'streaming',
  218. conversation_id: connversationId.current,
  219. ...data,
  220. }
  221. if (bodyParams?.files?.length) {
  222. bodyParams.files = bodyParams.files.map((item: VisionFile) => {
  223. if (item.transfer_method === TransferMethod.local_file) {
  224. return {
  225. ...item,
  226. url: '',
  227. }
  228. }
  229. return item
  230. })
  231. }
  232. let isAgentMode = false
  233. let hasSetResponseId = false
  234. ssePost(
  235. url,
  236. {
  237. body: bodyParams,
  238. },
  239. {
  240. isPublicAPI,
  241. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  242. if (!isAgentMode) {
  243. responseItem.content = responseItem.content + message
  244. }
  245. else {
  246. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  247. if (lastThought)
  248. lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
  249. }
  250. if (messageId && !hasSetResponseId) {
  251. responseItem.id = messageId
  252. hasSetResponseId = true
  253. }
  254. if (isFirstMessage && newConversationId)
  255. connversationId.current = newConversationId
  256. taskIdRef.current = taskId
  257. if (messageId)
  258. responseItem.id = messageId
  259. updateCurrentQA({
  260. responseItem,
  261. questionId,
  262. placeholderAnswerId,
  263. questionItem,
  264. })
  265. },
  266. async onCompleted(hasError?: boolean) {
  267. handleResponsing(false)
  268. if (hasError)
  269. return
  270. if (onConversationComplete)
  271. onConversationComplete(connversationId.current)
  272. if (connversationId.current && !hasStopResponded.current && onGetConvesationMessages) {
  273. const { data }: any = await onGetConvesationMessages(
  274. connversationId.current,
  275. newAbortController => conversationMessagesAbortControllerRef.current = newAbortController,
  276. )
  277. const newResponseItem = data.find((item: any) => item.id === responseItem.id)
  278. if (!newResponseItem)
  279. return
  280. const newChatList = produce(chatListRef.current, (draft) => {
  281. const index = draft.findIndex(item => item.id === responseItem.id)
  282. if (index !== -1) {
  283. const requestion = draft[index - 1]
  284. draft[index - 1] = {
  285. ...requestion,
  286. log: newResponseItem.message,
  287. }
  288. draft[index] = {
  289. ...draft[index],
  290. more: {
  291. time: dayjs.unix(newResponseItem.created_at).format('hh:mm A'),
  292. tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
  293. latency: newResponseItem.provider_response_latency.toFixed(2),
  294. },
  295. }
  296. }
  297. })
  298. handleUpdateChatList(newChatList)
  299. }
  300. if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  301. const { data }: any = await onGetSuggestedQuestions(
  302. responseItem.id,
  303. newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
  304. )
  305. setSuggestQuestions(data)
  306. }
  307. },
  308. onFile(file) {
  309. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  310. if (lastThought)
  311. responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(lastThought as any).message_files, file]
  312. updateCurrentQA({
  313. responseItem,
  314. questionId,
  315. placeholderAnswerId,
  316. questionItem,
  317. })
  318. },
  319. onThought(thought) {
  320. isAgentMode = true
  321. const response = responseItem as any
  322. if (thought.message_id && !hasSetResponseId)
  323. response.id = thought.message_id
  324. if (response.agent_thoughts.length === 0) {
  325. response.agent_thoughts.push(thought)
  326. }
  327. else {
  328. const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
  329. // thought changed but still the same thought, so update.
  330. if (lastThought.id === thought.id) {
  331. thought.thought = lastThought.thought
  332. thought.message_files = lastThought.message_files
  333. responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
  334. }
  335. else {
  336. responseItem.agent_thoughts!.push(thought)
  337. }
  338. }
  339. updateCurrentQA({
  340. responseItem,
  341. questionId,
  342. placeholderAnswerId,
  343. questionItem,
  344. })
  345. },
  346. onMessageEnd: (messageEnd) => {
  347. if (messageEnd.metadata?.annotation_reply) {
  348. responseItem.id = messageEnd.id
  349. responseItem.annotation = ({
  350. id: messageEnd.metadata.annotation_reply.id,
  351. authorName: messageEnd.metadata.annotation_reply.account.name,
  352. })
  353. const baseState = chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId)
  354. const newListWithAnswer = produce(
  355. baseState,
  356. (draft) => {
  357. if (!draft.find(item => item.id === questionId))
  358. draft.push({ ...questionItem })
  359. draft.push({
  360. ...responseItem,
  361. })
  362. })
  363. handleUpdateChatList(newListWithAnswer)
  364. return
  365. }
  366. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  367. const newListWithAnswer = produce(
  368. chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  369. (draft) => {
  370. if (!draft.find(item => item.id === questionId))
  371. draft.push({ ...questionItem })
  372. draft.push({ ...responseItem })
  373. })
  374. handleUpdateChatList(newListWithAnswer)
  375. },
  376. onMessageReplace: (messageReplace) => {
  377. responseItem.content = messageReplace.answer
  378. },
  379. onError() {
  380. handleResponsing(false)
  381. const newChatList = produce(chatListRef.current, (draft) => {
  382. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  383. })
  384. handleUpdateChatList(newChatList)
  385. },
  386. })
  387. return true
  388. }, [
  389. checkPromptVariables,
  390. config?.suggested_questions_after_answer,
  391. updateCurrentQA,
  392. t,
  393. notify,
  394. promptVariablesConfig,
  395. handleUpdateChatList,
  396. handleResponsing,
  397. ])
  398. const handleAnnotationEdited = useCallback((query: string, answer: string, index: number) => {
  399. handleUpdateChatList(chatListRef.current.map((item, i) => {
  400. if (i === index - 1) {
  401. return {
  402. ...item,
  403. content: query,
  404. }
  405. }
  406. if (i === index) {
  407. return {
  408. ...item,
  409. content: answer,
  410. annotation: {
  411. ...item.annotation,
  412. logAnnotation: undefined,
  413. } as any,
  414. }
  415. }
  416. return item
  417. }))
  418. }, [handleUpdateChatList])
  419. const handleAnnotationAdded = useCallback((annotationId: string, authorName: string, query: string, answer: string, index: number) => {
  420. handleUpdateChatList(chatListRef.current.map((item, i) => {
  421. if (i === index - 1) {
  422. return {
  423. ...item,
  424. content: query,
  425. }
  426. }
  427. if (i === index) {
  428. const answerItem = {
  429. ...item,
  430. content: item.content,
  431. annotation: {
  432. id: annotationId,
  433. authorName,
  434. logAnnotation: {
  435. content: answer,
  436. account: {
  437. id: '',
  438. name: authorName,
  439. email: '',
  440. },
  441. },
  442. } as Annotation,
  443. }
  444. return answerItem
  445. }
  446. return item
  447. }))
  448. }, [handleUpdateChatList])
  449. const handleAnnotationRemoved = useCallback((index: number) => {
  450. handleUpdateChatList(chatListRef.current.map((item, i) => {
  451. if (i === index) {
  452. return {
  453. ...item,
  454. content: item.content,
  455. annotation: {
  456. ...(item.annotation || {}),
  457. id: '',
  458. } as Annotation,
  459. }
  460. }
  461. return item
  462. }))
  463. }, [handleUpdateChatList])
  464. return {
  465. chatList,
  466. setChatList,
  467. conversationId: connversationId.current,
  468. isResponsing,
  469. setIsResponsing,
  470. handleSend,
  471. suggestedQuestions,
  472. handleRestart,
  473. handleStop,
  474. handleAnnotationEdited,
  475. handleAnnotationAdded,
  476. handleAnnotationRemoved,
  477. }
  478. }