hooks.tsx 13 KB

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