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