index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. 'use client'
  2. import { useState } from 'react'
  3. import { useMount } from 'ahooks'
  4. import { useContext } from 'use-context-selector'
  5. import { useTranslation } from 'react-i18next'
  6. import { useSWRConfig } from 'swr'
  7. import { unstable_serialize } from 'swr/infinite'
  8. import PermissionSelector from '../permission-selector'
  9. import IndexMethodRadio from '../index-method-radio'
  10. import RetrievalSettings from '../../external-knowledge-base/create/RetrievalSettings'
  11. import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'
  12. import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/economical-retrieval-method-config'
  13. import { ToastContext } from '@/app/components/base/toast'
  14. import Button from '@/app/components/base/button'
  15. import Input from '@/app/components/base/input'
  16. import Textarea from '@/app/components/base/textarea'
  17. import Divider from '@/app/components/base/divider'
  18. import { ApiConnectionMod } from '@/app/components/base/icons/src/vender/solid/development'
  19. import { updateDatasetSetting } from '@/service/datasets'
  20. import type { DataSetListResponse } from '@/models/datasets'
  21. import DatasetDetailContext from '@/context/dataset-detail'
  22. import { type RetrievalConfig } from '@/types/app'
  23. import { useAppContext } from '@/context/app-context'
  24. import { ensureRerankModelSelected, isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model'
  25. import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'
  26. import {
  27. useModelList,
  28. useModelListAndDefaultModelAndCurrentProviderAndModel,
  29. } from '@/app/components/header/account-setting/model-provider-page/hooks'
  30. import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
  31. import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
  32. import { fetchMembers } from '@/service/common'
  33. import type { Member } from '@/models/common'
  34. const rowClass = `
  35. flex justify-between py-4 flex-wrap gap-y-2
  36. `
  37. const labelClass = `
  38. flex items-center w-[168px] h-9
  39. `
  40. const getKey = (pageIndex: number, previousPageData: DataSetListResponse) => {
  41. if (!pageIndex || previousPageData.has_more)
  42. return { url: 'datasets', params: { page: pageIndex + 1, limit: 30 } }
  43. return null
  44. }
  45. const Form = () => {
  46. const { t } = useTranslation()
  47. const { notify } = useContext(ToastContext)
  48. const { mutate } = useSWRConfig()
  49. const { isCurrentWorkspaceDatasetOperator } = useAppContext()
  50. const { dataset: currentDataset, mutateDatasetRes: mutateDatasets } = useContext(DatasetDetailContext)
  51. const [loading, setLoading] = useState(false)
  52. const [name, setName] = useState(currentDataset?.name ?? '')
  53. const [description, setDescription] = useState(currentDataset?.description ?? '')
  54. const [permission, setPermission] = useState(currentDataset?.permission)
  55. const [topK, setTopK] = useState(currentDataset?.external_retrieval_model.top_k ?? 2)
  56. const [scoreThreshold, setScoreThreshold] = useState(currentDataset?.external_retrieval_model.score_threshold ?? 0.5)
  57. const [scoreThresholdEnabled, setScoreThresholdEnabled] = useState(currentDataset?.external_retrieval_model.score_threshold_enabled ?? false)
  58. const [selectedMemberIDs, setSelectedMemberIDs] = useState<string[]>(currentDataset?.partial_member_list || [])
  59. const [memberList, setMemberList] = useState<Member[]>([])
  60. const [indexMethod, setIndexMethod] = useState(currentDataset?.indexing_technique)
  61. const [retrievalConfig, setRetrievalConfig] = useState(currentDataset?.retrieval_model_dict as RetrievalConfig)
  62. const [embeddingModel, setEmbeddingModel] = useState<DefaultModel>(
  63. currentDataset?.embedding_model
  64. ? {
  65. provider: currentDataset.embedding_model_provider,
  66. model: currentDataset.embedding_model,
  67. }
  68. : {
  69. provider: '',
  70. model: '',
  71. },
  72. )
  73. const {
  74. modelList: rerankModelList,
  75. defaultModel: rerankDefaultModel,
  76. currentModel: isRerankDefaultModelValid,
  77. } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.rerank)
  78. const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)
  79. const getMembers = async () => {
  80. const { accounts } = await fetchMembers({ url: '/workspaces/current/members', params: {} })
  81. if (!accounts)
  82. setMemberList([])
  83. else
  84. setMemberList(accounts)
  85. }
  86. const handleSettingsChange = (data: { top_k?: number; score_threshold?: number; score_threshold_enabled?: boolean }) => {
  87. if (data.top_k !== undefined)
  88. setTopK(data.top_k)
  89. if (data.score_threshold !== undefined)
  90. setScoreThreshold(data.score_threshold)
  91. if (data.score_threshold_enabled !== undefined)
  92. setScoreThresholdEnabled(data.score_threshold_enabled)
  93. }
  94. useMount(() => {
  95. getMembers()
  96. })
  97. const handleSave = async () => {
  98. if (loading)
  99. return
  100. if (!name?.trim()) {
  101. notify({ type: 'error', message: t('datasetSettings.form.nameError') })
  102. return
  103. }
  104. if (
  105. !isReRankModelSelected({
  106. rerankDefaultModel,
  107. isRerankDefaultModelValid: !!isRerankDefaultModelValid,
  108. rerankModelList,
  109. retrievalConfig,
  110. indexMethod,
  111. })
  112. ) {
  113. notify({ type: 'error', message: t('appDebug.datasetConfig.rerankModelRequired') })
  114. return
  115. }
  116. const postRetrievalConfig = ensureRerankModelSelected({
  117. rerankDefaultModel: rerankDefaultModel!,
  118. retrievalConfig,
  119. indexMethod,
  120. })
  121. if (postRetrievalConfig.weights) {
  122. postRetrievalConfig.weights.vector_setting.embedding_provider_name = currentDataset?.embedding_model_provider || ''
  123. postRetrievalConfig.weights.vector_setting.embedding_model_name = currentDataset?.embedding_model || ''
  124. }
  125. try {
  126. setLoading(true)
  127. const requestParams = {
  128. datasetId: currentDataset!.id,
  129. body: {
  130. name,
  131. description,
  132. permission,
  133. indexing_technique: indexMethod,
  134. retrieval_model: {
  135. ...postRetrievalConfig,
  136. score_threshold: postRetrievalConfig.score_threshold_enabled ? postRetrievalConfig.score_threshold : 0,
  137. },
  138. embedding_model: embeddingModel.model,
  139. embedding_model_provider: embeddingModel.provider,
  140. ...(currentDataset!.provider === 'external' && {
  141. external_knowledge_id: currentDataset!.external_knowledge_info.external_knowledge_id,
  142. external_knowledge_api_id: currentDataset!.external_knowledge_info.external_knowledge_api_id,
  143. external_retrieval_model: {
  144. top_k: topK,
  145. score_threshold: scoreThreshold,
  146. score_threshold_enabled: scoreThresholdEnabled,
  147. },
  148. }),
  149. },
  150. } as any
  151. if (permission === 'partial_members') {
  152. requestParams.body.partial_member_list = selectedMemberIDs.map((id) => {
  153. return {
  154. user_id: id,
  155. role: memberList.find(member => member.id === id)?.role,
  156. }
  157. })
  158. }
  159. await updateDatasetSetting(requestParams)
  160. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  161. if (mutateDatasets) {
  162. await mutateDatasets()
  163. mutate(unstable_serialize(getKey))
  164. }
  165. }
  166. catch (e) {
  167. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  168. }
  169. finally {
  170. setLoading(false)
  171. }
  172. }
  173. return (
  174. <div className='w-full sm:w-[800px] p-4 sm:px-16 sm:py-6'>
  175. <div className={rowClass}>
  176. <div className={labelClass}>
  177. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.name')}</div>
  178. </div>
  179. <div className='w-full max-w-[480px]'>
  180. <Input
  181. disabled={!currentDataset?.embedding_available}
  182. className='h-9'
  183. value={name}
  184. onChange={e => setName(e.target.value)}
  185. />
  186. </div>
  187. </div>
  188. <div className={rowClass}>
  189. <div className={labelClass}>
  190. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.desc')}</div>
  191. </div>
  192. <div className='w-full max-w-[480px]'>
  193. <Textarea
  194. disabled={!currentDataset?.embedding_available}
  195. className='mb-2 h-[120px] resize-none'
  196. placeholder={t('datasetSettings.form.descPlaceholder') || ''}
  197. value={description}
  198. onChange={e => setDescription(e.target.value)}
  199. />
  200. </div>
  201. </div>
  202. <div className={rowClass}>
  203. <div className={labelClass}>
  204. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.permissions')}</div>
  205. </div>
  206. <div className='w-full sm:w-[480px]'>
  207. <PermissionSelector
  208. disabled={!currentDataset?.embedding_available || isCurrentWorkspaceDatasetOperator}
  209. permission={permission}
  210. value={selectedMemberIDs}
  211. onChange={v => setPermission(v)}
  212. onMemberSelect={setSelectedMemberIDs}
  213. memberList={memberList}
  214. />
  215. </div>
  216. </div>
  217. {currentDataset && currentDataset.indexing_technique && (
  218. <>
  219. <div className='w-full h-0 border-b-[0.5px] border-b-gray-200 my-2' />
  220. <div className={rowClass}>
  221. <div className={labelClass}>
  222. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.indexMethod')}</div>
  223. </div>
  224. <div className='w-full sm:w-[480px]'>
  225. <IndexMethodRadio
  226. disable={!currentDataset?.embedding_available}
  227. value={indexMethod}
  228. onChange={v => setIndexMethod(v)}
  229. />
  230. </div>
  231. </div>
  232. </>
  233. )}
  234. {indexMethod === 'high_quality' && (
  235. <div className={rowClass}>
  236. <div className={labelClass}>
  237. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.embeddingModel')}</div>
  238. </div>
  239. <div className='w-[480px]'>
  240. <ModelSelector
  241. triggerClassName=''
  242. defaultModel={embeddingModel}
  243. modelList={embeddingModelList}
  244. onSelect={(model: DefaultModel) => {
  245. setEmbeddingModel(model)
  246. }}
  247. />
  248. </div>
  249. </div>
  250. )}
  251. {/* Retrieval Method Config */}
  252. {currentDataset?.provider === 'external'
  253. ? <>
  254. <div className={rowClass}><Divider /></div>
  255. <div className={rowClass}>
  256. <div className={labelClass}>
  257. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.retrievalSetting.title')}</div>
  258. </div>
  259. <RetrievalSettings
  260. topK={topK}
  261. scoreThreshold={scoreThreshold}
  262. scoreThresholdEnabled={scoreThresholdEnabled}
  263. onChange={handleSettingsChange}
  264. isInRetrievalSetting={true}
  265. />
  266. </div>
  267. <div className={rowClass}><Divider /></div>
  268. <div className={rowClass}>
  269. <div className={labelClass}>
  270. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.externalKnowledgeAPI')}</div>
  271. </div>
  272. <div className='w-full max-w-[480px]'>
  273. <div className='flex h-full px-3 py-2 items-center gap-1 rounded-lg bg-components-input-bg-normal'>
  274. <ApiConnectionMod className='w-4 h-4 text-text-secondary' />
  275. <div className='overflow-hidden text-text-secondary text-ellipsis system-sm-medium'>
  276. {currentDataset?.external_knowledge_info.external_knowledge_api_name}
  277. </div>
  278. <div className='text-text-tertiary system-xs-regular'>·</div>
  279. <div className='text-text-tertiary system-xs-regular'>{currentDataset?.external_knowledge_info.external_knowledge_api_endpoint}</div>
  280. </div>
  281. </div>
  282. </div>
  283. <div className={rowClass}>
  284. <div className={labelClass}>
  285. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.externalKnowledgeID')}</div>
  286. </div>
  287. <div className='w-full max-w-[480px]'>
  288. <div className='flex h-full px-3 py-2 items-center gap-1 rounded-lg bg-components-input-bg-normal'>
  289. <div className='text-text-tertiary system-xs-regular'>{currentDataset?.external_knowledge_info.external_knowledge_id}</div>
  290. </div>
  291. </div>
  292. </div>
  293. <div className={rowClass}><Divider /></div>
  294. </>
  295. : <div className={rowClass}>
  296. <div className={labelClass}>
  297. <div>
  298. <div className='text-text-secondary system-sm-semibold'>{t('datasetSettings.form.retrievalSetting.title')}</div>
  299. <div className='leading-[18px] text-xs font-normal text-gray-500'>
  300. <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>
  301. {t('datasetSettings.form.retrievalSetting.description')}
  302. </div>
  303. </div>
  304. </div>
  305. <div className='w-[480px]'>
  306. {indexMethod === 'high_quality'
  307. ? (
  308. <RetrievalMethodConfig
  309. value={retrievalConfig}
  310. onChange={setRetrievalConfig}
  311. />
  312. )
  313. : (
  314. <EconomicalRetrievalMethodConfig
  315. value={retrievalConfig}
  316. onChange={setRetrievalConfig}
  317. />
  318. )}
  319. </div>
  320. </div>
  321. }
  322. <div className={rowClass}>
  323. <div className={labelClass} />
  324. <div className='w-[480px]'>
  325. <Button
  326. className='min-w-24'
  327. variant='primary'
  328. loading={loading}
  329. disabled={loading}
  330. onClick={handleSave}
  331. >
  332. {t('datasetSettings.form.save')}
  333. </Button>
  334. </div>
  335. </div>
  336. </div>
  337. )
  338. }
  339. export default Form