hooks.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import {
  2. useEffect,
  3. useRef,
  4. useState,
  5. } from 'react'
  6. import { useTranslation } from 'react-i18next'
  7. import { produce } from 'immer'
  8. import { useGetState } from 'ahooks'
  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. 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. }
  27. export const useChat = (
  28. config: ChatConfig,
  29. promptVariablesConfig?: {
  30. inputs: Inputs
  31. promptVariables: PromptVariable[]
  32. },
  33. prevChatList?: ChatItem[],
  34. stopChat?: (taskId: string) => void,
  35. ) => {
  36. const { t } = useTranslation()
  37. const { notify } = useToastContext()
  38. const connversationId = useRef('')
  39. const hasStopResponded = useRef(false)
  40. const [isResponsing, setIsResponsing] = useState(false)
  41. const [chatList, setChatList, getChatList] = useGetState<ChatItem[]>(prevChatList || [])
  42. const [taskId, setTaskId] = useState('')
  43. const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
  44. const [abortController, setAbortController] = useState<AbortController | null>(null)
  45. const [conversationMessagesAbortController, setConversationMessagesAbortController] = useState<AbortController | null>(null)
  46. const [suggestedQuestionsAbortController, setSuggestedQuestionsAbortController] = useState<AbortController | null>(null)
  47. const getIntroduction = (str: string) => {
  48. return replaceStringWithValues(str, promptVariablesConfig?.promptVariables || [], promptVariablesConfig?.inputs || {})
  49. }
  50. useEffect(() => {
  51. if (config.opening_statement && !chatList.some(item => !item.isAnswer)) {
  52. setChatList([{
  53. id: `${Date.now()}`,
  54. content: getIntroduction(config.opening_statement),
  55. isAnswer: true,
  56. isOpeningStatement: true,
  57. suggestedQuestions: config.suggested_questions,
  58. }])
  59. }
  60. }, [config.opening_statement, config.suggested_questions, promptVariablesConfig?.inputs])
  61. const handleStop = () => {
  62. if (stopChat && taskId)
  63. stopChat(taskId)
  64. if (abortController)
  65. abortController.abort()
  66. if (conversationMessagesAbortController)
  67. conversationMessagesAbortController.abort()
  68. if (suggestedQuestionsAbortController)
  69. suggestedQuestionsAbortController.abort()
  70. }
  71. const handleRestart = () => {
  72. handleStop()
  73. hasStopResponded.current = true
  74. connversationId.current = ''
  75. setIsResponsing(false)
  76. setChatList(config.opening_statement
  77. ? [{
  78. id: `${Date.now()}`,
  79. content: config.opening_statement,
  80. isAnswer: true,
  81. isOpeningStatement: true,
  82. suggestedQuestions: config.suggested_questions,
  83. }]
  84. : [])
  85. setSuggestQuestions([])
  86. }
  87. const handleSend = async (
  88. url: string,
  89. data: any,
  90. {
  91. onGetConvesationMessages,
  92. onGetSuggestedQuestions,
  93. }: SendCallback,
  94. ) => {
  95. setSuggestQuestions([])
  96. if (isResponsing) {
  97. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  98. return false
  99. }
  100. if (promptVariablesConfig?.inputs && promptVariablesConfig?.promptVariables) {
  101. const {
  102. promptVariables,
  103. inputs,
  104. } = promptVariablesConfig
  105. let hasEmptyInput = ''
  106. const requiredVars = promptVariables.filter(({ key, name, required, type }) => {
  107. if (type === 'api')
  108. return false
  109. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  110. return res
  111. })
  112. if (requiredVars?.length) {
  113. requiredVars.forEach(({ key, name }) => {
  114. if (hasEmptyInput)
  115. return
  116. if (!inputs[key])
  117. hasEmptyInput = name
  118. })
  119. }
  120. if (hasEmptyInput) {
  121. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  122. return false
  123. }
  124. }
  125. const updateCurrentQA = ({
  126. responseItem,
  127. questionId,
  128. placeholderAnswerId,
  129. questionItem,
  130. }: {
  131. responseItem: ChatItem
  132. questionId: string
  133. placeholderAnswerId: string
  134. questionItem: ChatItem
  135. }) => {
  136. // closesure new list is outdated.
  137. const newListWithAnswer = produce(
  138. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  139. (draft) => {
  140. if (!draft.find(item => item.id === questionId))
  141. draft.push({ ...questionItem })
  142. draft.push({ ...responseItem })
  143. })
  144. setChatList(newListWithAnswer)
  145. }
  146. const questionId = `question-${Date.now()}`
  147. const questionItem = {
  148. id: questionId,
  149. content: data.query,
  150. isAnswer: false,
  151. message_files: data.files,
  152. }
  153. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  154. const placeholderAnswerItem = {
  155. id: placeholderAnswerId,
  156. content: '',
  157. isAnswer: true,
  158. }
  159. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  160. setChatList(newList)
  161. // answer
  162. const responseItem: ChatItem = {
  163. id: `${Date.now()}`,
  164. content: '',
  165. agent_thoughts: [],
  166. message_files: [],
  167. isAnswer: true,
  168. }
  169. setIsResponsing(true)
  170. hasStopResponded.current = false
  171. const bodyParams = {
  172. response_mode: 'streaming',
  173. conversation_id: connversationId.current,
  174. ...data,
  175. }
  176. if (bodyParams?.files?.length) {
  177. bodyParams.files = bodyParams.files.map((item: VisionFile) => {
  178. if (item.transfer_method === TransferMethod.local_file) {
  179. return {
  180. ...item,
  181. url: '',
  182. }
  183. }
  184. return item
  185. })
  186. }
  187. let isAgentMode = false
  188. let hasSetResponseId = false
  189. ssePost(
  190. url,
  191. {
  192. body: bodyParams,
  193. },
  194. {
  195. getAbortController: (abortController) => {
  196. setAbortController(abortController)
  197. },
  198. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  199. if (!isAgentMode) {
  200. responseItem.content = responseItem.content + message
  201. }
  202. else {
  203. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  204. if (lastThought)
  205. lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
  206. }
  207. if (messageId && !hasSetResponseId) {
  208. responseItem.id = messageId
  209. hasSetResponseId = true
  210. }
  211. if (isFirstMessage && newConversationId)
  212. connversationId.current = newConversationId
  213. setTaskId(taskId)
  214. if (messageId)
  215. responseItem.id = messageId
  216. updateCurrentQA({
  217. responseItem,
  218. questionId,
  219. placeholderAnswerId,
  220. questionItem,
  221. })
  222. },
  223. async onCompleted(hasError?: boolean) {
  224. setIsResponsing(false)
  225. if (hasError)
  226. return
  227. if (connversationId.current) {
  228. const { data }: any = await onGetConvesationMessages(
  229. connversationId.current,
  230. newAbortController => setConversationMessagesAbortController(newAbortController),
  231. )
  232. const newResponseItem = data.find((item: any) => item.id === responseItem.id)
  233. if (!newResponseItem)
  234. return
  235. setChatList(produce(getChatList(), (draft) => {
  236. const index = draft.findIndex(item => item.id === responseItem.id)
  237. if (index !== -1) {
  238. const requestion = draft[index - 1]
  239. draft[index - 1] = {
  240. ...requestion,
  241. log: newResponseItem.message,
  242. }
  243. draft[index] = {
  244. ...draft[index],
  245. more: {
  246. time: dayjs.unix(newResponseItem.created_at).format('hh:mm A'),
  247. tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
  248. latency: newResponseItem.provider_response_latency.toFixed(2),
  249. },
  250. }
  251. }
  252. }))
  253. }
  254. if (config.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
  255. const { data }: any = await onGetSuggestedQuestions(
  256. responseItem.id,
  257. newAbortController => setSuggestedQuestionsAbortController(newAbortController),
  258. )
  259. setSuggestQuestions(data)
  260. }
  261. },
  262. onFile(file) {
  263. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  264. if (lastThought)
  265. responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(lastThought as any).message_files, file]
  266. updateCurrentQA({
  267. responseItem,
  268. questionId,
  269. placeholderAnswerId,
  270. questionItem,
  271. })
  272. },
  273. onThought(thought) {
  274. isAgentMode = true
  275. const response = responseItem as any
  276. if (thought.message_id && !hasSetResponseId)
  277. response.id = thought.message_id
  278. if (response.agent_thoughts.length === 0) {
  279. response.agent_thoughts.push(thought)
  280. }
  281. else {
  282. const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
  283. // thought changed but still the same thought, so update.
  284. if (lastThought.id === thought.id) {
  285. thought.thought = lastThought.thought
  286. thought.message_files = lastThought.message_files
  287. responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
  288. }
  289. else {
  290. responseItem.agent_thoughts!.push(thought)
  291. }
  292. }
  293. updateCurrentQA({
  294. responseItem,
  295. questionId,
  296. placeholderAnswerId,
  297. questionItem,
  298. })
  299. },
  300. onMessageEnd: (messageEnd) => {
  301. if (messageEnd.metadata?.annotation_reply) {
  302. responseItem.id = messageEnd.id
  303. responseItem.annotation = ({
  304. id: messageEnd.metadata.annotation_reply.id,
  305. authorName: messageEnd.metadata.annotation_reply.account.name,
  306. })
  307. const newListWithAnswer = produce(
  308. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  309. (draft) => {
  310. if (!draft.find(item => item.id === questionId))
  311. draft.push({ ...questionItem })
  312. draft.push({
  313. ...responseItem,
  314. })
  315. })
  316. setChatList(newListWithAnswer)
  317. return
  318. }
  319. responseItem.citation = messageEnd.metadata?.retriever_resources || []
  320. const newListWithAnswer = produce(
  321. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  322. (draft) => {
  323. if (!draft.find(item => item.id === questionId))
  324. draft.push({ ...questionItem })
  325. draft.push({ ...responseItem })
  326. })
  327. setChatList(newListWithAnswer)
  328. },
  329. onMessageReplace: (messageReplace) => {
  330. responseItem.content = messageReplace.answer
  331. },
  332. onError() {
  333. setIsResponsing(false)
  334. // role back placeholder answer
  335. setChatList(produce(getChatList(), (draft) => {
  336. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  337. }))
  338. },
  339. })
  340. return true
  341. }
  342. return {
  343. chatList,
  344. getChatList,
  345. setChatList,
  346. conversationId: connversationId.current,
  347. isResponsing,
  348. setIsResponsing,
  349. handleSend,
  350. suggestedQuestions,
  351. handleRestart,
  352. handleStop,
  353. }
  354. }
  355. export const useCurrentAnswerIsResponsing = (answerId: string) => {
  356. const {
  357. isResponsing,
  358. chatList,
  359. } = useChatContext()
  360. const isLast = answerId === chatList[chatList.length - 1]?.id
  361. return isLast && isResponsing
  362. }