index.tsx 14 KB

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