index.tsx 41 KB

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