hooks.ts 16 KB

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