index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import useSWR from 'swr'
  6. import { omit } from 'lodash-es'
  7. import { useBoolean } from 'ahooks'
  8. import { useContext } from 'use-context-selector'
  9. import SegmentCard from '../documents/detail/completed/SegmentCard'
  10. import docStyle from '../documents/detail/completed/style.module.css'
  11. import Textarea from './textarea'
  12. import s from './style.module.css'
  13. import HitDetail from './hit-detail'
  14. import ModifyRetrievalModal from './modify-retrieval-modal'
  15. import cn from '@/utils/classnames'
  16. import type { ExternalKnowledgeBaseHitTestingResponse, ExternalKnowledgeBaseHitTesting as ExternalKnowledgeBaseHitTestingType, HitTestingResponse, HitTesting as HitTestingType } from '@/models/datasets'
  17. import Loading from '@/app/components/base/loading'
  18. import Modal from '@/app/components/base/modal'
  19. import Drawer from '@/app/components/base/drawer'
  20. import Pagination from '@/app/components/base/pagination'
  21. import FloatRightContainer from '@/app/components/base/float-right-container'
  22. import { fetchTestingRecords } from '@/service/datasets'
  23. import DatasetDetailContext from '@/context/dataset-detail'
  24. import type { RetrievalConfig } from '@/types/app'
  25. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  26. import useTimestamp from '@/hooks/use-timestamp'
  27. const limit = 10
  28. type Props = {
  29. datasetId: string
  30. }
  31. const RecordsEmpty: FC = () => {
  32. const { t } = useTranslation()
  33. return <div className='bg-gray-50 rounded-2xl p-5'>
  34. <div className={s.clockWrapper}>
  35. <div className={cn(s.clockIcon, 'w-5 h-5')}></div>
  36. </div>
  37. <div className='my-2 text-gray-500 text-sm'>{t('datasetHitTesting.noRecentTip')}</div>
  38. </div>
  39. }
  40. const HitTesting: FC<Props> = ({ datasetId }: Props) => {
  41. const { t } = useTranslation()
  42. const { formatTime } = useTimestamp()
  43. const media = useBreakpoints()
  44. const isMobile = media === MediaType.mobile
  45. const [hitResult, setHitResult] = useState<HitTestingResponse | undefined>() // 初始化记录为空数组
  46. const [externalHitResult, setExternalHitResult] = useState<ExternalKnowledgeBaseHitTestingResponse | undefined>()
  47. const [submitLoading, setSubmitLoading] = useState(false)
  48. const [currParagraph, setCurrParagraph] = useState<{ paraInfo?: HitTestingType; showModal: boolean }>({ showModal: false })
  49. const [externalCurrParagraph, setExternalCurrParagraph] = useState<{ paraInfo?: ExternalKnowledgeBaseHitTestingType; showModal: boolean }>({ showModal: false })
  50. const [text, setText] = useState('')
  51. const [currPage, setCurrPage] = React.useState<number>(0)
  52. const { data: recordsRes, error, mutate: recordsMutate } = useSWR({
  53. action: 'fetchTestingRecords',
  54. datasetId,
  55. params: { limit, page: currPage + 1 },
  56. }, apiParams => fetchTestingRecords(omit(apiParams, 'action')))
  57. const total = recordsRes?.total || 0
  58. const onClickCard = (detail: HitTestingType) => {
  59. setCurrParagraph({ paraInfo: detail, showModal: true })
  60. }
  61. const onClickExternalCard = (detail: ExternalKnowledgeBaseHitTestingType) => {
  62. setExternalCurrParagraph({ paraInfo: detail, showModal: true })
  63. }
  64. const { dataset: currentDataset } = useContext(DatasetDetailContext)
  65. const isExternal = currentDataset?.provider === 'external'
  66. const [retrievalConfig, setRetrievalConfig] = useState(currentDataset?.retrieval_model_dict as RetrievalConfig)
  67. const [isShowModifyRetrievalModal, setIsShowModifyRetrievalModal] = useState(false)
  68. const [isShowRightPanel, { setTrue: showRightPanel, setFalse: hideRightPanel, set: setShowRightPanel }] = useBoolean(!isMobile)
  69. const renderHitResults = (results: any[], onClickCard: (record: any) => void) => (
  70. <>
  71. <div className='text-gray-600 font-semibold mb-4'>{t('datasetHitTesting.hit.title')}</div>
  72. <div className='overflow-auto flex-1'>
  73. <div className={s.cardWrapper}>
  74. {results.map((record, idx) => (
  75. <SegmentCard
  76. key={idx}
  77. loading={false}
  78. refSource= {{
  79. title: record.title,
  80. uri: record.metadata ? record.metadata['x-amz-bedrock-kb-source-uri'] : '',
  81. }}
  82. isExternal={isExternal}
  83. detail={record.segment}
  84. contentExternal={record.content}
  85. score={record.score}
  86. scene='hitTesting'
  87. className='h-[216px] mb-4'
  88. onClick={() => onClickCard(record)}
  89. />
  90. ))}
  91. </div>
  92. </div>
  93. </>
  94. )
  95. const renderEmptyState = () => (
  96. <div className='h-full flex flex-col justify-center items-center'>
  97. <div className={cn(docStyle.commonIcon, docStyle.targetIcon, '!bg-gray-200 !h-14 !w-14')} />
  98. <div className='text-gray-300 text-[13px] mt-3'>
  99. {t('datasetHitTesting.hit.emptyTip')}
  100. </div>
  101. </div>
  102. )
  103. useEffect(() => {
  104. setShowRightPanel(!isMobile)
  105. }, [isMobile, setShowRightPanel])
  106. return (
  107. <div className={s.container}>
  108. <div className={s.leftDiv}>
  109. <div className={s.titleWrapper}>
  110. <h1 className={s.title}>{t('datasetHitTesting.title')}</h1>
  111. <p className={s.desc}>{t('datasetHitTesting.desc')}</p>
  112. </div>
  113. <Textarea
  114. datasetId={datasetId}
  115. setHitResult={setHitResult}
  116. setExternalHitResult={setExternalHitResult}
  117. onSubmit={showRightPanel}
  118. onUpdateList={recordsMutate}
  119. loading={submitLoading}
  120. setLoading={setSubmitLoading}
  121. setText={setText}
  122. text={text}
  123. isExternal={isExternal}
  124. onClickRetrievalMethod={() => setIsShowModifyRetrievalModal(true)}
  125. retrievalConfig={retrievalConfig}
  126. isEconomy={currentDataset?.indexing_technique === 'economy'}
  127. />
  128. <div className={cn(s.title, 'mt-8 mb-2')}>{t('datasetHitTesting.recents')}</div>
  129. {(!recordsRes && !error)
  130. ? (
  131. <div className='flex-1'><Loading type='app' /></div>
  132. )
  133. : recordsRes?.data?.length
  134. ? (
  135. <>
  136. <div className='grow overflow-y-auto'>
  137. <table className={`w-full border-collapse border-0 mt-3 ${s.table}`}>
  138. <thead className="sticky top-0 h-8 bg-white leading-8 border-b border-gray-200 text-gray-500 font-bold">
  139. <tr>
  140. <td className='w-28'>{t('datasetHitTesting.table.header.source')}</td>
  141. <td>{t('datasetHitTesting.table.header.text')}</td>
  142. <td className='w-48'>{t('datasetHitTesting.table.header.time')}</td>
  143. </tr>
  144. </thead>
  145. <tbody className="text-gray-500">
  146. {recordsRes?.data?.map((record) => {
  147. return <tr
  148. key={record.id}
  149. className='group border-b border-gray-200 h-8 hover:bg-gray-50 cursor-pointer'
  150. onClick={() => setText(record.content)}
  151. >
  152. <td className='w-24'>
  153. <div className='flex items-center'>
  154. <div className={cn(s[`${record.source}_icon`], s.commonIcon, 'mr-1')} />
  155. <span className='capitalize'>{record.source.replace('_', ' ')}</span>
  156. </div>
  157. </td>
  158. <td className='max-w-xs group-hover:text-primary-600'>{record.content}</td>
  159. <td className='w-36'>
  160. {formatTime(record.created_at, t('datasetHitTesting.dateTimeFormat') as string)}
  161. </td>
  162. </tr>
  163. })}
  164. </tbody>
  165. </table>
  166. </div>
  167. {(total && total > limit)
  168. ? <Pagination current={currPage} onChange={setCurrPage} total={total} limit={limit} />
  169. : null}
  170. </>
  171. )
  172. : (
  173. <RecordsEmpty />
  174. )}
  175. </div>
  176. <FloatRightContainer panelClassname='!justify-start !overflow-y-auto' showClose isMobile={isMobile} isOpen={isShowRightPanel} onClose={hideRightPanel} footer={null}>
  177. <div className={cn(s.rightDiv, 'p-0 sm:px-8 sm:pt-[42px] sm:pb-[26px]')}>
  178. {submitLoading
  179. ? <div className={s.cardWrapper}>
  180. <SegmentCard
  181. loading={true}
  182. scene='hitTesting'
  183. className='h-[216px]'
  184. />
  185. <SegmentCard
  186. loading={true}
  187. scene='hitTesting'
  188. className='h-[216px]'
  189. />
  190. </div>
  191. : (
  192. (() => {
  193. if (!hitResult?.records.length && !externalHitResult?.records.length)
  194. return renderEmptyState()
  195. if (hitResult?.records.length)
  196. return renderHitResults(hitResult.records, onClickCard)
  197. return renderHitResults(externalHitResult?.records || [], onClickExternalCard)
  198. })()
  199. )
  200. }
  201. </div>
  202. </FloatRightContainer>
  203. <Modal
  204. className={isExternal ? 'py-10 px-8' : 'w-full'}
  205. closable
  206. onClose={() => {
  207. setCurrParagraph({ showModal: false })
  208. setExternalCurrParagraph({ showModal: false })
  209. }}
  210. isShow={currParagraph.showModal || externalCurrParagraph.showModal}
  211. >
  212. {currParagraph.showModal && (
  213. <HitDetail
  214. segInfo={currParagraph.paraInfo?.segment}
  215. />
  216. )}
  217. {externalCurrParagraph.showModal && (
  218. <HitDetail
  219. segInfo={{
  220. id: 'external',
  221. content: externalCurrParagraph.paraInfo?.content,
  222. }}
  223. />
  224. )}
  225. </Modal>
  226. <Drawer isOpen={isShowModifyRetrievalModal} onClose={() => setIsShowModifyRetrievalModal(false)} footer={null} mask={isMobile} panelClassname='mt-16 mx-2 sm:mr-2 mb-3 !p-0 !max-w-[640px] rounded-xl'>
  227. <ModifyRetrievalModal
  228. indexMethod={currentDataset?.indexing_technique || ''}
  229. value={retrievalConfig}
  230. isShow={isShowModifyRetrievalModal}
  231. onHide={() => setIsShowModifyRetrievalModal(false)}
  232. onSave={(value) => {
  233. setRetrievalConfig(value)
  234. setIsShowModifyRetrievalModal(false)
  235. }}
  236. />
  237. </Drawer>
  238. </div>
  239. )
  240. }
  241. export default HitTesting