index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. resultText: '',
  184. })
  185. setRespondingFalse()
  186. },
  187. onNodeStarted: ({ data }) => {
  188. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  189. draft.expand = true
  190. draft.tracing!.push({
  191. ...data,
  192. status: NodeRunningStatus.Running,
  193. expand: true,
  194. } as any)
  195. }))
  196. },
  197. onNodeFinished: ({ data }) => {
  198. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  199. const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id)
  200. if (currentIndex > -1 && draft.tracing) {
  201. draft.tracing[currentIndex] = {
  202. ...(draft.tracing[currentIndex].extras
  203. ? { extras: draft.tracing[currentIndex].extras }
  204. : {}),
  205. ...data,
  206. expand: !!data.error,
  207. } as any
  208. }
  209. }))
  210. },
  211. onWorkflowFinished: ({ data }) => {
  212. if (isTimeout)
  213. return
  214. if (data.error) {
  215. notify({ type: 'error', message: data.error })
  216. setRespondingFalse()
  217. onCompleted(getCompletionRes(), taskId, false)
  218. isEnd = true
  219. return
  220. }
  221. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  222. draft.status = data.error ? WorkflowRunningStatus.Failed : WorkflowRunningStatus.Succeeded
  223. }))
  224. if (!data.outputs)
  225. setCompletionRes('')
  226. else
  227. setCompletionRes(data.outputs)
  228. setRespondingFalse()
  229. setMessageId(tempMessageId)
  230. onCompleted(getCompletionRes(), taskId, true)
  231. isEnd = true
  232. },
  233. onTextChunk: (params) => {
  234. const { data: { text } } = params
  235. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  236. draft.resultText += text
  237. }))
  238. },
  239. onTextReplace: (params) => {
  240. const { data: { text } } = params
  241. setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {
  242. draft.resultText = text
  243. }))
  244. },
  245. },
  246. isInstalledApp,
  247. installedAppInfo?.id,
  248. )
  249. }
  250. else {
  251. sendCompletionMessage(data, {
  252. onData: (data: string, _isFirstMessage: boolean, { messageId }) => {
  253. tempMessageId = messageId
  254. res.push(data)
  255. setCompletionRes(res.join(''))
  256. },
  257. onCompleted: () => {
  258. if (isTimeout)
  259. return
  260. setRespondingFalse()
  261. setMessageId(tempMessageId)
  262. onCompleted(getCompletionRes(), taskId, true)
  263. isEnd = true
  264. },
  265. onMessageReplace: (messageReplace) => {
  266. res = [messageReplace.answer]
  267. setCompletionRes(res.join(''))
  268. },
  269. onError() {
  270. if (isTimeout)
  271. return
  272. setRespondingFalse()
  273. onCompleted(getCompletionRes(), taskId, false)
  274. isEnd = true
  275. },
  276. }, isInstalledApp, installedAppInfo?.id)
  277. }
  278. }
  279. const [controlClearMoreLikeThis, setControlClearMoreLikeThis] = useState(0)
  280. useEffect(() => {
  281. if (controlSend) {
  282. handleSend()
  283. setControlClearMoreLikeThis(Date.now())
  284. }
  285. }, [controlSend])
  286. useEffect(() => {
  287. if (controlRetry)
  288. handleSend()
  289. }, [controlRetry])
  290. const renderTextGenerationRes = () => (
  291. <TextGenerationRes
  292. isWorkflow={isWorkflow}
  293. workflowProcessData={workflowProcessData}
  294. className='mt-3'
  295. isError={isError}
  296. onRetry={handleSend}
  297. content={completionRes}
  298. messageId={messageId}
  299. isInWebApp
  300. moreLikeThis={moreLikeThisEnabled}
  301. onFeedback={handleFeedback}
  302. feedback={feedback}
  303. onSave={handleSaveMessage}
  304. isMobile={isMobile}
  305. isInstalledApp={isInstalledApp}
  306. installedAppId={installedAppInfo?.id}
  307. isLoading={isCallBatchAPI ? (!completionRes && isResponding) : false}
  308. taskId={isCallBatchAPI ? ((taskId as number) < 10 ? `0${taskId}` : `${taskId}`) : undefined}
  309. controlClearMoreLikeThis={controlClearMoreLikeThis}
  310. isShowTextToSpeech={isShowTextToSpeech}
  311. hideProcessDetail
  312. />
  313. )
  314. return (
  315. <div className={cn(isNoData && !isCallBatchAPI && 'h-full')}>
  316. {!isCallBatchAPI && (
  317. (isResponding && !completionRes)
  318. ? (
  319. <div className='flex h-full w-full justify-center items-center'>
  320. <Loading type='area' />
  321. </div>)
  322. : (
  323. <>
  324. {(isNoData && !workflowProcessData)
  325. ? <NoData />
  326. : renderTextGenerationRes()
  327. }
  328. </>
  329. )
  330. )}
  331. {isCallBatchAPI && (
  332. <div className='mt-2'>
  333. {renderTextGenerationRes()}
  334. </div>
  335. )}
  336. </div>
  337. )
  338. }
  339. export default React.memo(Result)