index.tsx 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. 'use client'
  2. import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useContext } from 'use-context-selector'
  5. import { useBoolean } from 'ahooks'
  6. import { XMarkIcon } from '@heroicons/react/20/solid'
  7. import { RocketLaunchIcon } from '@heroicons/react/24/outline'
  8. import cn from 'classnames'
  9. import Link from 'next/link'
  10. import { groupBy } from 'lodash-es'
  11. import RetrievalMethodInfo from '../../common/retrieval-method-info'
  12. import PreviewItem, { PreviewType } from './preview-item'
  13. import LanguageSelect from './language-select'
  14. import s from './index.module.css'
  15. import type { CreateDocumentReq, CustomFile, FileIndexingEstimateResponse, FullDocumentDetail, IndexingEstimateParams, IndexingEstimateResponse, NotionInfo, PreProcessingRule, ProcessRule, Rules, createDocumentResponse } from '@/models/datasets'
  16. import {
  17. createDocument,
  18. createFirstDocument,
  19. fetchFileIndexingEstimate as didFetchFileIndexingEstimate,
  20. fetchDefaultProcessRule,
  21. } from '@/service/datasets'
  22. import Button from '@/app/components/base/button'
  23. import Loading from '@/app/components/base/loading'
  24. import FloatRightContainer from '@/app/components/base/float-right-container'
  25. import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'
  26. import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/economical-retrieval-method-config'
  27. import { type RetrievalConfig } from '@/types/app'
  28. import { ensureRerankModelSelected, isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model'
  29. import Toast from '@/app/components/base/toast'
  30. import { formatNumber } from '@/utils/format'
  31. import type { NotionPage } from '@/models/common'
  32. import { DataSourceType, DocForm } from '@/models/datasets'
  33. import NotionIcon from '@/app/components/base/notion-icon'
  34. import Switch from '@/app/components/base/switch'
  35. import { MessageChatSquare } from '@/app/components/base/icons/src/public/common'
  36. import { XClose } from '@/app/components/base/icons/src/vender/line/general'
  37. import { useDatasetDetailContext } from '@/context/dataset-detail'
  38. import I18n from '@/context/i18n'
  39. import { IS_CE_EDITION } from '@/config'
  40. import { RETRIEVE_METHOD } from '@/types/app'
  41. import { useProviderContext } from '@/context/provider-context'
  42. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  43. import Tooltip from '@/app/components/base/tooltip'
  44. type ValueOf<T> = T[keyof T]
  45. type StepTwoProps = {
  46. isSetting?: boolean
  47. documentDetail?: FullDocumentDetail
  48. hasSetAPIKEY: boolean
  49. onSetting: () => void
  50. datasetId?: string
  51. indexingType?: ValueOf<IndexingType>
  52. dataSourceType: DataSourceType
  53. files: CustomFile[]
  54. notionPages?: NotionPage[]
  55. onStepChange?: (delta: number) => void
  56. updateIndexingTypeCache?: (type: string) => void
  57. updateResultCache?: (res: createDocumentResponse) => void
  58. onSave?: () => void
  59. onCancel?: () => void
  60. }
  61. enum SegmentType {
  62. AUTO = 'automatic',
  63. CUSTOM = 'custom',
  64. }
  65. enum IndexingType {
  66. QUALIFIED = 'high_quality',
  67. ECONOMICAL = 'economy',
  68. }
  69. const StepTwo = ({
  70. isSetting,
  71. documentDetail,
  72. hasSetAPIKEY,
  73. onSetting,
  74. datasetId,
  75. indexingType,
  76. dataSourceType,
  77. files,
  78. notionPages = [],
  79. onStepChange,
  80. updateIndexingTypeCache,
  81. updateResultCache,
  82. onSave,
  83. onCancel,
  84. }: StepTwoProps) => {
  85. const { t } = useTranslation()
  86. const { locale } = useContext(I18n)
  87. const media = useBreakpoints()
  88. const isMobile = media === MediaType.mobile
  89. const { dataset: currentDataset, mutateDatasetRes } = useDatasetDetailContext()
  90. const scrollRef = useRef<HTMLDivElement>(null)
  91. const [scrolled, setScrolled] = useState(false)
  92. const previewScrollRef = useRef<HTMLDivElement>(null)
  93. const [previewScrolled, setPreviewScrolled] = useState(false)
  94. const [segmentationType, setSegmentationType] = useState<SegmentType>(SegmentType.AUTO)
  95. const [segmentIdentifier, setSegmentIdentifier] = useState('\\n')
  96. const [max, setMax] = useState(1000)
  97. const [rules, setRules] = useState<PreProcessingRule[]>([])
  98. const [defaultConfig, setDefaultConfig] = useState<Rules>()
  99. const hasSetIndexType = !!indexingType
  100. const [indexType, setIndexType] = useState<ValueOf<IndexingType>>(
  101. (indexingType
  102. || hasSetAPIKEY)
  103. ? IndexingType.QUALIFIED
  104. : IndexingType.ECONOMICAL,
  105. )
  106. const [docForm, setDocForm] = useState<DocForm | string>(
  107. (datasetId && documentDetail) ? documentDetail.doc_form : DocForm.TEXT,
  108. )
  109. const [docLanguage, setDocLanguage] = useState<string>(locale === 'en' ? 'English' : 'Chinese')
  110. const [QATipHide, setQATipHide] = useState(false)
  111. const [previewSwitched, setPreviewSwitched] = useState(false)
  112. const [showPreview, { setTrue: setShowPreview, setFalse: hidePreview }] = useBoolean()
  113. const [customFileIndexingEstimate, setCustomFileIndexingEstimate] = useState<FileIndexingEstimateResponse | null>(null)
  114. const [automaticFileIndexingEstimate, setAutomaticFileIndexingEstimate] = useState<FileIndexingEstimateResponse | null>(null)
  115. const [estimateTokes, setEstimateTokes] = useState<Pick<IndexingEstimateResponse, 'tokens' | 'total_price'> | null>(null)
  116. const fileIndexingEstimate = (() => {
  117. return segmentationType === SegmentType.AUTO ? automaticFileIndexingEstimate : customFileIndexingEstimate
  118. })()
  119. const [isCreating, setIsCreating] = useState(false)
  120. const scrollHandle = (e: Event) => {
  121. if ((e.target as HTMLDivElement).scrollTop > 0)
  122. setScrolled(true)
  123. else
  124. setScrolled(false)
  125. }
  126. const previewScrollHandle = (e: Event) => {
  127. if ((e.target as HTMLDivElement).scrollTop > 0)
  128. setPreviewScrolled(true)
  129. else
  130. setPreviewScrolled(false)
  131. }
  132. const getFileName = (name: string) => {
  133. const arr = name.split('.')
  134. return arr.slice(0, -1).join('.')
  135. }
  136. const getRuleName = (key: string) => {
  137. if (key === 'remove_extra_spaces')
  138. return t('datasetCreation.stepTwo.removeExtraSpaces')
  139. if (key === 'remove_urls_emails')
  140. return t('datasetCreation.stepTwo.removeUrlEmails')
  141. if (key === 'remove_stopwords')
  142. return t('datasetCreation.stepTwo.removeStopwords')
  143. }
  144. const ruleChangeHandle = (id: string) => {
  145. const newRules = rules.map((rule) => {
  146. if (rule.id === id) {
  147. return {
  148. id: rule.id,
  149. enabled: !rule.enabled,
  150. }
  151. }
  152. return rule
  153. })
  154. setRules(newRules)
  155. }
  156. const resetRules = () => {
  157. if (defaultConfig) {
  158. setSegmentIdentifier((defaultConfig.segmentation.separator === '\n' ? '\\n' : defaultConfig.segmentation.separator) || '\\n')
  159. setMax(defaultConfig.segmentation.max_tokens)
  160. setRules(defaultConfig.pre_processing_rules)
  161. }
  162. }
  163. const fetchFileIndexingEstimate = async (docForm = DocForm.TEXT) => {
  164. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  165. const res = await didFetchFileIndexingEstimate(getFileIndexingEstimateParams(docForm)!)
  166. if (segmentationType === SegmentType.CUSTOM) {
  167. setCustomFileIndexingEstimate(res)
  168. }
  169. else {
  170. setAutomaticFileIndexingEstimate(res)
  171. indexType === IndexingType.QUALIFIED && setEstimateTokes({ tokens: res.tokens, total_price: res.total_price })
  172. }
  173. }
  174. const confirmChangeCustomConfig = () => {
  175. setCustomFileIndexingEstimate(null)
  176. setShowPreview()
  177. fetchFileIndexingEstimate()
  178. setPreviewSwitched(false)
  179. }
  180. const getIndexing_technique = () => indexingType || indexType
  181. const getProcessRule = () => {
  182. const processRule: ProcessRule = {
  183. rules: {} as any, // api will check this. It will be removed after api refactored.
  184. mode: segmentationType,
  185. }
  186. if (segmentationType === SegmentType.CUSTOM) {
  187. const ruleObj = {
  188. pre_processing_rules: rules,
  189. segmentation: {
  190. separator: segmentIdentifier === '\\n' ? '\n' : segmentIdentifier,
  191. max_tokens: max,
  192. },
  193. }
  194. processRule.rules = ruleObj
  195. }
  196. return processRule
  197. }
  198. const getNotionInfo = () => {
  199. const workspacesMap = groupBy(notionPages, 'workspace_id')
  200. const workspaces = Object.keys(workspacesMap).map((workspaceId) => {
  201. return {
  202. workspaceId,
  203. pages: workspacesMap[workspaceId],
  204. }
  205. })
  206. return workspaces.map((workspace) => {
  207. return {
  208. workspace_id: workspace.workspaceId,
  209. pages: workspace.pages.map((page) => {
  210. const { page_id, page_name, page_icon, type } = page
  211. return {
  212. page_id,
  213. page_name,
  214. page_icon,
  215. type,
  216. }
  217. }),
  218. }
  219. }) as NotionInfo[]
  220. }
  221. const getFileIndexingEstimateParams = (docForm: DocForm): IndexingEstimateParams | undefined => {
  222. if (dataSourceType === DataSourceType.FILE) {
  223. return {
  224. info_list: {
  225. data_source_type: dataSourceType,
  226. file_info_list: {
  227. file_ids: files.map(file => file.id) as string[],
  228. },
  229. },
  230. indexing_technique: getIndexing_technique() as string,
  231. process_rule: getProcessRule(),
  232. doc_form: docForm,
  233. doc_language: docLanguage,
  234. dataset_id: datasetId as string,
  235. }
  236. }
  237. if (dataSourceType === DataSourceType.NOTION) {
  238. return {
  239. info_list: {
  240. data_source_type: dataSourceType,
  241. notion_info_list: getNotionInfo(),
  242. },
  243. indexing_technique: getIndexing_technique() as string,
  244. process_rule: getProcessRule(),
  245. doc_form: docForm,
  246. doc_language: docLanguage,
  247. dataset_id: datasetId as string,
  248. }
  249. }
  250. }
  251. const {
  252. rerankDefaultModel,
  253. isRerankDefaultModelVaild,
  254. rerankModelList,
  255. } = useProviderContext()
  256. const getCreationParams = () => {
  257. let params
  258. if (isSetting) {
  259. params = {
  260. original_document_id: documentDetail?.id,
  261. doc_form: docForm,
  262. doc_language: docLanguage,
  263. process_rule: getProcessRule(),
  264. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  265. retrieval_model: retrievalConfig, // Readonly. If want to changed, just go to settings page.
  266. } as CreateDocumentReq
  267. }
  268. else { // create
  269. const indexMethod = getIndexing_technique()
  270. if (
  271. !isReRankModelSelected({
  272. rerankDefaultModel,
  273. isRerankDefaultModelVaild,
  274. rerankModelList,
  275. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  276. retrievalConfig,
  277. indexMethod: indexMethod as string,
  278. })
  279. ) {
  280. Toast.notify({ type: 'error', message: t('appDebug.datasetConfig.rerankModelRequired') })
  281. return
  282. }
  283. const postRetrievalConfig = ensureRerankModelSelected({
  284. rerankDefaultModel: rerankDefaultModel!,
  285. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  286. retrievalConfig,
  287. indexMethod: indexMethod as string,
  288. })
  289. params = {
  290. data_source: {
  291. type: dataSourceType,
  292. info_list: {
  293. data_source_type: dataSourceType,
  294. },
  295. },
  296. indexing_technique: getIndexing_technique(),
  297. process_rule: getProcessRule(),
  298. doc_form: docForm,
  299. doc_language: docLanguage,
  300. retrieval_model: postRetrievalConfig,
  301. } as CreateDocumentReq
  302. if (dataSourceType === DataSourceType.FILE) {
  303. params.data_source.info_list.file_info_list = {
  304. file_ids: files.map(file => file.id || '').filter(Boolean),
  305. }
  306. }
  307. if (dataSourceType === DataSourceType.NOTION)
  308. params.data_source.info_list.notion_info_list = getNotionInfo()
  309. }
  310. return params
  311. }
  312. const getRules = async () => {
  313. try {
  314. const res = await fetchDefaultProcessRule({ url: '/datasets/process-rule' })
  315. const separator = res.rules.segmentation.separator
  316. setSegmentIdentifier((separator === '\n' ? '\\n' : separator) || '\\n')
  317. setMax(res.rules.segmentation.max_tokens)
  318. setRules(res.rules.pre_processing_rules)
  319. setDefaultConfig(res.rules)
  320. }
  321. catch (err) {
  322. console.log(err)
  323. }
  324. }
  325. const getRulesFromDetail = () => {
  326. if (documentDetail) {
  327. const rules = documentDetail.dataset_process_rule.rules
  328. const separator = rules.segmentation.separator
  329. const max = rules.segmentation.max_tokens
  330. setSegmentIdentifier((separator === '\n' ? '\\n' : separator) || '\\n')
  331. setMax(max)
  332. setRules(rules.pre_processing_rules)
  333. setDefaultConfig(rules)
  334. }
  335. }
  336. const getDefaultMode = () => {
  337. if (documentDetail)
  338. setSegmentationType(documentDetail.dataset_process_rule.mode)
  339. }
  340. const createHandle = async () => {
  341. if (isCreating)
  342. return
  343. setIsCreating(true)
  344. try {
  345. let res
  346. const params = getCreationParams()
  347. if (!params)
  348. return false
  349. setIsCreating(true)
  350. if (!datasetId) {
  351. res = await createFirstDocument({
  352. body: params as CreateDocumentReq,
  353. })
  354. updateIndexingTypeCache && updateIndexingTypeCache(indexType as string)
  355. updateResultCache && updateResultCache(res)
  356. }
  357. else {
  358. res = await createDocument({
  359. datasetId,
  360. body: params as CreateDocumentReq,
  361. })
  362. updateIndexingTypeCache && updateIndexingTypeCache(indexType as string)
  363. updateResultCache && updateResultCache(res)
  364. }
  365. if (mutateDatasetRes)
  366. mutateDatasetRes()
  367. onStepChange && onStepChange(+1)
  368. isSetting && onSave && onSave()
  369. }
  370. catch (err) {
  371. Toast.notify({
  372. type: 'error',
  373. message: `${err}`,
  374. })
  375. }
  376. finally {
  377. setIsCreating(false)
  378. }
  379. }
  380. const handleSwitch = (state: boolean) => {
  381. if (state)
  382. setDocForm(DocForm.QA)
  383. else
  384. setDocForm(DocForm.TEXT)
  385. }
  386. const handleSelect = (language: string) => {
  387. setDocLanguage(language)
  388. }
  389. const changeToEconomicalType = () => {
  390. if (!hasSetIndexType) {
  391. setIndexType(IndexingType.ECONOMICAL)
  392. setDocForm(DocForm.TEXT)
  393. }
  394. }
  395. const previewSwitch = async () => {
  396. setPreviewSwitched(true)
  397. if (segmentationType === SegmentType.AUTO)
  398. setAutomaticFileIndexingEstimate(null)
  399. else
  400. setCustomFileIndexingEstimate(null)
  401. await fetchFileIndexingEstimate(DocForm.QA)
  402. }
  403. useEffect(() => {
  404. // fetch rules
  405. if (!isSetting) {
  406. getRules()
  407. }
  408. else {
  409. getRulesFromDetail()
  410. getDefaultMode()
  411. }
  412. }, [])
  413. useEffect(() => {
  414. scrollRef.current?.addEventListener('scroll', scrollHandle)
  415. return () => {
  416. scrollRef.current?.removeEventListener('scroll', scrollHandle)
  417. }
  418. }, [])
  419. useLayoutEffect(() => {
  420. if (showPreview) {
  421. previewScrollRef.current?.addEventListener('scroll', previewScrollHandle)
  422. return () => {
  423. previewScrollRef.current?.removeEventListener('scroll', previewScrollHandle)
  424. }
  425. }
  426. }, [showPreview])
  427. useEffect(() => {
  428. if (indexingType === IndexingType.ECONOMICAL && docForm === DocForm.QA)
  429. setDocForm(DocForm.TEXT)
  430. }, [indexingType, docForm])
  431. useEffect(() => {
  432. // get indexing type by props
  433. if (indexingType)
  434. setIndexType(indexingType as IndexingType)
  435. else
  436. setIndexType(hasSetAPIKEY ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
  437. }, [hasSetAPIKEY, indexingType, datasetId])
  438. useEffect(() => {
  439. if (segmentationType === SegmentType.AUTO) {
  440. setAutomaticFileIndexingEstimate(null)
  441. !isMobile && setShowPreview()
  442. fetchFileIndexingEstimate()
  443. setPreviewSwitched(false)
  444. }
  445. else {
  446. hidePreview()
  447. setCustomFileIndexingEstimate(null)
  448. setPreviewSwitched(false)
  449. }
  450. }, [segmentationType, indexType])
  451. const [retrievalConfig, setRetrievalConfig] = useState(currentDataset?.retrieval_model_dict || {
  452. search_method: RETRIEVE_METHOD.semantic,
  453. reranking_enable: false,
  454. reranking_model: {
  455. reranking_provider_name: rerankDefaultModel?.model_provider.provider_name,
  456. reranking_model_name: rerankDefaultModel?.model_name,
  457. },
  458. top_k: 3,
  459. score_threshold_enabled: false,
  460. score_threshold: 0.5,
  461. } as RetrievalConfig)
  462. return (
  463. <div className='flex w-full h-full'>
  464. <div ref={scrollRef} className='relative h-full w-full overflow-y-scroll'>
  465. <div className={cn(s.pageHeader, scrolled && s.fixed, isMobile && '!px-6')}>
  466. <span>{t('datasetCreation.steps.two')}</span>
  467. {isMobile && (
  468. <Button
  469. className='border-[0.5px] !h-8 hover:outline hover:outline-[0.5px] hover:outline-gray-300 text-gray-700 font-medium bg-white shadow-[0px_1px_2px_0px_rgba(16,24,40,0.05)]'
  470. onClick={setShowPreview}
  471. >
  472. <Tooltip selector='data-preview-toggle'>
  473. <div className="flex flex-row items-center">
  474. <RocketLaunchIcon className="h-4 w-4 mr-1.5 stroke-[1.8px]" />
  475. <span className="text-[13px]">{t('datasetCreation.stepTwo.previewTitleButton')}</span>
  476. </div>
  477. </Tooltip>
  478. </Button>
  479. )}
  480. </div>
  481. <div className={cn(s.form, isMobile && '!px-4')}>
  482. <div className={s.label}>{t('datasetCreation.stepTwo.segmentation')}</div>
  483. <div className='max-w-[640px]'>
  484. <div
  485. className={cn(
  486. s.radioItem,
  487. s.segmentationItem,
  488. segmentationType === SegmentType.AUTO && s.active,
  489. )}
  490. onClick={() => setSegmentationType(SegmentType.AUTO)}
  491. >
  492. <span className={cn(s.typeIcon, s.auto)} />
  493. <span className={cn(s.radio)} />
  494. <div className={s.typeHeader}>
  495. <div className={s.title}>{t('datasetCreation.stepTwo.auto')}</div>
  496. <div className={s.tip}>{t('datasetCreation.stepTwo.autoDescription')}</div>
  497. </div>
  498. </div>
  499. <div
  500. className={cn(
  501. s.radioItem,
  502. s.segmentationItem,
  503. segmentationType === SegmentType.CUSTOM && s.active,
  504. segmentationType === SegmentType.CUSTOM && s.custom,
  505. )}
  506. onClick={() => setSegmentationType(SegmentType.CUSTOM)}
  507. >
  508. <span className={cn(s.typeIcon, s.customize)} />
  509. <span className={cn(s.radio)} />
  510. <div className={s.typeHeader}>
  511. <div className={s.title}>{t('datasetCreation.stepTwo.custom')}</div>
  512. <div className={s.tip}>{t('datasetCreation.stepTwo.customDescription')}</div>
  513. </div>
  514. {segmentationType === SegmentType.CUSTOM && (
  515. <div className={s.typeFormBody}>
  516. <div className={s.formRow}>
  517. <div className='w-full'>
  518. <div className={s.label}>{t('datasetCreation.stepTwo.separator')}</div>
  519. <input
  520. type="text"
  521. className={s.input}
  522. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={segmentIdentifier}
  523. onChange={e => setSegmentIdentifier(e.target.value)}
  524. />
  525. </div>
  526. </div>
  527. <div className={s.formRow}>
  528. <div className='w-full'>
  529. <div className={s.label}>{t('datasetCreation.stepTwo.maxLength')}</div>
  530. <input
  531. type="number"
  532. className={s.input}
  533. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''}
  534. value={max}
  535. min={1}
  536. onChange={e => setMax(parseInt(e.target.value.replace(/^0+/, ''), 10))}
  537. />
  538. </div>
  539. </div>
  540. <div className={s.formRow}>
  541. <div className='w-full flex flex-col gap-1'>
  542. <div className={s.label}>{t('datasetCreation.stepTwo.rules')}</div>
  543. {rules.map(rule => (
  544. <div key={rule.id} className={s.ruleItem}>
  545. <input id={rule.id} type="checkbox" checked={rule.enabled} onChange={() => ruleChangeHandle(rule.id)} className="w-4 h-4 rounded border-gray-300 text-blue-700 focus:ring-blue-700" />
  546. <label htmlFor={rule.id} className="ml-2 text-sm font-normal cursor-pointer text-gray-800">{getRuleName(rule.id)}</label>
  547. </div>
  548. ))}
  549. </div>
  550. </div>
  551. <div className={s.formFooter}>
  552. <Button type="primary" className={cn(s.button, '!h-8 text-primary-600')} onClick={confirmChangeCustomConfig}>{t('datasetCreation.stepTwo.preview')}</Button>
  553. <Button className={cn(s.button, 'ml-2 !h-8')} onClick={resetRules}>{t('datasetCreation.stepTwo.reset')}</Button>
  554. </div>
  555. </div>
  556. )}
  557. </div>
  558. </div>
  559. <div className={s.label}>{t('datasetCreation.stepTwo.indexMode')}</div>
  560. <div className='max-w-[640px]'>
  561. <div className='flex items-center gap-3 flex-wrap sm:flex-nowrap'>
  562. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.QUALIFIED)) && (
  563. <div
  564. className={cn(
  565. s.radioItem,
  566. s.indexItem,
  567. !hasSetAPIKEY && s.disabled,
  568. !hasSetIndexType && indexType === IndexingType.QUALIFIED && s.active,
  569. hasSetIndexType && s.disabled,
  570. hasSetIndexType && '!w-full',
  571. )}
  572. onClick={() => {
  573. if (hasSetAPIKEY)
  574. setIndexType(IndexingType.QUALIFIED)
  575. }}
  576. >
  577. <span className={cn(s.typeIcon, s.qualified)} />
  578. {!hasSetIndexType && <span className={cn(s.radio)} />}
  579. <div className={s.typeHeader}>
  580. <div className={s.title}>
  581. {t('datasetCreation.stepTwo.qualified')}
  582. {!hasSetIndexType && <span className={s.recommendTag}>{t('datasetCreation.stepTwo.recommend')}</span>}
  583. </div>
  584. <div className={s.tip}>{t('datasetCreation.stepTwo.qualifiedTip')}</div>
  585. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  586. {
  587. estimateTokes
  588. ? (
  589. <div className='text-xs font-medium text-gray-800'>{formatNumber(estimateTokes.tokens)} tokens(<span className='text-yellow-500'>${formatNumber(estimateTokes.total_price)}</span>)</div>
  590. )
  591. : (
  592. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  593. )
  594. }
  595. </div>
  596. {!hasSetAPIKEY && (
  597. <div className={s.warningTip}>
  598. <span>{t('datasetCreation.stepTwo.warning')}&nbsp;</span>
  599. <span className={s.click} onClick={onSetting}>{t('datasetCreation.stepTwo.click')}</span>
  600. </div>
  601. )}
  602. </div>
  603. )}
  604. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.ECONOMICAL)) && (
  605. <div
  606. className={cn(
  607. s.radioItem,
  608. s.indexItem,
  609. !hasSetIndexType && indexType === IndexingType.ECONOMICAL && s.active,
  610. hasSetIndexType && s.disabled,
  611. hasSetIndexType && '!w-full',
  612. )}
  613. onClick={changeToEconomicalType}
  614. >
  615. <span className={cn(s.typeIcon, s.economical)} />
  616. {!hasSetIndexType && <span className={cn(s.radio)} />}
  617. <div className={s.typeHeader}>
  618. <div className={s.title}>{t('datasetCreation.stepTwo.economical')}</div>
  619. <div className={s.tip}>{t('datasetCreation.stepTwo.economicalTip')}</div>
  620. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  621. <div className='text-xs font-medium text-gray-800'>0 tokens</div>
  622. </div>
  623. </div>
  624. )}
  625. </div>
  626. {hasSetIndexType && (
  627. <div className='mt-2 text-xs text-gray-500 font-medium'>
  628. {t('datasetCreation.stepTwo.indexSettedTip')}
  629. <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
  630. </div>
  631. )}
  632. {IS_CE_EDITION && indexType === IndexingType.QUALIFIED && (
  633. <div className='mt-3 rounded-xl bg-gray-50 border border-gray-100'>
  634. <div className='flex justify-between items-center px-5 py-4'>
  635. <div className='flex justify-center items-center w-8 h-8 rounded-lg bg-indigo-50'>
  636. <MessageChatSquare className='w-4 h-4' />
  637. </div>
  638. <div className='grow mx-3'>
  639. <div className='mb-[2px] text-md font-medium text-gray-900'>{t('datasetCreation.stepTwo.QATitle')}</div>
  640. <div className='inline-flex items-center text-[13px] leading-[18px] text-gray-500'>
  641. <span className='pr-1'>{t('datasetCreation.stepTwo.QALanguage')}</span>
  642. <LanguageSelect currentLanguage={docLanguage} onSelect={handleSelect} />
  643. </div>
  644. </div>
  645. <div className='shrink-0'>
  646. <Switch
  647. defaultValue={docForm === DocForm.QA}
  648. onChange={handleSwitch}
  649. size='md'
  650. />
  651. </div>
  652. </div>
  653. {docForm === DocForm.QA && !QATipHide && (
  654. <div className='flex justify-between items-center px-5 py-2 bg-orange-50 border-t border-amber-100 rounded-b-xl text-[13px] leading-[18px] text-medium text-amber-500'>
  655. {t('datasetCreation.stepTwo.QATip')}
  656. <XClose className='w-4 h-4 text-gray-500 cursor-pointer' onClick={() => setQATipHide(true)} />
  657. </div>
  658. )}
  659. </div>
  660. )}
  661. {/* Retrieval Method Config */}
  662. <div>
  663. {!datasetId
  664. ? (
  665. <div className={s.label}>
  666. {t('datasetSettings.form.retrievalSetting.title')}
  667. <div className='leading-[18px] text-xs font-normal text-gray-500'>
  668. <a target='_blank' href='https://docs.dify.ai/advanced/retrieval-augment' className='text-[#155eef]'>{t('datasetSettings.form.retrievalSetting.learnMore')}</a>
  669. {t('datasetSettings.form.retrievalSetting.longDescription')}
  670. </div>
  671. </div>
  672. )
  673. : (
  674. <div className={cn(s.label, 'flex justify-between items-center')}>
  675. <div>{t('datasetSettings.form.retrievalSetting.title')}</div>
  676. </div>
  677. )}
  678. <div className='max-w-[640px]'>
  679. {!datasetId
  680. ? (<>
  681. {getIndexing_technique() === IndexingType.QUALIFIED
  682. ? (
  683. <RetrievalMethodConfig
  684. value={retrievalConfig}
  685. onChange={setRetrievalConfig}
  686. />
  687. )
  688. : (
  689. <EconomicalRetrievalMethodConfig
  690. value={retrievalConfig}
  691. onChange={setRetrievalConfig}
  692. />
  693. )}
  694. </>)
  695. : (
  696. <div>
  697. <RetrievalMethodInfo
  698. value={retrievalConfig}
  699. />
  700. <div className='mt-2 text-xs text-gray-500 font-medium'>
  701. {t('datasetCreation.stepTwo.retrivalSettedTip')}
  702. <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
  703. </div>
  704. </div>
  705. )}
  706. </div>
  707. </div>
  708. <div className={s.source}>
  709. <div className={s.sourceContent}>
  710. {dataSourceType === DataSourceType.FILE && (
  711. <>
  712. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.fileSource')}</div>
  713. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  714. <span className={cn(s.fileIcon, files.length && s[files[0].extension || ''])} />
  715. {getFileName(files[0].name || '')}
  716. {files.length > 1 && (
  717. <span className={s.sourceCount}>
  718. <span>{t('datasetCreation.stepTwo.other')}</span>
  719. <span>{files.length - 1}</span>
  720. <span>{t('datasetCreation.stepTwo.fileUnit')}</span>
  721. </span>
  722. )}
  723. </div>
  724. </>
  725. )}
  726. {dataSourceType === DataSourceType.NOTION && (
  727. <>
  728. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.notionSource')}</div>
  729. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  730. <NotionIcon
  731. className='shrink-0 mr-1'
  732. type='page'
  733. src={notionPages[0]?.page_icon}
  734. />
  735. {notionPages[0]?.page_name}
  736. {notionPages.length > 1 && (
  737. <span className={s.sourceCount}>
  738. <span>{t('datasetCreation.stepTwo.other')}</span>
  739. <span>{notionPages.length - 1}</span>
  740. <span>{t('datasetCreation.stepTwo.notionUnit')}</span>
  741. </span>
  742. )}
  743. </div>
  744. </>
  745. )}
  746. </div>
  747. <div className={s.divider} />
  748. <div className={s.segmentCount}>
  749. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateSegment')}</div>
  750. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  751. {
  752. fileIndexingEstimate
  753. ? (
  754. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.total_segments)} </div>
  755. )
  756. : (
  757. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  758. )
  759. }
  760. </div>
  761. </div>
  762. </div>
  763. {!isSetting
  764. ? (
  765. <div className='flex items-center mt-8 py-2'>
  766. <Button onClick={() => onStepChange && onStepChange(-1)}>{t('datasetCreation.stepTwo.lastStep')}</Button>
  767. <div className={s.divider} />
  768. <Button loading={isCreating} type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.nextStep')}</Button>
  769. </div>
  770. )
  771. : (
  772. <div className='flex items-center mt-8 py-2'>
  773. <Button loading={isCreating} type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.save')}</Button>
  774. <Button className='ml-2' onClick={onCancel}>{t('datasetCreation.stepTwo.cancel')}</Button>
  775. </div>
  776. )}
  777. </div>
  778. </div>
  779. </div>
  780. <FloatRightContainer isMobile={isMobile} isOpen={showPreview} onClose={hidePreview} footer={null}>
  781. {showPreview && <div ref={previewScrollRef} className={cn(s.previewWrap, isMobile && s.isMobile, 'relative h-full overflow-y-scroll border-l border-[#F2F4F7]')}>
  782. <div className={cn(s.previewHeader, previewScrolled && `${s.fixed} pb-3`)}>
  783. <div className='flex items-center justify-between px-8'>
  784. <div className='grow flex items-center'>
  785. <div>{t('datasetCreation.stepTwo.previewTitle')}</div>
  786. {docForm === DocForm.QA && !previewSwitched && (
  787. <Button className='ml-2 !h-[26px] !py-[3px] !px-2 !text-xs !font-medium !text-primary-600' onClick={previewSwitch}>{t('datasetCreation.stepTwo.previewButton')}</Button>
  788. )}
  789. </div>
  790. <div className='flex items-center justify-center w-6 h-6 cursor-pointer' onClick={hidePreview}>
  791. <XMarkIcon className='h-4 w-4'></XMarkIcon>
  792. </div>
  793. </div>
  794. {docForm === DocForm.QA && !previewSwitched && (
  795. <div className='px-8 pr-12 text-xs text-gray-500'>
  796. <span>{t('datasetCreation.stepTwo.previewSwitchTipStart')}</span>
  797. <span className='text-amber-600'>{t('datasetCreation.stepTwo.previewSwitchTipEnd')}</span>
  798. </div>
  799. )}
  800. </div>
  801. <div className='my-4 px-8 space-y-4'>
  802. {previewSwitched && docForm === DocForm.QA && fileIndexingEstimate?.qa_preview && (
  803. <>
  804. {fileIndexingEstimate?.qa_preview.map((item, index) => (
  805. <PreviewItem type={PreviewType.QA} key={item.question} qa={item} index={index + 1} />
  806. ))}
  807. </>
  808. )}
  809. {(docForm === DocForm.TEXT || !previewSwitched) && fileIndexingEstimate?.preview && (
  810. <>
  811. {fileIndexingEstimate?.preview.map((item, index) => (
  812. <PreviewItem type={PreviewType.TEXT} key={item} content={item} index={index + 1} />
  813. ))}
  814. </>
  815. )}
  816. {previewSwitched && docForm === DocForm.QA && !fileIndexingEstimate?.qa_preview && (
  817. <div className='flex items-center justify-center h-[200px]'>
  818. <Loading type='area' />
  819. </div>
  820. )}
  821. {!previewSwitched && !fileIndexingEstimate?.preview && (
  822. <div className='flex items-center justify-center h-[200px]'>
  823. <Loading type='area' />
  824. </div>
  825. )}
  826. </div>
  827. </div>}
  828. {!showPreview && (
  829. <div className={cn(s.sideTip)}>
  830. <div className={s.tipCard}>
  831. <span className={s.icon} />
  832. <div className={s.title}>{t('datasetCreation.stepTwo.sideTipTitle')}</div>
  833. <div className={s.content}>
  834. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP1')}</p>
  835. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP2')}</p>
  836. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP3')}</p>
  837. <p>{t('datasetCreation.stepTwo.sideTipP4')}</p>
  838. </div>
  839. </div>
  840. </div>
  841. )}
  842. </FloatRightContainer>
  843. </div>
  844. )
  845. }
  846. export default StepTwo