hooks.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 [newConversationId, setNewConversationId] = useState('')
  87. const chatShouldReloadKey = useMemo(() => {
  88. if (currentConversationId === newConversationId)
  89. return ''
  90. return currentConversationId
  91. }, [currentConversationId, newConversationId])
  92. const { data: appParams } = useSWR(['appParams', isInstalledApp, appId], () => fetchAppParams(isInstalledApp, appId))
  93. const { data: appMeta } = useSWR(['appMeta', isInstalledApp, appId], () => fetchAppMeta(isInstalledApp, appId))
  94. const { data: appPinnedConversationData } = useSWR(['appConversationData', isInstalledApp, appId, true], () => fetchConversations(isInstalledApp, appId, undefined, true, 100))
  95. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(['appConversationData', isInstalledApp, appId, false], () => fetchConversations(isInstalledApp, appId, undefined, false, 100))
  96. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null, () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId))
  97. const [clearChatList, setClearChatList] = useState(false)
  98. const [isResponding, setIsResponding] = useState(false)
  99. const appPrevChatList = useMemo(
  100. () => (currentConversationId && appChatListData?.data.length)
  101. ? buildChatItemTree(getFormattedChatList(appChatListData.data))
  102. : [],
  103. [appChatListData, currentConversationId],
  104. )
  105. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  106. const pinnedConversationList = useMemo(() => {
  107. return appPinnedConversationData?.data || []
  108. }, [appPinnedConversationData])
  109. const { t } = useTranslation()
  110. const newConversationInputsRef = useRef<Record<string, any>>({})
  111. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  112. const [initInputs, setInitInputs] = useState<Record<string, any>>({})
  113. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  114. newConversationInputsRef.current = newInputs
  115. setNewConversationInputs(newInputs)
  116. }, [])
  117. const inputsForms = useMemo(() => {
  118. return (appParams?.user_input_form || []).filter((item: any) => !item.external_data_tool).map((item: any) => {
  119. if (item.paragraph) {
  120. let value = initInputs[item.paragraph.variable]
  121. if (value && item.paragraph.max_length && value.length > item.paragraph.max_length)
  122. value = value.slice(0, item.paragraph.max_length)
  123. return {
  124. ...item.paragraph,
  125. default: value || item.default,
  126. type: 'paragraph',
  127. }
  128. }
  129. if (item.number) {
  130. const convertedNumber = Number(initInputs[item.number.variable]) ?? undefined
  131. return {
  132. ...item.number,
  133. default: convertedNumber || item.default,
  134. type: 'number',
  135. }
  136. }
  137. if (item.select) {
  138. const isInputInOptions = item.select.options.includes(initInputs[item.select.variable])
  139. return {
  140. ...item.select,
  141. default: (isInputInOptions ? initInputs[item.select.variable] : undefined) || item.default,
  142. type: 'select',
  143. }
  144. }
  145. if (item['file-list']) {
  146. return {
  147. ...item['file-list'],
  148. type: 'file-list',
  149. }
  150. }
  151. if (item.file) {
  152. return {
  153. ...item.file,
  154. type: 'file',
  155. }
  156. }
  157. let value = initInputs[item['text-input'].variable]
  158. if (value && item['text-input'].max_length && value.length > item['text-input'].max_length)
  159. value = value.slice(0, item['text-input'].max_length)
  160. return {
  161. ...item['text-input'],
  162. default: value || item.default,
  163. type: 'text-input',
  164. }
  165. })
  166. }, [initInputs, appParams])
  167. useEffect(() => {
  168. // init inputs from url params
  169. (async () => {
  170. const inputs = await getProcessedInputsFromUrlParams()
  171. setInitInputs(inputs)
  172. })()
  173. }, [])
  174. useEffect(() => {
  175. const conversationInputs: Record<string, any> = {}
  176. inputsForms.forEach((item: any) => {
  177. conversationInputs[item.variable] = item.default || null
  178. })
  179. handleNewConversationInputsChange(conversationInputs)
  180. }, [handleNewConversationInputsChange, inputsForms])
  181. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  182. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  183. useEffect(() => {
  184. if (appConversationData?.data && !appConversationDataLoading)
  185. setOriginConversationList(appConversationData?.data)
  186. }, [appConversationData, appConversationDataLoading])
  187. const conversationList = useMemo(() => {
  188. const data = originConversationList.slice()
  189. if (showNewConversationItemInList && data[0]?.id !== '') {
  190. data.unshift({
  191. id: '',
  192. name: t('share.chat.newChatDefaultName'),
  193. inputs: {},
  194. introduction: '',
  195. })
  196. }
  197. return data
  198. }, [originConversationList, showNewConversationItemInList, t])
  199. useEffect(() => {
  200. if (newConversation) {
  201. setOriginConversationList(produce((draft) => {
  202. const index = draft.findIndex(item => item.id === newConversation.id)
  203. if (index > -1)
  204. draft[index] = newConversation
  205. else
  206. draft.unshift(newConversation)
  207. }))
  208. }
  209. }, [newConversation])
  210. const currentConversationItem = useMemo(() => {
  211. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  212. if (!conversationItem && pinnedConversationList.length)
  213. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  214. return conversationItem
  215. }, [conversationList, currentConversationId, pinnedConversationList])
  216. const { notify } = useToastContext()
  217. const checkInputsRequired = useCallback((silent?: boolean) => {
  218. let hasEmptyInput = ''
  219. let fileIsUploading = false
  220. const requiredVars = inputsForms.filter(({ required }) => required)
  221. if (requiredVars.length) {
  222. requiredVars.forEach(({ variable, label, type }) => {
  223. if (hasEmptyInput)
  224. return
  225. if (fileIsUploading)
  226. return
  227. if (!newConversationInputsRef.current[variable] && !silent)
  228. hasEmptyInput = label as string
  229. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  230. const files = newConversationInputsRef.current[variable]
  231. if (Array.isArray(files))
  232. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  233. else
  234. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  235. }
  236. })
  237. }
  238. if (hasEmptyInput) {
  239. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  240. return false
  241. }
  242. if (fileIsUploading) {
  243. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  244. return
  245. }
  246. return true
  247. }, [inputsForms, notify, t])
  248. const handleStartChat = useCallback((callback?: any) => {
  249. if (checkInputsRequired()) {
  250. setShowNewConversationItemInList(true)
  251. callback?.()
  252. }
  253. }, [setShowNewConversationItemInList, checkInputsRequired])
  254. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: () => { } })
  255. const handleChangeConversation = useCallback((conversationId: string) => {
  256. currentChatInstanceRef.current.handleStop()
  257. setNewConversationId('')
  258. handleConversationIdInfoChange(conversationId)
  259. if (conversationId)
  260. setClearChatList(false)
  261. }, [handleConversationIdInfoChange, setClearChatList])
  262. const handleNewConversation = useCallback(async () => {
  263. currentChatInstanceRef.current.handleStop()
  264. setShowNewConversationItemInList(true)
  265. handleChangeConversation('')
  266. handleNewConversationInputsChange(await getProcessedInputsFromUrlParams())
  267. setClearChatList(true)
  268. }, [handleChangeConversation, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])
  269. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  270. setNewConversationId(newConversationId)
  271. handleConversationIdInfoChange(newConversationId)
  272. setShowNewConversationItemInList(false)
  273. mutateAppConversationData()
  274. }, [mutateAppConversationData, handleConversationIdInfoChange])
  275. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  276. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  277. notify({ type: 'success', message: t('common.api.success') })
  278. }, [isInstalledApp, appId, t, notify])
  279. return {
  280. appInfoError,
  281. appInfoLoading,
  282. isInstalledApp,
  283. appId,
  284. currentConversationId,
  285. currentConversationItem,
  286. handleConversationIdInfoChange,
  287. appData,
  288. appParams: appParams || {} as ChatConfig,
  289. appMeta,
  290. appPinnedConversationData,
  291. appConversationData,
  292. appConversationDataLoading,
  293. appChatListData,
  294. appChatListDataLoading,
  295. appPrevChatList,
  296. pinnedConversationList,
  297. conversationList,
  298. setShowNewConversationItemInList,
  299. newConversationInputs,
  300. newConversationInputsRef,
  301. handleNewConversationInputsChange,
  302. inputsForms,
  303. handleNewConversation,
  304. handleStartChat,
  305. handleChangeConversation,
  306. handleNewConversationCompleted,
  307. newConversationId,
  308. chatShouldReloadKey,
  309. handleFeedback,
  310. currentChatInstanceRef,
  311. clearChatList,
  312. setClearChatList,
  313. isResponding,
  314. setIsResponding,
  315. }
  316. }