index.tsx 36 KB

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