index.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 cn from 'classnames'
  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, updateFeedback } from '@/service/share'
  11. import type { Feedbacktype } from '@/app/components/app/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 type { ModerationService } from '@/models/common'
  16. import { TransferMethod, type VisionFile, type VisionSettings } from '@/types/app'
  17. export type IResultProps = {
  18. isCallBatchAPI: boolean
  19. isPC: boolean
  20. isMobile: boolean
  21. isInstalledApp: boolean
  22. installedAppInfo?: InstalledApp
  23. isError: boolean
  24. isShowTextToSpeech: boolean
  25. promptConfig: PromptConfig | null
  26. moreLikeThisEnabled: boolean
  27. inputs: Record<string, any>
  28. controlSend?: number
  29. controlRetry?: number
  30. controlStopResponding?: number
  31. onShowRes: () => void
  32. handleSaveMessage: (messageId: string) => void
  33. taskId?: number
  34. onCompleted: (completionRes: string, taskId?: number, success?: boolean) => void
  35. enableModeration?: boolean
  36. moderationService?: (text: string) => ReturnType<ModerationService>
  37. visionConfig: VisionSettings
  38. completionFiles: VisionFile[]
  39. }
  40. const Result: FC<IResultProps> = ({
  41. isCallBatchAPI,
  42. isPC,
  43. isMobile,
  44. isInstalledApp,
  45. installedAppInfo,
  46. isError,
  47. isShowTextToSpeech,
  48. promptConfig,
  49. moreLikeThisEnabled,
  50. inputs,
  51. controlSend,
  52. controlRetry,
  53. controlStopResponding,
  54. onShowRes,
  55. handleSaveMessage,
  56. taskId,
  57. onCompleted,
  58. visionConfig,
  59. completionFiles,
  60. }) => {
  61. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  62. useEffect(() => {
  63. if (controlStopResponding)
  64. setResponsingFalse()
  65. }, [controlStopResponding])
  66. const [completionRes, doSetCompletionRes] = useState('')
  67. const completionResRef = useRef('')
  68. const setCompletionRes = (res: string) => {
  69. completionResRef.current = res
  70. doSetCompletionRes(res)
  71. }
  72. const getCompletionRes = () => completionResRef.current
  73. const { notify } = Toast
  74. const isNoData = !completionRes
  75. const [messageId, setMessageId] = useState<string | null>(null)
  76. const [feedback, setFeedback] = useState<Feedbacktype>({
  77. rating: null,
  78. })
  79. const handleFeedback = async (feedback: Feedbacktype) => {
  80. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  81. setFeedback(feedback)
  82. }
  83. const logError = (message: string) => {
  84. notify({ type: 'error', message })
  85. }
  86. const checkCanSend = () => {
  87. // batch will check outer
  88. if (isCallBatchAPI)
  89. return true
  90. const prompt_variables = promptConfig?.prompt_variables
  91. if (!prompt_variables || prompt_variables?.length === 0)
  92. return true
  93. let hasEmptyInput = ''
  94. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  95. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  96. return res
  97. }) || [] // compatible with old version
  98. requiredVars.forEach(({ key, name }) => {
  99. if (hasEmptyInput)
  100. return
  101. if (!inputs[key])
  102. hasEmptyInput = name
  103. })
  104. if (hasEmptyInput) {
  105. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  106. return false
  107. }
  108. if (completionFiles.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  109. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  110. return false
  111. }
  112. return !hasEmptyInput
  113. }
  114. const handleSend = async () => {
  115. if (isResponsing) {
  116. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  117. return false
  118. }
  119. if (!checkCanSend())
  120. return
  121. const data: Record<string, any> = {
  122. inputs,
  123. }
  124. if (visionConfig.enabled && completionFiles && completionFiles?.length > 0) {
  125. data.files = completionFiles.map((item) => {
  126. if (item.transfer_method === TransferMethod.local_file) {
  127. return {
  128. ...item,
  129. url: '',
  130. }
  131. }
  132. return item
  133. })
  134. }
  135. setMessageId(null)
  136. setFeedback({
  137. rating: null,
  138. })
  139. setCompletionRes('')
  140. let res: string[] = []
  141. let tempMessageId = ''
  142. if (!isPC)
  143. onShowRes()
  144. setResponsingTrue()
  145. const startTime = Date.now()
  146. let isTimeout = false
  147. const runId = setInterval(() => {
  148. if (Date.now() - startTime > 1000 * 60) { // 1min timeout
  149. clearInterval(runId)
  150. setResponsingFalse()
  151. onCompleted(getCompletionRes(), taskId, false)
  152. isTimeout = true
  153. }
  154. }, 1000)
  155. sendCompletionMessage(data, {
  156. onData: (data: string, _isFirstMessage: boolean, { messageId }) => {
  157. tempMessageId = messageId
  158. res.push(data)
  159. setCompletionRes(res.join(''))
  160. },
  161. onCompleted: () => {
  162. if (isTimeout)
  163. return
  164. setResponsingFalse()
  165. setMessageId(tempMessageId)
  166. onCompleted(getCompletionRes(), taskId, true)
  167. clearInterval(runId)
  168. },
  169. onMessageReplace: (messageReplace) => {
  170. res = [messageReplace.answer]
  171. setCompletionRes(res.join(''))
  172. },
  173. onError() {
  174. if (isTimeout)
  175. return
  176. setResponsingFalse()
  177. onCompleted(getCompletionRes(), taskId, false)
  178. clearInterval(runId)
  179. },
  180. }, isInstalledApp, installedAppInfo?.id)
  181. }
  182. const [controlClearMoreLikeThis, setControlClearMoreLikeThis] = useState(0)
  183. useEffect(() => {
  184. if (controlSend) {
  185. handleSend()
  186. setControlClearMoreLikeThis(Date.now())
  187. }
  188. }, [controlSend])
  189. useEffect(() => {
  190. if (controlRetry)
  191. handleSend()
  192. }, [controlRetry])
  193. const renderTextGenerationRes = () => (
  194. <TextGenerationRes
  195. className='mt-3'
  196. isError={isError}
  197. onRetry={handleSend}
  198. content={completionRes}
  199. messageId={messageId}
  200. isInWebApp
  201. moreLikeThis={moreLikeThisEnabled}
  202. onFeedback={handleFeedback}
  203. feedback={feedback}
  204. onSave={handleSaveMessage}
  205. isMobile={isMobile}
  206. isInstalledApp={isInstalledApp}
  207. installedAppId={installedAppInfo?.id}
  208. isLoading={isCallBatchAPI ? (!completionRes && isResponsing) : false}
  209. taskId={isCallBatchAPI ? ((taskId as number) < 10 ? `0${taskId}` : `${taskId}`) : undefined}
  210. controlClearMoreLikeThis={controlClearMoreLikeThis}
  211. isShowTextToSpeech={isShowTextToSpeech}
  212. />
  213. )
  214. return (
  215. <div className={cn(isNoData && !isCallBatchAPI && 'h-full')}>
  216. {!isCallBatchAPI && (
  217. (isResponsing && !completionRes)
  218. ? (
  219. <div className='flex h-full w-full justify-center items-center'>
  220. <Loading type='area' />
  221. </div>)
  222. : (
  223. <>
  224. {isNoData
  225. ? <NoData />
  226. : renderTextGenerationRes()
  227. }
  228. </>
  229. )
  230. )}
  231. {isCallBatchAPI && (
  232. <div className='mt-2'>
  233. {renderTextGenerationRes()}
  234. </div>
  235. )}
  236. </div>
  237. )
  238. }
  239. export default React.memo(Result)