index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useDebounce } from 'ahooks'
  6. import Toast from '../../base/toast'
  7. import Filter from './filter'
  8. import type { QueryParam } from './filter'
  9. import List from './list'
  10. import EmptyElement from './empty-element'
  11. import HeaderOpts from './header-opts'
  12. import { AnnotationEnableStatus, type AnnotationItem, type AnnotationItemBasic, JobStatus } from './type'
  13. import ViewAnnotationModal from './view-annotation-modal'
  14. import cn from '@/utils/classnames'
  15. import Pagination from '@/app/components/base/pagination'
  16. import Switch from '@/app/components/base/switch'
  17. import { addAnnotation, delAnnotation, fetchAnnotationConfig as doFetchAnnotationConfig, editAnnotation, fetchAnnotationList, queryAnnotationJobStatus, updateAnnotationScore, updateAnnotationStatus } from '@/service/annotation'
  18. import Loading from '@/app/components/base/loading'
  19. import { APP_PAGE_LIMIT } from '@/config'
  20. import ConfigParamModal from '@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal'
  21. import type { AnnotationReplyConfig } from '@/models/debug'
  22. import { sleep } from '@/utils'
  23. import { useProviderContext } from '@/context/provider-context'
  24. import AnnotationFullModal from '@/app/components/billing/annotation-full/modal'
  25. import { Settings04 } from '@/app/components/base/icons/src/vender/line/general'
  26. import type { App } from '@/types/app'
  27. type Props = {
  28. appDetail: App
  29. }
  30. const Annotation: FC<Props> = ({
  31. appDetail,
  32. }) => {
  33. const { t } = useTranslation()
  34. const [isShowEdit, setIsShowEdit] = React.useState(false)
  35. const [annotationConfig, setAnnotationConfig] = useState<AnnotationReplyConfig | null>(null)
  36. const [isChatApp, setIsChatApp] = useState(false)
  37. const fetchAnnotationConfig = async () => {
  38. const res = await doFetchAnnotationConfig(appDetail.id)
  39. setAnnotationConfig(res as AnnotationReplyConfig)
  40. return (res as AnnotationReplyConfig).id
  41. }
  42. useEffect(() => {
  43. const isChatApp = appDetail.mode !== 'completion'
  44. setIsChatApp(isChatApp)
  45. if (isChatApp)
  46. fetchAnnotationConfig()
  47. }, [])
  48. const [controlRefreshSwitch, setControlRefreshSwitch] = useState(Date.now())
  49. const { plan, enableBilling } = useProviderContext()
  50. const isAnnotationFull = (enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse)
  51. const [isShowAnnotationFullModal, setIsShowAnnotationFullModal] = useState(false)
  52. const ensureJobCompleted = async (jobId: string, status: AnnotationEnableStatus) => {
  53. let isCompleted = false
  54. while (!isCompleted) {
  55. const res: any = await queryAnnotationJobStatus(appDetail.id, status, jobId)
  56. isCompleted = res.job_status === JobStatus.completed
  57. if (isCompleted)
  58. break
  59. await sleep(2000)
  60. }
  61. }
  62. const [queryParams, setQueryParams] = useState<QueryParam>({})
  63. const [currPage, setCurrPage] = React.useState<number>(0)
  64. const debouncedQueryParams = useDebounce(queryParams, { wait: 500 })
  65. const [limit, setLimit] = React.useState<number>(APP_PAGE_LIMIT)
  66. const query = {
  67. page: currPage + 1,
  68. limit,
  69. keyword: debouncedQueryParams.keyword || '',
  70. }
  71. const [controlUpdateList, setControlUpdateList] = useState(Date.now())
  72. const [list, setList] = useState<AnnotationItem[]>([])
  73. const [total, setTotal] = useState(10)
  74. const [isLoading, setIsLoading] = useState(false)
  75. const fetchList = async (page = 1) => {
  76. setIsLoading(true)
  77. try {
  78. const { data, total }: any = await fetchAnnotationList(appDetail.id, {
  79. ...query,
  80. page,
  81. })
  82. setList(data as AnnotationItem[])
  83. setTotal(total)
  84. }
  85. catch (e) {
  86. }
  87. setIsLoading(false)
  88. }
  89. useEffect(() => {
  90. fetchList(currPage + 1)
  91. }, [currPage])
  92. useEffect(() => {
  93. fetchList(1)
  94. setControlUpdateList(Date.now())
  95. }, [queryParams])
  96. const handleAdd = async (payload: AnnotationItemBasic) => {
  97. await addAnnotation(appDetail.id, {
  98. ...payload,
  99. })
  100. Toast.notify({
  101. message: t('common.api.actionSuccess'),
  102. type: 'success',
  103. })
  104. fetchList()
  105. setControlUpdateList(Date.now())
  106. }
  107. const handleRemove = async (id: string) => {
  108. await delAnnotation(appDetail.id, id)
  109. Toast.notify({
  110. message: t('common.api.actionSuccess'),
  111. type: 'success',
  112. })
  113. fetchList()
  114. setControlUpdateList(Date.now())
  115. }
  116. const [currItem, setCurrItem] = useState<AnnotationItem | null>(list[0])
  117. const [isShowViewModal, setIsShowViewModal] = useState(false)
  118. useEffect(() => {
  119. if (!isShowEdit)
  120. setControlRefreshSwitch(Date.now())
  121. }, [isShowEdit])
  122. const handleView = (item: AnnotationItem) => {
  123. setCurrItem(item)
  124. setIsShowViewModal(true)
  125. }
  126. const handleSave = async (question: string, answer: string) => {
  127. await editAnnotation(appDetail.id, (currItem as AnnotationItem).id, {
  128. question,
  129. answer,
  130. })
  131. Toast.notify({
  132. message: t('common.api.actionSuccess'),
  133. type: 'success',
  134. })
  135. fetchList()
  136. setControlUpdateList(Date.now())
  137. }
  138. return (
  139. <div className='flex flex-col h-full'>
  140. <p className='text-text-tertiary system-sm-regular'>{t('appLog.description')}</p>
  141. <div className='flex flex-col py-4 flex-1'>
  142. <Filter appId={appDetail.id} queryParams={queryParams} setQueryParams={setQueryParams}>
  143. <div className='flex items-center space-x-2'>
  144. {isChatApp && (
  145. <>
  146. <div className={cn(!annotationConfig?.enabled && 'pr-2', 'flex items-center h-7 rounded-lg border border-gray-200 pl-2 space-x-1')}>
  147. <div className='leading-[18px] text-[13px] font-medium text-gray-900'>{t('appAnnotation.name')}</div>
  148. <Switch
  149. key={controlRefreshSwitch}
  150. defaultValue={annotationConfig?.enabled}
  151. size='md'
  152. onChange={async (value) => {
  153. if (value) {
  154. if (isAnnotationFull) {
  155. setIsShowAnnotationFullModal(true)
  156. setControlRefreshSwitch(Date.now())
  157. return
  158. }
  159. setIsShowEdit(true)
  160. }
  161. else {
  162. const { job_id: jobId }: any = await updateAnnotationStatus(appDetail.id, AnnotationEnableStatus.disable, annotationConfig?.embedding_model, annotationConfig?.score_threshold)
  163. await ensureJobCompleted(jobId, AnnotationEnableStatus.disable)
  164. await fetchAnnotationConfig()
  165. Toast.notify({
  166. message: t('common.api.actionSuccess'),
  167. type: 'success',
  168. })
  169. }
  170. }}
  171. ></Switch>
  172. {annotationConfig?.enabled && (
  173. <div className='flex items-center pl-1.5'>
  174. <div className='shrink-0 mr-1 w-[1px] h-3.5 bg-gray-200'></div>
  175. <div
  176. className={`
  177. shrink-0 h-7 w-7 flex items-center justify-center
  178. text-xs text-gray-700 font-medium
  179. `}
  180. onClick={() => { setIsShowEdit(true) }}
  181. >
  182. <div className='flex h-6 w-6 items-center justify-center rounded-md cursor-pointer hover:bg-gray-200'>
  183. <Settings04 className='w-4 h-4' />
  184. </div>
  185. </div>
  186. </div>
  187. )}
  188. </div>
  189. <div className='shrink-0 mx-3 w-[1px] h-3.5 bg-gray-200'></div>
  190. </>
  191. )}
  192. <HeaderOpts
  193. appId={appDetail.id}
  194. controlUpdateList={controlUpdateList}
  195. onAdd={handleAdd}
  196. onAdded={() => {
  197. fetchList()
  198. }}
  199. />
  200. </div>
  201. </Filter>
  202. {isLoading
  203. ? <Loading type='app' />
  204. : total > 0
  205. ? <List
  206. list={list}
  207. onRemove={handleRemove}
  208. onView={handleView}
  209. />
  210. : <div className='grow flex h-full items-center justify-center'><EmptyElement /></div>
  211. }
  212. {/* Show Pagination only if the total is more than the limit */}
  213. {(total && total > APP_PAGE_LIMIT)
  214. ? <Pagination
  215. current={currPage}
  216. onChange={setCurrPage}
  217. total={total}
  218. limit={limit}
  219. onLimitChange={setLimit}
  220. />
  221. : null}
  222. {isShowViewModal && (
  223. <ViewAnnotationModal
  224. appId={appDetail.id}
  225. isShow={isShowViewModal}
  226. onHide={() => setIsShowViewModal(false)}
  227. onRemove={async () => {
  228. await handleRemove((currItem as AnnotationItem)?.id)
  229. }}
  230. item={currItem as AnnotationItem}
  231. onSave={handleSave}
  232. />
  233. )}
  234. {isShowEdit && (
  235. <ConfigParamModal
  236. appId={appDetail.id}
  237. isShow
  238. isInit={!annotationConfig?.enabled}
  239. onHide={() => {
  240. setIsShowEdit(false)
  241. }}
  242. onSave={async (embeddingModel, score) => {
  243. if (
  244. embeddingModel.embedding_model_name !== annotationConfig?.embedding_model?.embedding_model_name
  245. || embeddingModel.embedding_provider_name !== annotationConfig?.embedding_model?.embedding_provider_name
  246. ) {
  247. const { job_id: jobId }: any = await updateAnnotationStatus(appDetail.id, AnnotationEnableStatus.enable, embeddingModel, score)
  248. await ensureJobCompleted(jobId, AnnotationEnableStatus.enable)
  249. }
  250. const annotationId = await fetchAnnotationConfig()
  251. if (score !== annotationConfig?.score_threshold)
  252. await updateAnnotationScore(appDetail.id, annotationId, score)
  253. await fetchAnnotationConfig()
  254. Toast.notify({
  255. message: t('common.api.actionSuccess'),
  256. type: 'success',
  257. })
  258. setIsShowEdit(false)
  259. }}
  260. annotationConfig={annotationConfig!}
  261. />
  262. )}
  263. {
  264. isShowAnnotationFullModal && (
  265. <AnnotationFullModal
  266. show={isShowAnnotationFullModal}
  267. onHide={() => setIsShowAnnotationFullModal(false)}
  268. />
  269. )
  270. }
  271. </div>
  272. </div>
  273. )
  274. }
  275. export default React.memo(Annotation)