index.tsx 13 KB

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