hooks.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import {
  2. useCallback,
  3. useEffect,
  4. useMemo,
  5. useRef,
  6. useState,
  7. } from 'react'
  8. import { useTranslation } from 'react-i18next'
  9. import useSWR from 'swr'
  10. import { useLocalStorageState } from 'ahooks'
  11. import produce from 'immer'
  12. import type {
  13. Callback,
  14. ChatConfig,
  15. ChatItem,
  16. Feedback,
  17. } from '../types'
  18. import { CONVERSATION_ID_INFO } from '../constants'
  19. import {
  20. delConversation,
  21. fetchAppInfo,
  22. fetchAppMeta,
  23. fetchAppParams,
  24. fetchChatList,
  25. fetchConversations,
  26. generationConversationName,
  27. pinConversation,
  28. renameConversation,
  29. unpinConversation,
  30. updateFeedback,
  31. } from '@/service/share'
  32. import type { InstalledApp } from '@/models/explore'
  33. import type {
  34. AppData,
  35. ConversationItem,
  36. } from '@/models/share'
  37. import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
  38. import { useToastContext } from '@/app/components/base/toast'
  39. import { changeLanguage } from '@/i18n/i18next-config'
  40. export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {
  41. const isInstalledApp = useMemo(() => !!installedAppInfo, [installedAppInfo])
  42. const { data: appInfo, isLoading: appInfoLoading, error: appInfoError } = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo)
  43. const appData = useMemo(() => {
  44. if (isInstalledApp) {
  45. const { id, app } = installedAppInfo!
  46. return {
  47. app_id: id,
  48. site: { title: app.name, icon: app.icon, icon_background: app.icon_background, prompt_public: false, copyright: '' },
  49. plan: 'basic',
  50. } as AppData
  51. }
  52. return appInfo
  53. }, [isInstalledApp, installedAppInfo, appInfo])
  54. const appId = useMemo(() => appData?.app_id, [appData])
  55. useEffect(() => {
  56. if (appData?.site.default_language)
  57. changeLanguage(appData.site.default_language)
  58. }, [appData])
  59. const [conversationIdInfo, setConversationIdInfo] = useLocalStorageState<Record<string, string>>(CONVERSATION_ID_INFO, {
  60. defaultValue: {},
  61. })
  62. const currentConversationId = useMemo(() => conversationIdInfo?.[appId || ''] || '', [appId, conversationIdInfo])
  63. const handleConversationIdInfoChange = useCallback((changeConversationId: string) => {
  64. if (appId) {
  65. setConversationIdInfo({
  66. ...conversationIdInfo,
  67. [appId || '']: changeConversationId,
  68. })
  69. }
  70. }, [appId, conversationIdInfo, setConversationIdInfo])
  71. const [showConfigPanelBeforeChat, setShowConfigPanelBeforeChat] = useState(true)
  72. const [newConversationId, setNewConversationId] = useState('')
  73. const chatShouldReloadKey = useMemo(() => {
  74. if (currentConversationId === newConversationId)
  75. return ''
  76. return currentConversationId
  77. }, [currentConversationId, newConversationId])
  78. const { data: appParams } = useSWR(['appParams', isInstalledApp, appId], () => fetchAppParams(isInstalledApp, appId))
  79. const { data: appMeta } = useSWR(['appMeta', isInstalledApp, appId], () => fetchAppMeta(isInstalledApp, appId))
  80. const { data: appPinnedConversationData, mutate: mutateAppPinnedConversationData } = useSWR(['appConversationData', isInstalledApp, appId, true], () => fetchConversations(isInstalledApp, appId, undefined, true, 100))
  81. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(['appConversationData', isInstalledApp, appId, false], () => fetchConversations(isInstalledApp, appId, undefined, false, 100))
  82. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null, () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId))
  83. const appPrevChatList = useMemo(() => {
  84. const data = appChatListData?.data || []
  85. const chatList: ChatItem[] = []
  86. if (currentConversationId && data.length) {
  87. data.forEach((item: any) => {
  88. chatList.push({
  89. id: `question-${item.id}`,
  90. content: item.query,
  91. isAnswer: false,
  92. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'user') || [],
  93. })
  94. chatList.push({
  95. id: item.id,
  96. content: item.answer,
  97. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  98. feedback: item.feedback,
  99. isAnswer: true,
  100. citation: item.retriever_resources,
  101. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  102. })
  103. })
  104. }
  105. return chatList
  106. }, [appChatListData, currentConversationId])
  107. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  108. const pinnedConversationList = useMemo(() => {
  109. return appPinnedConversationData?.data || []
  110. }, [appPinnedConversationData])
  111. const { t } = useTranslation()
  112. const newConversationInputsRef = useRef<Record<string, any>>({})
  113. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  114. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  115. newConversationInputsRef.current = newInputs
  116. setNewConversationInputs(newInputs)
  117. }, [])
  118. const inputsForms = useMemo(() => {
  119. return (appParams?.user_input_form || []).filter((item: any) => item.paragraph || item.select || item['text-input']).map((item: any) => {
  120. if (item.paragraph) {
  121. return {
  122. ...item.paragraph,
  123. type: 'paragraph',
  124. }
  125. }
  126. if (item.select) {
  127. return {
  128. ...item.select,
  129. type: 'select',
  130. }
  131. }
  132. return {
  133. ...item['text-input'],
  134. type: 'text-input',
  135. }
  136. })
  137. }, [appParams])
  138. useEffect(() => {
  139. const conversationInputs: Record<string, any> = {}
  140. inputsForms.forEach((item: any) => {
  141. conversationInputs[item.variable] = item.default || ''
  142. })
  143. handleNewConversationInputsChange(conversationInputs)
  144. }, [handleNewConversationInputsChange, inputsForms])
  145. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId))
  146. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  147. useEffect(() => {
  148. if (appConversationData?.data && !appConversationDataLoading)
  149. setOriginConversationList(appConversationData?.data)
  150. }, [appConversationData, appConversationDataLoading])
  151. const conversationList = useMemo(() => {
  152. const data = originConversationList.slice()
  153. if (showNewConversationItemInList && data[0]?.id !== '') {
  154. data.unshift({
  155. id: '',
  156. name: t('share.chat.newChatDefaultName'),
  157. inputs: {},
  158. introduction: '',
  159. })
  160. }
  161. return data
  162. }, [originConversationList, showNewConversationItemInList, t])
  163. useEffect(() => {
  164. if (newConversation) {
  165. setOriginConversationList(produce((draft) => {
  166. const index = draft.findIndex(item => item.id === newConversation.id)
  167. if (index > -1)
  168. draft[index] = newConversation
  169. else
  170. draft.unshift(newConversation)
  171. }))
  172. }
  173. }, [newConversation])
  174. const currentConversationItem = useMemo(() => {
  175. let coversationItem = conversationList.find(item => item.id === currentConversationId)
  176. if (!coversationItem && pinnedConversationList.length)
  177. coversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  178. return coversationItem
  179. }, [conversationList, currentConversationId, pinnedConversationList])
  180. const { notify } = useToastContext()
  181. const checkInputsRequired = useCallback((silent?: boolean) => {
  182. if (inputsForms.length) {
  183. for (let i = 0; i < inputsForms.length; i += 1) {
  184. const item = inputsForms[i]
  185. if (item.required && !newConversationInputsRef.current[item.variable]) {
  186. if (!silent) {
  187. notify({
  188. type: 'error',
  189. message: t('appDebug.errorMessage.valueOfVarRequired', { key: item.variable }),
  190. })
  191. }
  192. return
  193. }
  194. }
  195. return true
  196. }
  197. return true
  198. }, [inputsForms, notify, t])
  199. const handleStartChat = useCallback(() => {
  200. if (checkInputsRequired()) {
  201. setShowConfigPanelBeforeChat(false)
  202. setShowNewConversationItemInList(true)
  203. }
  204. }, [setShowConfigPanelBeforeChat, setShowNewConversationItemInList, checkInputsRequired])
  205. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: () => {} })
  206. const handleChangeConversation = useCallback((conversationId: string) => {
  207. currentChatInstanceRef.current.handleStop()
  208. setNewConversationId('')
  209. handleConversationIdInfoChange(conversationId)
  210. if (conversationId === '' && !checkInputsRequired(true))
  211. setShowConfigPanelBeforeChat(true)
  212. else
  213. setShowConfigPanelBeforeChat(false)
  214. }, [handleConversationIdInfoChange, setShowConfigPanelBeforeChat, checkInputsRequired])
  215. const handleNewConversation = useCallback(() => {
  216. currentChatInstanceRef.current.handleStop()
  217. setNewConversationId('')
  218. if (showNewConversationItemInList) {
  219. handleChangeConversation('')
  220. }
  221. else if (currentConversationId) {
  222. handleConversationIdInfoChange('')
  223. setShowConfigPanelBeforeChat(true)
  224. setShowNewConversationItemInList(true)
  225. handleNewConversationInputsChange({})
  226. }
  227. }, [handleChangeConversation, currentConversationId, handleConversationIdInfoChange, setShowConfigPanelBeforeChat, setShowNewConversationItemInList, showNewConversationItemInList, handleNewConversationInputsChange])
  228. const handleUpdateConversationList = useCallback(() => {
  229. mutateAppConversationData()
  230. mutateAppPinnedConversationData()
  231. }, [mutateAppConversationData, mutateAppPinnedConversationData])
  232. const handlePinConversation = useCallback(async (conversationId: string) => {
  233. await pinConversation(isInstalledApp, appId, conversationId)
  234. notify({ type: 'success', message: t('common.api.success') })
  235. handleUpdateConversationList()
  236. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  237. const handleUnpinConversation = useCallback(async (conversationId: string) => {
  238. await unpinConversation(isInstalledApp, appId, conversationId)
  239. notify({ type: 'success', message: t('common.api.success') })
  240. handleUpdateConversationList()
  241. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  242. const [conversationDeleting, setConversationDeleting] = useState(false)
  243. const handleDeleteConversation = useCallback(async (
  244. conversationId: string,
  245. {
  246. onSuccess,
  247. }: Callback,
  248. ) => {
  249. if (conversationDeleting)
  250. return
  251. try {
  252. setConversationDeleting(true)
  253. await delConversation(isInstalledApp, appId, conversationId)
  254. notify({ type: 'success', message: t('common.api.success') })
  255. onSuccess()
  256. }
  257. finally {
  258. setConversationDeleting(false)
  259. }
  260. if (conversationId === currentConversationId)
  261. handleNewConversation()
  262. handleUpdateConversationList()
  263. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList, handleNewConversation, currentConversationId, conversationDeleting])
  264. const [conversationRenaming, setConversationRenaming] = useState(false)
  265. const handleRenameConversation = useCallback(async (
  266. conversationId: string,
  267. newName: string,
  268. {
  269. onSuccess,
  270. }: Callback,
  271. ) => {
  272. if (conversationRenaming)
  273. return
  274. if (!newName.trim()) {
  275. notify({
  276. type: 'error',
  277. message: t('common.chat.conversationNameCanNotEmpty'),
  278. })
  279. return
  280. }
  281. setConversationRenaming(true)
  282. try {
  283. await renameConversation(isInstalledApp, appId, conversationId, newName)
  284. notify({
  285. type: 'success',
  286. message: t('common.actionMsg.modifiedSuccessfully'),
  287. })
  288. setOriginConversationList(produce((draft) => {
  289. const index = originConversationList.findIndex(item => item.id === conversationId)
  290. const item = draft[index]
  291. draft[index] = {
  292. ...item,
  293. name: newName,
  294. }
  295. }))
  296. onSuccess()
  297. }
  298. finally {
  299. setConversationRenaming(false)
  300. }
  301. }, [isInstalledApp, appId, notify, t, conversationRenaming, originConversationList])
  302. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  303. setNewConversationId(newConversationId)
  304. handleConversationIdInfoChange(newConversationId)
  305. setShowNewConversationItemInList(false)
  306. mutateAppConversationData()
  307. }, [mutateAppConversationData, handleConversationIdInfoChange])
  308. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  309. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  310. notify({ type: 'success', message: t('common.api.success') })
  311. }, [isInstalledApp, appId, t, notify])
  312. return {
  313. appInfoError,
  314. appInfoLoading,
  315. isInstalledApp,
  316. appId,
  317. currentConversationId,
  318. currentConversationItem,
  319. handleConversationIdInfoChange,
  320. appData,
  321. appParams: appParams || {} as ChatConfig,
  322. appMeta,
  323. appPinnedConversationData,
  324. appConversationData,
  325. appConversationDataLoading,
  326. appChatListData,
  327. appChatListDataLoading,
  328. appPrevChatList,
  329. pinnedConversationList,
  330. conversationList,
  331. showConfigPanelBeforeChat,
  332. setShowConfigPanelBeforeChat,
  333. setShowNewConversationItemInList,
  334. newConversationInputs,
  335. handleNewConversationInputsChange,
  336. inputsForms,
  337. handleNewConversation,
  338. handleStartChat,
  339. handleChangeConversation,
  340. handlePinConversation,
  341. handleUnpinConversation,
  342. conversationDeleting,
  343. handleDeleteConversation,
  344. conversationRenaming,
  345. handleRenameConversation,
  346. handleNewConversationCompleted,
  347. newConversationId,
  348. chatShouldReloadKey,
  349. handleFeedback,
  350. currentChatInstanceRef,
  351. }
  352. }