index.tsx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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. } = useProviderContext()
  249. const getCreationParams = () => {
  250. let params
  251. if (isSetting) {
  252. params = {
  253. original_document_id: documentDetail?.id,
  254. doc_form: docForm,
  255. doc_language: docLanguage,
  256. process_rule: getProcessRule(),
  257. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  258. retrieval_model: retrievalConfig, // Readonly. If want to changed, just go to settings page.
  259. } as CreateDocumentReq
  260. }
  261. else { // create
  262. const indexMethod = getIndexing_technique()
  263. if (
  264. !isReRankModelSelected({
  265. rerankDefaultModel,
  266. isRerankDefaultModelVaild,
  267. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  268. retrievalConfig,
  269. indexMethod: indexMethod as string,
  270. })
  271. ) {
  272. Toast.notify({ type: 'error', message: t('appDebug.datasetConfig.rerankModelRequired') })
  273. return
  274. }
  275. const postRetrievalConfig = ensureRerankModelSelected({
  276. rerankDefaultModel: rerankDefaultModel!,
  277. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  278. retrievalConfig,
  279. indexMethod: indexMethod as string,
  280. })
  281. params = {
  282. data_source: {
  283. type: dataSourceType,
  284. info_list: {
  285. data_source_type: dataSourceType,
  286. },
  287. },
  288. indexing_technique: getIndexing_technique(),
  289. process_rule: getProcessRule(),
  290. doc_form: docForm,
  291. doc_language: docLanguage,
  292. retrieval_model: postRetrievalConfig,
  293. } as CreateDocumentReq
  294. if (dataSourceType === DataSourceType.FILE) {
  295. params.data_source.info_list.file_info_list = {
  296. file_ids: files.map(file => file.id || '').filter(Boolean),
  297. }
  298. }
  299. if (dataSourceType === DataSourceType.NOTION)
  300. params.data_source.info_list.notion_info_list = getNotionInfo()
  301. }
  302. return params
  303. }
  304. const getRules = async () => {
  305. try {
  306. const res = await fetchDefaultProcessRule({ url: '/datasets/process-rule' })
  307. const separator = res.rules.segmentation.separator
  308. setSegmentIdentifier((separator === '\n' ? '\\n' : separator) || '\\n')
  309. setMax(res.rules.segmentation.max_tokens)
  310. setRules(res.rules.pre_processing_rules)
  311. setDefaultConfig(res.rules)
  312. }
  313. catch (err) {
  314. console.log(err)
  315. }
  316. }
  317. const getRulesFromDetail = () => {
  318. if (documentDetail) {
  319. const rules = documentDetail.dataset_process_rule.rules
  320. const separator = rules.segmentation.separator
  321. const max = rules.segmentation.max_tokens
  322. setSegmentIdentifier((separator === '\n' ? '\\n' : separator) || '\\n')
  323. setMax(max)
  324. setRules(rules.pre_processing_rules)
  325. setDefaultConfig(rules)
  326. }
  327. }
  328. const getDefaultMode = () => {
  329. if (documentDetail)
  330. setSegmentationType(documentDetail.dataset_process_rule.mode)
  331. }
  332. const createHandle = async () => {
  333. if (isCreating)
  334. return
  335. setIsCreating(true)
  336. try {
  337. let res
  338. const params = getCreationParams()
  339. setIsCreating(true)
  340. if (!datasetId) {
  341. res = await createFirstDocument({
  342. body: params as CreateDocumentReq,
  343. })
  344. updateIndexingTypeCache && updateIndexingTypeCache(indexType as string)
  345. updateResultCache && updateResultCache(res)
  346. }
  347. else {
  348. res = await createDocument({
  349. datasetId,
  350. body: params as CreateDocumentReq,
  351. })
  352. updateIndexingTypeCache && updateIndexingTypeCache(indexType as string)
  353. updateResultCache && updateResultCache(res)
  354. }
  355. if (mutateDatasetRes)
  356. mutateDatasetRes()
  357. onStepChange && onStepChange(+1)
  358. isSetting && onSave && onSave()
  359. }
  360. catch (err) {
  361. Toast.notify({
  362. type: 'error',
  363. message: `${err}`,
  364. })
  365. }
  366. finally {
  367. setIsCreating(false)
  368. }
  369. }
  370. const handleSwitch = (state: boolean) => {
  371. if (state)
  372. setDocForm(DocForm.QA)
  373. else
  374. setDocForm(DocForm.TEXT)
  375. }
  376. const handleSelect = (language: string) => {
  377. setDocLanguage(language)
  378. }
  379. const changeToEconomicalType = () => {
  380. if (!hasSetIndexType) {
  381. setIndexType(IndexingType.ECONOMICAL)
  382. setDocForm(DocForm.TEXT)
  383. }
  384. }
  385. const previewSwitch = async () => {
  386. setPreviewSwitched(true)
  387. if (segmentationType === SegmentType.AUTO)
  388. setAutomaticFileIndexingEstimate(null)
  389. else
  390. setCustomFileIndexingEstimate(null)
  391. await fetchFileIndexingEstimate(DocForm.QA)
  392. }
  393. useEffect(() => {
  394. // fetch rules
  395. if (!isSetting) {
  396. getRules()
  397. }
  398. else {
  399. getRulesFromDetail()
  400. getDefaultMode()
  401. }
  402. }, [])
  403. useEffect(() => {
  404. scrollRef.current?.addEventListener('scroll', scrollHandle)
  405. return () => {
  406. scrollRef.current?.removeEventListener('scroll', scrollHandle)
  407. }
  408. }, [])
  409. useLayoutEffect(() => {
  410. if (showPreview) {
  411. previewScrollRef.current?.addEventListener('scroll', previewScrollHandle)
  412. return () => {
  413. previewScrollRef.current?.removeEventListener('scroll', previewScrollHandle)
  414. }
  415. }
  416. }, [showPreview])
  417. useEffect(() => {
  418. if (indexingType === IndexingType.ECONOMICAL && docForm === DocForm.QA)
  419. setDocForm(DocForm.TEXT)
  420. }, [indexingType, docForm])
  421. useEffect(() => {
  422. // get indexing type by props
  423. if (indexingType)
  424. setIndexType(indexingType as IndexingType)
  425. else
  426. setIndexType(hasSetAPIKEY ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
  427. }, [hasSetAPIKEY, indexingType, datasetId])
  428. useEffect(() => {
  429. if (segmentationType === SegmentType.AUTO) {
  430. setAutomaticFileIndexingEstimate(null)
  431. setShowPreview()
  432. fetchFileIndexingEstimate()
  433. setPreviewSwitched(false)
  434. }
  435. else {
  436. hidePreview()
  437. setCustomFileIndexingEstimate(null)
  438. setPreviewSwitched(false)
  439. }
  440. }, [segmentationType, indexType])
  441. const [retrievalConfig, setRetrievalConfig] = useState(currentDataset?.retrieval_model_dict || {
  442. search_method: RETRIEVE_METHOD.semantic,
  443. reranking_enable: false,
  444. reranking_model: {
  445. reranking_provider_name: rerankDefaultModel?.model_provider.provider_name,
  446. reranking_model_name: rerankDefaultModel?.model_name,
  447. },
  448. top_k: 3,
  449. score_threshold_enable: false,
  450. score_threshold: 0.5,
  451. } as RetrievalConfig)
  452. return (
  453. <div className='flex w-full h-full'>
  454. <div ref={scrollRef} className='relative h-full w-full overflow-y-scroll'>
  455. <div className={cn(s.pageHeader, scrolled && s.fixed)}>{t('datasetCreation.steps.two')}</div>
  456. <div className={cn(s.form)}>
  457. <div className={s.label}>{t('datasetCreation.stepTwo.segmentation')}</div>
  458. <div className='max-w-[640px]'>
  459. <div
  460. className={cn(
  461. s.radioItem,
  462. s.segmentationItem,
  463. segmentationType === SegmentType.AUTO && s.active,
  464. )}
  465. onClick={() => setSegmentationType(SegmentType.AUTO)}
  466. >
  467. <span className={cn(s.typeIcon, s.auto)} />
  468. <span className={cn(s.radio)} />
  469. <div className={s.typeHeader}>
  470. <div className={s.title}>{t('datasetCreation.stepTwo.auto')}</div>
  471. <div className={s.tip}>{t('datasetCreation.stepTwo.autoDescription')}</div>
  472. </div>
  473. </div>
  474. <div
  475. className={cn(
  476. s.radioItem,
  477. s.segmentationItem,
  478. segmentationType === SegmentType.CUSTOM && s.active,
  479. segmentationType === SegmentType.CUSTOM && s.custom,
  480. )}
  481. onClick={() => setSegmentationType(SegmentType.CUSTOM)}
  482. >
  483. <span className={cn(s.typeIcon, s.customize)} />
  484. <span className={cn(s.radio)} />
  485. <div className={s.typeHeader}>
  486. <div className={s.title}>{t('datasetCreation.stepTwo.custom')}</div>
  487. <div className={s.tip}>{t('datasetCreation.stepTwo.customDescription')}</div>
  488. </div>
  489. {segmentationType === SegmentType.CUSTOM && (
  490. <div className={s.typeFormBody}>
  491. <div className={s.formRow}>
  492. <div className='w-full'>
  493. <div className={s.label}>{t('datasetCreation.stepTwo.separator')}</div>
  494. <input
  495. type="text"
  496. className={s.input}
  497. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''} value={segmentIdentifier}
  498. onChange={e => setSegmentIdentifier(e.target.value)}
  499. />
  500. </div>
  501. </div>
  502. <div className={s.formRow}>
  503. <div className='w-full'>
  504. <div className={s.label}>{t('datasetCreation.stepTwo.maxLength')}</div>
  505. <input
  506. type="number"
  507. className={s.input}
  508. placeholder={t('datasetCreation.stepTwo.separatorPlaceholder') || ''}
  509. value={max}
  510. min={1}
  511. onChange={e => setMax(parseInt(e.target.value.replace(/^0+/, ''), 10))}
  512. />
  513. </div>
  514. </div>
  515. <div className={s.formRow}>
  516. <div className='w-full'>
  517. <div className={s.label}>{t('datasetCreation.stepTwo.rules')}</div>
  518. {rules.map(rule => (
  519. <div key={rule.id} className={s.ruleItem}>
  520. <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" />
  521. <label htmlFor={rule.id} className="ml-2 text-sm font-normal cursor-pointer text-gray-800">{getRuleName(rule.id)}</label>
  522. </div>
  523. ))}
  524. </div>
  525. </div>
  526. <div className={s.formFooter}>
  527. <Button type="primary" className={cn(s.button, '!h-8 text-primary-600')} onClick={confirmChangeCustomConfig}>{t('datasetCreation.stepTwo.preview')}</Button>
  528. <Button className={cn(s.button, 'ml-2 !h-8')} onClick={resetRules}>{t('datasetCreation.stepTwo.reset')}</Button>
  529. </div>
  530. </div>
  531. )}
  532. </div>
  533. </div>
  534. <div className={s.label}>{t('datasetCreation.stepTwo.indexMode')}</div>
  535. <div className='max-w-[640px]'>
  536. <div className='flex items-center gap-3'>
  537. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.QUALIFIED)) && (
  538. <div
  539. className={cn(
  540. s.radioItem,
  541. s.indexItem,
  542. !hasSetAPIKEY && s.disabled,
  543. !hasSetIndexType && indexType === IndexingType.QUALIFIED && s.active,
  544. hasSetIndexType && s.disabled,
  545. hasSetIndexType && '!w-full',
  546. )}
  547. onClick={() => {
  548. if (hasSetAPIKEY)
  549. setIndexType(IndexingType.QUALIFIED)
  550. }}
  551. >
  552. <span className={cn(s.typeIcon, s.qualified)} />
  553. {!hasSetIndexType && <span className={cn(s.radio)} />}
  554. <div className={s.typeHeader}>
  555. <div className={s.title}>
  556. {t('datasetCreation.stepTwo.qualified')}
  557. {!hasSetIndexType && <span className={s.recommendTag}>{t('datasetCreation.stepTwo.recommend')}</span>}
  558. </div>
  559. <div className={s.tip}>{t('datasetCreation.stepTwo.qualifiedTip')}</div>
  560. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  561. {
  562. estimateTokes
  563. ? (
  564. <div className='text-xs font-medium text-gray-800'>{formatNumber(estimateTokes.tokens)} tokens(<span className='text-yellow-500'>${formatNumber(estimateTokes.total_price)}</span>)</div>
  565. )
  566. : (
  567. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  568. )
  569. }
  570. </div>
  571. {!hasSetAPIKEY && (
  572. <div className={s.warningTip}>
  573. <span>{t('datasetCreation.stepTwo.warning')}&nbsp;</span>
  574. <span className={s.click} onClick={onSetting}>{t('datasetCreation.stepTwo.click')}</span>
  575. </div>
  576. )}
  577. </div>
  578. )}
  579. {(!hasSetIndexType || (hasSetIndexType && indexingType === IndexingType.ECONOMICAL)) && (
  580. <div
  581. className={cn(
  582. s.radioItem,
  583. s.indexItem,
  584. !hasSetIndexType && indexType === IndexingType.ECONOMICAL && s.active,
  585. hasSetIndexType && s.disabled,
  586. hasSetIndexType && '!w-full',
  587. )}
  588. onClick={changeToEconomicalType}
  589. >
  590. <span className={cn(s.typeIcon, s.economical)} />
  591. {!hasSetIndexType && <span className={cn(s.radio)} />}
  592. <div className={s.typeHeader}>
  593. <div className={s.title}>{t('datasetCreation.stepTwo.economical')}</div>
  594. <div className={s.tip}>{t('datasetCreation.stepTwo.economicalTip')}</div>
  595. <div className='pb-0.5 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateCost')}</div>
  596. <div className='text-xs font-medium text-gray-800'>0 tokens</div>
  597. </div>
  598. </div>
  599. )}
  600. </div>
  601. {hasSetIndexType && (
  602. <div className='mt-2 text-xs text-gray-500 font-medium'>
  603. {t('datasetCreation.stepTwo.indexSettedTip')}
  604. <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
  605. </div>
  606. )}
  607. {IS_CE_EDITION && indexType === IndexingType.QUALIFIED && (
  608. <div className='mt-3 rounded-xl bg-gray-50 border border-gray-100'>
  609. <div className='flex justify-between items-center px-5 py-4'>
  610. <div className='flex justify-center items-center w-8 h-8 rounded-lg bg-indigo-50'>
  611. <MessageChatSquare className='w-4 h-4' />
  612. </div>
  613. <div className='grow mx-3'>
  614. <div className='mb-[2px] text-md font-medium text-gray-900'>{t('datasetCreation.stepTwo.QATitle')}</div>
  615. <div className='inline-flex items-center text-[13px] leading-[18px] text-gray-500'>
  616. <span className='pr-1'>{t('datasetCreation.stepTwo.QALanguage')}</span>
  617. <LanguageSelect currentLanguage={docLanguage} onSelect={handleSelect} />
  618. </div>
  619. </div>
  620. <div className='shrink-0'>
  621. <Switch
  622. defaultValue={docForm === DocForm.QA}
  623. onChange={handleSwitch}
  624. size='md'
  625. />
  626. </div>
  627. </div>
  628. {docForm === DocForm.QA && !QATipHide && (
  629. <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'>
  630. {t('datasetCreation.stepTwo.QATip')}
  631. <XClose className='w-4 h-4 text-gray-500 cursor-pointer' onClick={() => setQATipHide(true)} />
  632. </div>
  633. )}
  634. </div>
  635. )}
  636. {/* Retrieval Method Config */}
  637. <div>
  638. {!datasetId
  639. ? (
  640. <div className={s.label}>
  641. {t('datasetSettings.form.retrievalSetting.title')}
  642. <div className='leading-[18px] text-xs font-normal text-gray-500'>
  643. <a target='_blank' href='https://docs.dify.ai/advanced/retrieval-augment' className='text-[#155eef]'>{t('datasetSettings.form.retrievalSetting.learnMore')}</a>
  644. {t('datasetSettings.form.retrievalSetting.longDescription')}
  645. </div>
  646. </div>
  647. )
  648. : (
  649. <div className={cn(s.label, 'flex justify-between items-center')}>
  650. <div>{t('datasetSettings.form.retrievalSetting.title')}</div>
  651. </div>
  652. )}
  653. <div className='max-w-[640px]'>
  654. {!datasetId
  655. ? (<>
  656. {getIndexing_technique() === IndexingType.QUALIFIED
  657. ? (
  658. <RetrievalMethodConfig
  659. value={retrievalConfig}
  660. onChange={setRetrievalConfig}
  661. />
  662. )
  663. : (
  664. <EconomicalRetrievalMethodConfig
  665. value={retrievalConfig}
  666. onChange={setRetrievalConfig}
  667. />
  668. )}
  669. </>)
  670. : (
  671. <div>
  672. <RetrievalMethodInfo
  673. value={retrievalConfig}
  674. />
  675. <div className='mt-2 text-xs text-gray-500 font-medium'>
  676. {t('datasetCreation.stepTwo.retrivalSettedTip')}
  677. <Link className='text-[#155EEF]' href={`/datasets/${datasetId}/settings`}>{t('datasetCreation.stepTwo.datasetSettingLink')}</Link>
  678. </div>
  679. </div>
  680. )}
  681. </div>
  682. </div>
  683. <div className={s.source}>
  684. <div className={s.sourceContent}>
  685. {dataSourceType === DataSourceType.FILE && (
  686. <>
  687. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.fileSource')}</div>
  688. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  689. <span className={cn(s.fileIcon, files.length && s[files[0].extension || ''])} />
  690. {getFileName(files[0].name || '')}
  691. {files.length > 1 && (
  692. <span className={s.sourceCount}>
  693. <span>{t('datasetCreation.stepTwo.other')}</span>
  694. <span>{files.length - 1}</span>
  695. <span>{t('datasetCreation.stepTwo.fileUnit')}</span>
  696. </span>
  697. )}
  698. </div>
  699. </>
  700. )}
  701. {dataSourceType === DataSourceType.NOTION && (
  702. <>
  703. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.notionSource')}</div>
  704. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  705. <NotionIcon
  706. className='shrink-0 mr-1'
  707. type='page'
  708. src={notionPages[0]?.page_icon}
  709. />
  710. {notionPages[0]?.page_name}
  711. {notionPages.length > 1 && (
  712. <span className={s.sourceCount}>
  713. <span>{t('datasetCreation.stepTwo.other')}</span>
  714. <span>{notionPages.length - 1}</span>
  715. <span>{t('datasetCreation.stepTwo.notionUnit')}</span>
  716. </span>
  717. )}
  718. </div>
  719. </>
  720. )}
  721. </div>
  722. <div className={s.divider} />
  723. <div className={s.segmentCount}>
  724. <div className='mb-2 text-xs font-medium text-gray-500'>{t('datasetCreation.stepTwo.emstimateSegment')}</div>
  725. <div className='flex items-center text-sm leading-6 font-medium text-gray-800'>
  726. {
  727. fileIndexingEstimate
  728. ? (
  729. <div className='text-xs font-medium text-gray-800'>{formatNumber(fileIndexingEstimate.total_segments)} </div>
  730. )
  731. : (
  732. <div className={s.calculating}>{t('datasetCreation.stepTwo.calculating')}</div>
  733. )
  734. }
  735. </div>
  736. </div>
  737. </div>
  738. {!isSetting
  739. ? (
  740. <div className='flex items-center mt-8 py-2'>
  741. <Button onClick={() => onStepChange && onStepChange(-1)}>{t('datasetCreation.stepTwo.lastStep')}</Button>
  742. <div className={s.divider} />
  743. <Button loading={isCreating} type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.nextStep')}</Button>
  744. </div>
  745. )
  746. : (
  747. <div className='flex items-center mt-8 py-2'>
  748. <Button loading={isCreating} type='primary' onClick={createHandle}>{t('datasetCreation.stepTwo.save')}</Button>
  749. <Button className='ml-2' onClick={onCancel}>{t('datasetCreation.stepTwo.cancel')}</Button>
  750. </div>
  751. )}
  752. </div>
  753. </div>
  754. </div>
  755. {(showPreview)
  756. ? (
  757. <div ref={previewScrollRef} className={cn(s.previewWrap, 'relativeh-full overflow-y-scroll border-l border-[#F2F4F7]')}>
  758. <div className={cn(s.previewHeader, previewScrolled && `${s.fixed} pb-3`)}>
  759. <div className='flex items-center justify-between px-8'>
  760. <div className='grow flex items-center'>
  761. <div>{t('datasetCreation.stepTwo.previewTitle')}</div>
  762. {docForm === DocForm.QA && !previewSwitched && (
  763. <Button className='ml-2 !h-[26px] !py-[3px] !px-2 !text-xs !font-medium !text-primary-600' onClick={previewSwitch}>{t('datasetCreation.stepTwo.previewButton')}</Button>
  764. )}
  765. </div>
  766. <div className='flex items-center justify-center w-6 h-6 cursor-pointer' onClick={hidePreview}>
  767. <XMarkIcon className='h-4 w-4'></XMarkIcon>
  768. </div>
  769. </div>
  770. {docForm === DocForm.QA && !previewSwitched && (
  771. <div className='px-8 pr-12 text-xs text-gray-500'>
  772. <span>{t('datasetCreation.stepTwo.previewSwitchTipStart')}</span>
  773. <span className='text-amber-600'>{t('datasetCreation.stepTwo.previewSwitchTipEnd')}</span>
  774. </div>
  775. )}
  776. </div>
  777. <div className='my-4 px-8 space-y-4'>
  778. {previewSwitched && docForm === DocForm.QA && fileIndexingEstimate?.qa_preview && (
  779. <>
  780. {fileIndexingEstimate?.qa_preview.map((item, index) => (
  781. <PreviewItem type={PreviewType.QA} key={item.question} qa={item} index={index + 1} />
  782. ))}
  783. </>
  784. )}
  785. {(docForm === DocForm.TEXT || !previewSwitched) && fileIndexingEstimate?.preview && (
  786. <>
  787. {fileIndexingEstimate?.preview.map((item, index) => (
  788. <PreviewItem type={PreviewType.TEXT} key={item} content={item} index={index + 1} />
  789. ))}
  790. </>
  791. )}
  792. {previewSwitched && docForm === DocForm.QA && !fileIndexingEstimate?.qa_preview && (
  793. <div className='flex items-center justify-center h-[200px]'>
  794. <Loading type='area' />
  795. </div>
  796. )}
  797. {!previewSwitched && !fileIndexingEstimate?.preview && (
  798. <div className='flex items-center justify-center h-[200px]'>
  799. <Loading type='area' />
  800. </div>
  801. )}
  802. </div>
  803. </div>
  804. )
  805. : (<div className={cn(s.sideTip)}>
  806. <div className={s.tipCard}>
  807. <span className={s.icon} />
  808. <div className={s.title}>{t('datasetCreation.stepTwo.sideTipTitle')}</div>
  809. <div className={s.content}>
  810. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP1')}</p>
  811. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP2')}</p>
  812. <p className='mb-3'>{t('datasetCreation.stepTwo.sideTipP3')}</p>
  813. <p>{t('datasetCreation.stepTwo.sideTipP4')}</p>
  814. </div>
  815. </div>
  816. </div>)}
  817. </div>
  818. )
  819. }
  820. export default StepTwo