hooks.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. setInitInputs(getProcessedInputsFromUrlParams())
  170. }, [])
  171. useEffect(() => {
  172. const conversationInputs: Record<string, any> = {}
  173. inputsForms.forEach((item: any) => {
  174. conversationInputs[item.variable] = item.default || null
  175. })
  176. handleNewConversationInputsChange(conversationInputs)
  177. }, [handleNewConversationInputsChange, inputsForms])
  178. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  179. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  180. useEffect(() => {
  181. if (appConversationData?.data && !appConversationDataLoading)
  182. setOriginConversationList(appConversationData?.data)
  183. }, [appConversationData, appConversationDataLoading])
  184. const conversationList = useMemo(() => {
  185. const data = originConversationList.slice()
  186. if (showNewConversationItemInList && data[0]?.id !== '') {
  187. data.unshift({
  188. id: '',
  189. name: t('share.chat.newChatDefaultName'),
  190. inputs: {},
  191. introduction: '',
  192. })
  193. }
  194. return data
  195. }, [originConversationList, showNewConversationItemInList, t])
  196. useEffect(() => {
  197. if (newConversation) {
  198. setOriginConversationList(produce((draft) => {
  199. const index = draft.findIndex(item => item.id === newConversation.id)
  200. if (index > -1)
  201. draft[index] = newConversation
  202. else
  203. draft.unshift(newConversation)
  204. }))
  205. }
  206. }, [newConversation])
  207. const currentConversationItem = useMemo(() => {
  208. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  209. if (!conversationItem && pinnedConversationList.length)
  210. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  211. return conversationItem
  212. }, [conversationList, currentConversationId, pinnedConversationList])
  213. const { notify } = useToastContext()
  214. const checkInputsRequired = useCallback((silent?: boolean) => {
  215. let hasEmptyInput = ''
  216. let fileIsUploading = false
  217. const requiredVars = inputsForms.filter(({ required }) => required)
  218. if (requiredVars.length) {
  219. requiredVars.forEach(({ variable, label, type }) => {
  220. if (hasEmptyInput)
  221. return
  222. if (fileIsUploading)
  223. return
  224. if (!newConversationInputsRef.current[variable] && !silent)
  225. hasEmptyInput = label as string
  226. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  227. const files = newConversationInputsRef.current[variable]
  228. if (Array.isArray(files))
  229. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  230. else
  231. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  232. }
  233. })
  234. }
  235. if (hasEmptyInput) {
  236. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  237. return false
  238. }
  239. if (fileIsUploading) {
  240. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  241. return
  242. }
  243. return true
  244. }, [inputsForms, notify, t])
  245. const handleStartChat = useCallback((callback?: any) => {
  246. if (checkInputsRequired()) {
  247. setShowNewConversationItemInList(true)
  248. callback?.()
  249. }
  250. }, [setShowNewConversationItemInList, checkInputsRequired])
  251. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: () => { } })
  252. const handleChangeConversation = useCallback((conversationId: string) => {
  253. currentChatInstanceRef.current.handleStop()
  254. setNewConversationId('')
  255. handleConversationIdInfoChange(conversationId)
  256. if (conversationId)
  257. setClearChatList(false)
  258. }, [handleConversationIdInfoChange, setClearChatList])
  259. const handleNewConversation = useCallback(() => {
  260. currentChatInstanceRef.current.handleStop()
  261. setShowNewConversationItemInList(true)
  262. handleChangeConversation('')
  263. handleNewConversationInputsChange({})
  264. setClearChatList(true)
  265. }, [handleChangeConversation, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])
  266. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  267. setNewConversationId(newConversationId)
  268. handleConversationIdInfoChange(newConversationId)
  269. setShowNewConversationItemInList(false)
  270. mutateAppConversationData()
  271. }, [mutateAppConversationData, handleConversationIdInfoChange])
  272. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  273. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  274. notify({ type: 'success', message: t('common.api.success') })
  275. }, [isInstalledApp, appId, t, notify])
  276. return {
  277. appInfoError,
  278. appInfoLoading,
  279. isInstalledApp,
  280. appId,
  281. currentConversationId,
  282. currentConversationItem,
  283. handleConversationIdInfoChange,
  284. appData,
  285. appParams: appParams || {} as ChatConfig,
  286. appMeta,
  287. appPinnedConversationData,
  288. appConversationData,
  289. appConversationDataLoading,
  290. appChatListData,
  291. appChatListDataLoading,
  292. appPrevChatList,
  293. pinnedConversationList,
  294. conversationList,
  295. setShowNewConversationItemInList,
  296. newConversationInputs,
  297. newConversationInputsRef,
  298. handleNewConversationInputsChange,
  299. inputsForms,
  300. handleNewConversation,
  301. handleStartChat,
  302. handleChangeConversation,
  303. handleNewConversationCompleted,
  304. newConversationId,
  305. chatShouldReloadKey,
  306. handleFeedback,
  307. currentChatInstanceRef,
  308. clearChatList,
  309. setClearChatList,
  310. isResponding,
  311. setIsResponding,
  312. }
  313. }