hooks.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. ChatConfig,
  14. ChatItem,
  15. Feedback,
  16. } from '../types'
  17. import { CONVERSATION_ID_INFO } from '../constants'
  18. import { buildChatItemTree, getProcessedInputsFromUrlParams } from '../utils'
  19. import { getProcessedFilesFromResponse } from '../../file-uploader/utils'
  20. import {
  21. fetchAppInfo,
  22. fetchAppMeta,
  23. fetchAppParams,
  24. fetchChatList,
  25. fetchConversations,
  26. generationConversationName,
  27. updateFeedback,
  28. } from '@/service/share'
  29. import type {
  30. // AppData,
  31. ConversationItem,
  32. } from '@/models/share'
  33. import { useToastContext } from '@/app/components/base/toast'
  34. import { changeLanguage } from '@/i18n/i18next-config'
  35. import { InputVarType } from '@/app/components/workflow/types'
  36. import { TransferMethod } from '@/types/app'
  37. import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
  38. function getFormattedChatList(messages: any[]) {
  39. const newChatList: ChatItem[] = []
  40. messages.forEach((item) => {
  41. const questionFiles = item.message_files?.filter((file: any) => file.belongs_to === 'user') || []
  42. newChatList.push({
  43. id: `question-${item.id}`,
  44. content: item.query,
  45. isAnswer: false,
  46. message_files: getProcessedFilesFromResponse(questionFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  47. parentMessageId: item.parent_message_id || undefined,
  48. })
  49. const answerFiles = item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || []
  50. newChatList.push({
  51. id: item.id,
  52. content: item.answer,
  53. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  54. feedback: item.feedback,
  55. isAnswer: true,
  56. citation: item.retriever_resources,
  57. message_files: getProcessedFilesFromResponse(answerFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  58. parentMessageId: `question-${item.id}`,
  59. })
  60. })
  61. return newChatList
  62. }
  63. export const useEmbeddedChatbot = () => {
  64. const isInstalledApp = false
  65. const { data: appInfo, isLoading: appInfoLoading, error: appInfoError } = useSWR('appInfo', fetchAppInfo)
  66. const appData = useMemo(() => {
  67. return appInfo
  68. }, [appInfo])
  69. const appId = useMemo(() => appData?.app_id, [appData])
  70. useEffect(() => {
  71. if (appInfo?.site.default_language)
  72. changeLanguage(appInfo.site.default_language)
  73. }, [appInfo])
  74. const [conversationIdInfo, setConversationIdInfo] = useLocalStorageState<Record<string, string>>(CONVERSATION_ID_INFO, {
  75. defaultValue: {},
  76. })
  77. const currentConversationId = useMemo(() => conversationIdInfo?.[appId || ''] || '', [appId, conversationIdInfo])
  78. const handleConversationIdInfoChange = useCallback((changeConversationId: string) => {
  79. if (appId) {
  80. setConversationIdInfo({
  81. ...conversationIdInfo,
  82. [appId || '']: changeConversationId,
  83. })
  84. }
  85. }, [appId, conversationIdInfo, setConversationIdInfo])
  86. const [showConfigPanelBeforeChat, setShowConfigPanelBeforeChat] = useState(true)
  87. const [newConversationId, setNewConversationId] = useState('')
  88. const chatShouldReloadKey = useMemo(() => {
  89. if (currentConversationId === newConversationId)
  90. return ''
  91. return currentConversationId
  92. }, [currentConversationId, newConversationId])
  93. const { data: appParams } = useSWR(['appParams', isInstalledApp, appId], () => fetchAppParams(isInstalledApp, appId))
  94. const { data: appMeta } = useSWR(['appMeta', isInstalledApp, appId], () => fetchAppMeta(isInstalledApp, appId))
  95. const { data: appPinnedConversationData } = useSWR(['appConversationData', isInstalledApp, appId, true], () => fetchConversations(isInstalledApp, appId, undefined, true, 100))
  96. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(['appConversationData', isInstalledApp, appId, false], () => fetchConversations(isInstalledApp, appId, undefined, false, 100))
  97. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null, () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId))
  98. const appPrevChatList = useMemo(
  99. () => (currentConversationId && appChatListData?.data.length)
  100. ? buildChatItemTree(getFormattedChatList(appChatListData.data))
  101. : [],
  102. [appChatListData, currentConversationId],
  103. )
  104. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  105. const pinnedConversationList = useMemo(() => {
  106. return appPinnedConversationData?.data || []
  107. }, [appPinnedConversationData])
  108. const { t } = useTranslation()
  109. const newConversationInputsRef = useRef<Record<string, any>>({})
  110. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  111. const [initInputs, setInitInputs] = useState<Record<string, any>>({})
  112. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  113. newConversationInputsRef.current = newInputs
  114. setNewConversationInputs(newInputs)
  115. }, [])
  116. const inputsForms = useMemo(() => {
  117. return (appParams?.user_input_form || []).filter((item: any) => !item.external_data_tool).map((item: any) => {
  118. if (item.paragraph) {
  119. let value = initInputs[item.paragraph.variable]
  120. if (value && item.paragraph.max_length && value.length > item.paragraph.max_length)
  121. value = value.slice(0, item.paragraph.max_length)
  122. return {
  123. ...item.paragraph,
  124. default: value || item.default,
  125. type: 'paragraph',
  126. }
  127. }
  128. if (item.number) {
  129. const convertedNumber = Number(initInputs[item.number.variable]) ?? undefined
  130. return {
  131. ...item.number,
  132. default: convertedNumber || item.default,
  133. type: 'number',
  134. }
  135. }
  136. if (item.select) {
  137. const isInputInOptions = item.select.options.includes(initInputs[item.select.variable])
  138. return {
  139. ...item.select,
  140. default: (isInputInOptions ? initInputs[item.select.variable] : undefined) || item.default,
  141. type: 'select',
  142. }
  143. }
  144. if (item['file-list']) {
  145. return {
  146. ...item['file-list'],
  147. type: 'file-list',
  148. }
  149. }
  150. if (item.file) {
  151. return {
  152. ...item.file,
  153. type: 'file',
  154. }
  155. }
  156. let value = initInputs[item['text-input'].variable]
  157. if (value && item['text-input'].max_length && value.length > item['text-input'].max_length)
  158. value = value.slice(0, item['text-input'].max_length)
  159. return {
  160. ...item['text-input'],
  161. default: value || item.default,
  162. type: 'text-input',
  163. }
  164. })
  165. }, [initInputs, appParams])
  166. useEffect(() => {
  167. // init inputs from url params
  168. setInitInputs(getProcessedInputsFromUrlParams())
  169. }, [])
  170. useEffect(() => {
  171. const conversationInputs: Record<string, any> = {}
  172. inputsForms.forEach((item: any) => {
  173. conversationInputs[item.variable] = item.default || null
  174. })
  175. handleNewConversationInputsChange(conversationInputs)
  176. }, [handleNewConversationInputsChange, inputsForms])
  177. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  178. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  179. useEffect(() => {
  180. if (appConversationData?.data && !appConversationDataLoading)
  181. setOriginConversationList(appConversationData?.data)
  182. }, [appConversationData, appConversationDataLoading])
  183. const conversationList = useMemo(() => {
  184. const data = originConversationList.slice()
  185. if (showNewConversationItemInList && data[0]?.id !== '') {
  186. data.unshift({
  187. id: '',
  188. name: t('share.chat.newChatDefaultName'),
  189. inputs: {},
  190. introduction: '',
  191. })
  192. }
  193. return data
  194. }, [originConversationList, showNewConversationItemInList, t])
  195. useEffect(() => {
  196. if (newConversation) {
  197. setOriginConversationList(produce((draft) => {
  198. const index = draft.findIndex(item => item.id === newConversation.id)
  199. if (index > -1)
  200. draft[index] = newConversation
  201. else
  202. draft.unshift(newConversation)
  203. }))
  204. }
  205. }, [newConversation])
  206. const currentConversationItem = useMemo(() => {
  207. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  208. if (!conversationItem && pinnedConversationList.length)
  209. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  210. return conversationItem
  211. }, [conversationList, currentConversationId, pinnedConversationList])
  212. const { notify } = useToastContext()
  213. const checkInputsRequired = useCallback((silent?: boolean) => {
  214. let hasEmptyInput = ''
  215. let fileIsUploading = false
  216. const requiredVars = inputsForms.filter(({ required }) => required)
  217. if (requiredVars.length) {
  218. requiredVars.forEach(({ variable, label, type }) => {
  219. if (hasEmptyInput)
  220. return
  221. if (fileIsUploading)
  222. return
  223. if (!newConversationInputsRef.current[variable] && !silent)
  224. hasEmptyInput = label as string
  225. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  226. const files = newConversationInputsRef.current[variable]
  227. if (Array.isArray(files))
  228. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  229. else
  230. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  231. }
  232. })
  233. }
  234. if (hasEmptyInput) {
  235. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  236. return false
  237. }
  238. if (fileIsUploading) {
  239. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  240. return
  241. }
  242. return true
  243. }, [inputsForms, notify, t])
  244. const handleStartChat = useCallback(() => {
  245. if (checkInputsRequired()) {
  246. setShowConfigPanelBeforeChat(false)
  247. setShowNewConversationItemInList(true)
  248. }
  249. }, [setShowConfigPanelBeforeChat, setShowNewConversationItemInList, checkInputsRequired])
  250. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: () => { } })
  251. const handleChangeConversation = useCallback((conversationId: string) => {
  252. currentChatInstanceRef.current.handleStop()
  253. setNewConversationId('')
  254. handleConversationIdInfoChange(conversationId)
  255. if (conversationId === '' && !checkInputsRequired(true))
  256. setShowConfigPanelBeforeChat(true)
  257. else
  258. setShowConfigPanelBeforeChat(false)
  259. }, [handleConversationIdInfoChange, setShowConfigPanelBeforeChat, checkInputsRequired])
  260. const handleNewConversation = useCallback(() => {
  261. currentChatInstanceRef.current.handleStop()
  262. setNewConversationId('')
  263. if (showNewConversationItemInList) {
  264. handleChangeConversation('')
  265. }
  266. else if (currentConversationId) {
  267. handleConversationIdInfoChange('')
  268. setShowConfigPanelBeforeChat(true)
  269. setShowNewConversationItemInList(true)
  270. handleNewConversationInputsChange({})
  271. }
  272. }, [handleChangeConversation, currentConversationId, handleConversationIdInfoChange, setShowConfigPanelBeforeChat, setShowNewConversationItemInList, showNewConversationItemInList, handleNewConversationInputsChange])
  273. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  274. setNewConversationId(newConversationId)
  275. handleConversationIdInfoChange(newConversationId)
  276. setShowNewConversationItemInList(false)
  277. mutateAppConversationData()
  278. }, [mutateAppConversationData, handleConversationIdInfoChange])
  279. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  280. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  281. notify({ type: 'success', message: t('common.api.success') })
  282. }, [isInstalledApp, appId, t, notify])
  283. return {
  284. appInfoError,
  285. appInfoLoading,
  286. isInstalledApp,
  287. appId,
  288. currentConversationId,
  289. currentConversationItem,
  290. handleConversationIdInfoChange,
  291. appData,
  292. appParams: appParams || {} as ChatConfig,
  293. appMeta,
  294. appPinnedConversationData,
  295. appConversationData,
  296. appConversationDataLoading,
  297. appChatListData,
  298. appChatListDataLoading,
  299. appPrevChatList,
  300. pinnedConversationList,
  301. conversationList,
  302. showConfigPanelBeforeChat,
  303. setShowConfigPanelBeforeChat,
  304. setShowNewConversationItemInList,
  305. newConversationInputs,
  306. newConversationInputsRef,
  307. handleNewConversationInputsChange,
  308. inputsForms,
  309. handleNewConversation,
  310. handleStartChat,
  311. handleChangeConversation,
  312. handleNewConversationCompleted,
  313. newConversationId,
  314. chatShouldReloadKey,
  315. handleFeedback,
  316. currentChatInstanceRef,
  317. }
  318. }