index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useRef, useState } from 'react'
  4. import { useBoolean } from 'ahooks'
  5. import { t } from 'i18next'
  6. import produce from 'immer'
  7. import cn from 'classnames'
  8. import TextGenerationRes from '@/app/components/app/text-generate/item'
  9. import NoData from '@/app/components/share/text-generation/no-data'
  10. import Toast from '@/app/components/base/toast'
  11. import { sendCompletionMessage, sendWorkflowMessage, updateFeedback } from '@/service/share'
  12. import type { Feedbacktype } from '@/app/components/app/chat/type'
  13. import Loading from '@/app/components/base/loading'
  14. import type { PromptConfig } from '@/models/debug'
  15. import type { InstalledApp } from '@/models/explore'
  16. import type { ModerationService } from '@/models/common'
  17. import { TransferMethod, type VisionFile, type VisionSettings } from '@/types/app'
  18. import { NodeRunningStatus, WorkflowRunningStatus } from '@/app/components/workflow/types'
  19. import type { WorkflowProcess } from '@/app/components/base/chat/types'
  20. import { sleep } from '@/utils'
  21. export type IResultProps = {
  22. isWorkflow: boolean
  23. isCallBatchAPI: boolean
  24. isPC: boolean
  25. isMobile: boolean
  26. isInstalledApp: boolean
  27. installedAppInfo?: InstalledApp
  28. isError: boolean
  29. isShowTextToSpeech: boolean
  30. promptConfig: PromptConfig | null
  31. moreLikeThisEnabled: boolean
  32. inputs: Record<string, any>
  33. controlSend?: number
  34. controlRetry?: number
  35. controlStopResponding?: number
  36. onShowRes: () => void
  37. handleSaveMessage: (messageId: string) => void
  38. taskId?: number
  39. onCompleted: (completionRes: string, taskId?: number, success?: boolean) => void
  40. enableModeration?: boolean
  41. moderationService?: (text: string) => ReturnType<ModerationService>
  42. visionConfig: VisionSettings
  43. completionFiles: VisionFile[]
  44. }
  45. const Result: FC<IResultProps> = ({
  46. isWorkflow,
  47. isCallBatchAPI,
  48. isPC,
  49. isMobile,
  50. isInstalledApp,
  51. installedAppInfo,
  52. isError,
  53. isShowTextToSpeech,
  54. promptConfig,
  55. moreLikeThisEnabled,
  56. inputs,
  57. controlSend,
  58. controlRetry,
  59. controlStopResponding,
  60. onShowRes,
  61. handleSaveMessage,
  62. taskId,
  63. onCompleted,
  64. visionConfig,
  65. completionFiles,
  66. }) => {
  67. const [isResponding, { setTrue: setRespondingTrue, setFalse: setRespondingFalse }] = useBoolean(false)
  68. useEffect(() => {
  69. if (controlStopResponding)
  70. setRespondingFalse()
  71. }, [controlStopResponding])
  72. const [completionRes, doSetCompletionRes] = useState<any>('')
  73. const completionResRef = useRef<any>()
  74. const setCompletionRes = (res: any) => {
  75. completionResRef.current = res
  76. doSetCompletionRes(res)
  77. }
  78. const getCompletionRes = () => completionResRef.current
  79. const [workflowProcessData, doSetWorkflowProccessData] = useState<WorkflowProcess>()
  80. const workflowProcessDataRef = useRef<WorkflowProcess>()
  81. const setWorkflowProccessData = (data: WorkflowProcess) => {
  82. workflowProcessDataRef.current = data
  83. doSetWorkflowProccessData(data)
  84. }
  85. const getWorkflowProccessData = () => workflowProcessDataRef.current
  86. const { notify } = Toast
  87. const isNoData = !completionRes
  88. const [messageId, setMessageId] = useState<string | null>(null)
  89. const [feedback, setFeedback] = useState<Feedbacktype>({
  90. rating: null,
  91. })
  92. const handleFeedback = async (feedback: Feedbacktype) => {
  93. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  94. setFeedback(feedback)
  95. }
  96. const logError = (message: string) => {
  97. notify({ type: 'error', message })
  98. }
  99. const checkCanSend = () => {
  100. // batch will check outer
  101. if (isCallBatchAPI)
  102. return true
  103. const prompt_variables = promptConfig?.prompt_variables
  104. if (!prompt_variables || prompt_variables?.length === 0) {
  105. if (completionFiles.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  106. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  107. return false
  108. }
  109. return true
  110. }
  111. let hasEmptyInput = ''
  112. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  113. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  114. return res
  115. }) || [] // compatible with old version
  116. requiredVars.forEach(({ key, name }) => {
  117. if (hasEmptyInput)
  118. return
  119. if (!inputs[key])
  120. hasEmptyInput = name
  121. })
  122. if (hasEmptyInput) {
  123. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  124. return false
  125. }
  126. if (completionFiles.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  127. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  128. return false
  129. }
  130. return !hasEmptyInput
  131. }
  132. const handleSend = async () => {
  133. if (isResponding) {
  134. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  135. return false
  136. }
  137. if (!checkCanSend())
  138. return
  139. const data: Record<string, any> = {
  140. inputs,
  141. }
  142. if (visionConfig.enabled && completionFiles && completionFiles?.length > 0) {
  143. data.files = completionFiles.map((item) => {
  144. if (item.transfer_method === TransferMethod.local_file) {
  145. return {
  146. ...item,
  147. url: '',
  148. }
  149. }
  150. return item
  151. })
  152. }
  153. setMessageId(null)
  154. setFeedback({
  155. rating: null,
  156. })
  157. setCompletionRes('')
  158. let res: string[] = []
  159. let tempMessageId = ''
  160. if (!isPC)
  161. onShowRes()
  162. setRespondingTrue()
  163. let isEnd = false
  164. let isTimeout = false;
  165. (async () => {
  166. await sleep(1000 * 60) // 1min timeout
  167. if (!isEnd) {
  168. setRespondingFalse()
  169. onCompleted(getCompletionRes(), taskId, false)
  170. isTimeout = true
  171. }
  172. })()
  173. if (isWorkflow) {
  174. sendWorkflowMessage(
  175. data,
  176. {
  177. onWorkflowStarted: ({ workflow_run_id }) => {
  178. tempMessageId = workflow_run_id
  179. setWorkflowProccessData({
  180. status: WorkflowRunningStatus.Running,
  181. tracing: [],
  182. expand: false,
  183. })
  184. setRespondingFalse()
  185. },
  186. onNodeStarted: ({ data }) => {
  187. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  188. draft.expand = true
  189. draft.tracing!.push({
  190. ...data,
  191. status: NodeRunningStatus.Running,
  192. expand: true,
  193. } as any)
  194. }))
  195. },
  196. onNodeFinished: ({ data }) => {
  197. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  198. const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id)
  199. if (currentIndex > -1 && draft.tracing) {
  200. draft.tracing[currentIndex] = {
  201. ...(draft.tracing[currentIndex].extras
  202. ? { extras: draft.tracing[currentIndex].extras }
  203. : {}),
  204. ...data,
  205. expand: !!data.error,
  206. } as any
  207. }
  208. }))
  209. },
  210. onWorkflowFinished: ({ data }) => {
  211. if (isTimeout)
  212. return
  213. if (data.error) {
  214. notify({ type: 'error', message: data.error })
  215. setRespondingFalse()
  216. onCompleted(getCompletionRes(), taskId, false)
  217. isEnd = true
  218. return
  219. }
  220. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  221. draft.status = data.error ? WorkflowRunningStatus.Failed : WorkflowRunningStatus.Succeeded
  222. }))
  223. if (!data.outputs)
  224. setCompletionRes('')
  225. else if (Object.keys(data.outputs).length > 1)
  226. setCompletionRes(data.outputs)
  227. else
  228. setCompletionRes(data.outputs[Object.keys(data.outputs)[0]])
  229. setRespondingFalse()
  230. setMessageId(tempMessageId)
  231. onCompleted(getCompletionRes(), taskId, true)
  232. isEnd = true
  233. },
  234. },
  235. isInstalledApp,
  236. installedAppInfo?.id,
  237. )
  238. }
  239. else {
  240. sendCompletionMessage(data, {
  241. onData: (data: string, _isFirstMessage: boolean, { messageId }) => {
  242. tempMessageId = messageId
  243. res.push(data)
  244. setCompletionRes(res.join(''))
  245. },
  246. onCompleted: () => {
  247. if (isTimeout)
  248. return
  249. setRespondingFalse()
  250. setMessageId(tempMessageId)
  251. onCompleted(getCompletionRes(), taskId, true)
  252. isEnd = true
  253. },
  254. onMessageReplace: (messageReplace) => {
  255. res = [messageReplace.answer]
  256. setCompletionRes(res.join(''))
  257. },
  258. onError() {
  259. if (isTimeout)
  260. return
  261. setRespondingFalse()
  262. onCompleted(getCompletionRes(), taskId, false)
  263. isEnd = true
  264. },
  265. }, isInstalledApp, installedAppInfo?.id)
  266. }
  267. }
  268. const [controlClearMoreLikeThis, setControlClearMoreLikeThis] = useState(0)
  269. useEffect(() => {
  270. if (controlSend) {
  271. handleSend()
  272. setControlClearMoreLikeThis(Date.now())
  273. }
  274. }, [controlSend])
  275. useEffect(() => {
  276. if (controlRetry)
  277. handleSend()
  278. }, [controlRetry])
  279. const renderTextGenerationRes = () => (
  280. <TextGenerationRes
  281. isWorkflow={isWorkflow}
  282. workflowProcessData={workflowProcessData}
  283. className='mt-3'
  284. isError={isError}
  285. onRetry={handleSend}
  286. content={completionRes}
  287. messageId={messageId}
  288. isInWebApp
  289. moreLikeThis={moreLikeThisEnabled}
  290. onFeedback={handleFeedback}
  291. feedback={feedback}
  292. onSave={handleSaveMessage}
  293. isMobile={isMobile}
  294. isInstalledApp={isInstalledApp}
  295. installedAppId={installedAppInfo?.id}
  296. isLoading={isCallBatchAPI ? (!completionRes && isResponding) : false}
  297. taskId={isCallBatchAPI ? ((taskId as number) < 10 ? `0${taskId}` : `${taskId}`) : undefined}
  298. controlClearMoreLikeThis={controlClearMoreLikeThis}
  299. isShowTextToSpeech={isShowTextToSpeech}
  300. />
  301. )
  302. return (
  303. <div className={cn(isNoData && !isCallBatchAPI && 'h-full')}>
  304. {!isCallBatchAPI && (
  305. (isResponding && !completionRes)
  306. ? (
  307. <div className='flex h-full w-full justify-center items-center'>
  308. <Loading type='area' />
  309. </div>)
  310. : (
  311. <>
  312. {(isNoData && !workflowProcessData)
  313. ? <NoData />
  314. : renderTextGenerationRes()
  315. }
  316. </>
  317. )
  318. )}
  319. {isCallBatchAPI && (
  320. <div className='mt-2'>
  321. {renderTextGenerationRes()}
  322. </div>
  323. )}
  324. </div>
  325. )
  326. }
  327. export default React.memo(Result)