index.tsx 34 KB

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