index.tsx 12 KB

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