hooks.ts 16 KB

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