hooks.ts 16 KB

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