index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { Pagination } from 'react-headless-pagination'
  6. import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline'
  7. import cn from 'classnames'
  8. import Toast from '../../base/toast'
  9. import Filter from './filter'
  10. import type { QueryParam } from './filter'
  11. import List from './list'
  12. import EmptyElement from './empty-element'
  13. import HeaderOpts from './header-opts'
  14. import s from './style.module.css'
  15. import { AnnotationEnableStatus, type AnnotationItem, type AnnotationItemBasic, JobStatus } from './type'
  16. import ViewAnnotationModal from './view-annotation-modal'
  17. import Switch from '@/app/components/base/switch'
  18. import { addAnnotation, delAnnotation, fetchAnnotationConfig as doFetchAnnotationConfig, editAnnotation, fetchAnnotationList, queryAnnotationJobStatus, updateAnnotationScore, updateAnnotationStatus } from '@/service/annotation'
  19. import Loading from '@/app/components/base/loading'
  20. import { APP_PAGE_LIMIT } from '@/config'
  21. import ConfigParamModal from '@/app/components/app/configuration/toolbox/annotation/config-param-modal'
  22. import type { AnnotationReplyConfig } from '@/models/debug'
  23. import { sleep } from '@/utils'
  24. import { useProviderContext } from '@/context/provider-context'
  25. import AnnotationFullModal from '@/app/components/billing/annotation-full/modal'
  26. import { Settings04 } from '@/app/components/base/icons/src/vender/line/general'
  27. import { fetchAppDetail } from '@/service/apps'
  28. type Props = {
  29. appId: string
  30. }
  31. const Annotation: FC<Props> = ({
  32. appId,
  33. }) => {
  34. const { t } = useTranslation()
  35. const [isShowEdit, setIsShowEdit] = React.useState(false)
  36. const [annotationConfig, setAnnotationConfig] = useState<AnnotationReplyConfig | null>(null)
  37. const [isChatApp, setIsChatApp] = useState(false)
  38. const fetchAnnotationConfig = async () => {
  39. const res = await doFetchAnnotationConfig(appId)
  40. setAnnotationConfig(res as AnnotationReplyConfig)
  41. }
  42. useEffect(() => {
  43. fetchAppDetail({ url: '/apps', id: appId }).then(async (res: any) => {
  44. const isChatApp = res.mode === 'chat'
  45. setIsChatApp(isChatApp)
  46. if (isChatApp)
  47. fetchAnnotationConfig()
  48. })
  49. }, [])
  50. const [controlRefreshSwitch, setControlRefreshSwitch] = useState(Date.now())
  51. const { plan, enableBilling } = useProviderContext()
  52. const isAnnotationFull = (enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse)
  53. const [isShowAnnotationFullModal, setIsShowAnnotationFullModal] = useState(false)
  54. const ensureJobCompleted = async (jobId: string, status: AnnotationEnableStatus) => {
  55. let isCompleted = false
  56. while (!isCompleted) {
  57. const res: any = await queryAnnotationJobStatus(appId, status, jobId)
  58. isCompleted = res.job_status === JobStatus.completed
  59. if (isCompleted)
  60. break
  61. await sleep(2000)
  62. }
  63. }
  64. const [queryParams, setQueryParams] = useState<QueryParam>({})
  65. const [currPage, setCurrPage] = React.useState<number>(0)
  66. const query = {
  67. page: currPage + 1,
  68. limit: APP_PAGE_LIMIT,
  69. keyword: queryParams.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(appId, {
  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(appId, {
  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(appId, 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(appId, (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='flex text-sm font-normal text-gray-500'>{t('appLog.description')}</p>
  141. <div className='grow flex flex-col py-4 '>
  142. <Filter appId={appId} 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(appId, 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={appId}
  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. className="flex items-center w-full h-10 text-sm select-none mt-8"
  216. currentPage={currPage}
  217. edgePageCount={2}
  218. middlePagesSiblingCount={1}
  219. setCurrentPage={setCurrPage}
  220. totalPages={Math.ceil(total / APP_PAGE_LIMIT)}
  221. truncableClassName="w-8 px-0.5 text-center"
  222. truncableText="..."
  223. >
  224. <Pagination.PrevButton
  225. disabled={currPage === 0}
  226. className={`flex items-center mr-2 text-gray-500 focus:outline-none ${currPage === 0 ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:text-gray-600 dark:hover:text-gray-200'}`} >
  227. <ArrowLeftIcon className="mr-3 h-3 w-3" />
  228. {t('appLog.table.pagination.previous')}
  229. </Pagination.PrevButton>
  230. <div className={`flex items-center justify-center flex-grow ${s.pagination}`}>
  231. <Pagination.PageButton
  232. activeClassName="bg-primary-50 dark:bg-opacity-0 text-primary-600 dark:text-white"
  233. className="flex items-center justify-center h-8 w-8 rounded-full cursor-pointer"
  234. inactiveClassName="text-gray-500"
  235. />
  236. </div>
  237. <Pagination.NextButton
  238. disabled={currPage === Math.ceil(total / APP_PAGE_LIMIT) - 1}
  239. className={`flex items-center mr-2 text-gray-500 focus:outline-none ${currPage === Math.ceil(total / APP_PAGE_LIMIT) - 1 ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:text-gray-600 dark:hover:text-gray-200'}`} >
  240. {t('appLog.table.pagination.next')}
  241. <ArrowRightIcon className="ml-3 h-3 w-3" />
  242. </Pagination.NextButton>
  243. </Pagination>
  244. : null}
  245. {isShowViewModal && (
  246. <ViewAnnotationModal
  247. appId={appId}
  248. isShow={isShowViewModal}
  249. onHide={() => setIsShowViewModal(false)}
  250. onRemove={async () => {
  251. await handleRemove((currItem as AnnotationItem)?.id)
  252. }}
  253. item={currItem as AnnotationItem}
  254. onSave={handleSave}
  255. />
  256. )}
  257. {isShowEdit && (
  258. <ConfigParamModal
  259. appId={appId}
  260. isShow
  261. isInit={!annotationConfig?.enabled}
  262. onHide={() => {
  263. setIsShowEdit(false)
  264. }}
  265. onSave={async (embeddingModel, score) => {
  266. if (
  267. embeddingModel.embedding_model_name !== annotationConfig?.embedding_model?.embedding_model_name
  268. && embeddingModel.embedding_provider_name !== annotationConfig?.embedding_model?.embedding_provider_name
  269. ) {
  270. const { job_id: jobId }: any = await updateAnnotationStatus(appId, AnnotationEnableStatus.enable, embeddingModel, score)
  271. await ensureJobCompleted(jobId, AnnotationEnableStatus.enable)
  272. }
  273. if (score !== annotationConfig?.score_threshold)
  274. await updateAnnotationScore(appId, annotationConfig?.id || '', score)
  275. await fetchAnnotationConfig()
  276. Toast.notify({
  277. message: t('common.api.actionSuccess'),
  278. type: 'success',
  279. })
  280. setIsShowEdit(false)
  281. }}
  282. annotationConfig={annotationConfig!}
  283. />
  284. )}
  285. {
  286. isShowAnnotationFullModal && (
  287. <AnnotationFullModal
  288. show={isShowAnnotationFullModal}
  289. onHide={() => setIsShowAnnotationFullModal(false)}
  290. />
  291. )
  292. }
  293. </div>
  294. </div>
  295. )
  296. }
  297. export default React.memo(Annotation)