dataset_service.py 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  1. import datetime
  2. import json
  3. import logging
  4. import random
  5. import time
  6. import uuid
  7. from typing import Any, Optional
  8. from flask_login import current_user # type: ignore
  9. from sqlalchemy import func
  10. from werkzeug.exceptions import NotFound
  11. from configs import dify_config
  12. from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
  13. from core.model_manager import ModelManager
  14. from core.model_runtime.entities.model_entities import ModelType
  15. from core.rag.index_processor.constant.index_type import IndexType
  16. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  17. from events.dataset_event import dataset_was_deleted
  18. from events.document_event import document_was_deleted
  19. from extensions.ext_database import db
  20. from extensions.ext_redis import redis_client
  21. from libs import helper
  22. from models.account import Account, TenantAccountRole
  23. from models.dataset import (
  24. AppDatasetJoin,
  25. ChildChunk,
  26. Dataset,
  27. DatasetAutoDisableLog,
  28. DatasetCollectionBinding,
  29. DatasetPermission,
  30. DatasetPermissionEnum,
  31. DatasetProcessRule,
  32. DatasetQuery,
  33. Document,
  34. DocumentSegment,
  35. ExternalKnowledgeBindings,
  36. )
  37. from models.model import UploadFile
  38. from models.source import DataSourceOauthBinding
  39. from services.entities.knowledge_entities.knowledge_entities import (
  40. ChildChunkUpdateArgs,
  41. KnowledgeConfig,
  42. RerankingModel,
  43. RetrievalModel,
  44. SegmentUpdateArgs,
  45. )
  46. from services.errors.account import InvalidActionError, NoPermissionError
  47. from services.errors.chunk import ChildChunkDeleteIndexError, ChildChunkIndexingError
  48. from services.errors.dataset import DatasetNameDuplicateError
  49. from services.errors.document import DocumentIndexingError
  50. from services.errors.file import FileNotExistsError
  51. from services.external_knowledge_service import ExternalDatasetService
  52. from services.feature_service import FeatureModel, FeatureService
  53. from services.tag_service import TagService
  54. from services.vector_service import VectorService
  55. from tasks.batch_clean_document_task import batch_clean_document_task
  56. from tasks.clean_notion_document_task import clean_notion_document_task
  57. from tasks.deal_dataset_vector_index_task import deal_dataset_vector_index_task
  58. from tasks.delete_segment_from_index_task import delete_segment_from_index_task
  59. from tasks.disable_segment_from_index_task import disable_segment_from_index_task
  60. from tasks.disable_segments_from_index_task import disable_segments_from_index_task
  61. from tasks.document_indexing_task import document_indexing_task
  62. from tasks.document_indexing_update_task import document_indexing_update_task
  63. from tasks.duplicate_document_indexing_task import duplicate_document_indexing_task
  64. from tasks.enable_segments_to_index_task import enable_segments_to_index_task
  65. from tasks.recover_document_indexing_task import recover_document_indexing_task
  66. from tasks.retry_document_indexing_task import retry_document_indexing_task
  67. from tasks.sync_website_document_indexing_task import sync_website_document_indexing_task
  68. class DatasetService:
  69. @staticmethod
  70. def get_datasets(page, per_page, tenant_id=None, user=None, search=None, tag_ids=None):
  71. query = Dataset.query.filter(Dataset.tenant_id == tenant_id).order_by(Dataset.created_at.desc())
  72. if user:
  73. # get permitted dataset ids
  74. dataset_permission = DatasetPermission.query.filter_by(account_id=user.id, tenant_id=tenant_id).all()
  75. permitted_dataset_ids = {dp.dataset_id for dp in dataset_permission} if dataset_permission else None
  76. if user.current_role == TenantAccountRole.DATASET_OPERATOR:
  77. # only show datasets that the user has permission to access
  78. if permitted_dataset_ids:
  79. query = query.filter(Dataset.id.in_(permitted_dataset_ids))
  80. else:
  81. return [], 0
  82. else:
  83. # show all datasets that the user has permission to access
  84. if permitted_dataset_ids:
  85. query = query.filter(
  86. db.or_(
  87. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  88. db.and_(Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id),
  89. db.and_(
  90. Dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM,
  91. Dataset.id.in_(permitted_dataset_ids),
  92. ),
  93. )
  94. )
  95. else:
  96. query = query.filter(
  97. db.or_(
  98. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  99. db.and_(Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id),
  100. )
  101. )
  102. else:
  103. # if no user, only show datasets that are shared with all team members
  104. query = query.filter(Dataset.permission == DatasetPermissionEnum.ALL_TEAM)
  105. if search:
  106. query = query.filter(Dataset.name.ilike(f"%{search}%"))
  107. if tag_ids:
  108. target_ids = TagService.get_target_ids_by_tag_ids("knowledge", tenant_id, tag_ids)
  109. if target_ids:
  110. query = query.filter(Dataset.id.in_(target_ids))
  111. else:
  112. return [], 0
  113. datasets = query.paginate(page=page, per_page=per_page, max_per_page=100, error_out=False)
  114. return datasets.items, datasets.total
  115. @staticmethod
  116. def get_process_rules(dataset_id):
  117. # get the latest process rule
  118. dataset_process_rule = (
  119. db.session.query(DatasetProcessRule)
  120. .filter(DatasetProcessRule.dataset_id == dataset_id)
  121. .order_by(DatasetProcessRule.created_at.desc())
  122. .limit(1)
  123. .one_or_none()
  124. )
  125. if dataset_process_rule:
  126. mode = dataset_process_rule.mode
  127. rules = dataset_process_rule.rules_dict
  128. else:
  129. mode = DocumentService.DEFAULT_RULES["mode"]
  130. rules = DocumentService.DEFAULT_RULES["rules"]
  131. return {"mode": mode, "rules": rules}
  132. @staticmethod
  133. def get_datasets_by_ids(ids, tenant_id):
  134. datasets = Dataset.query.filter(Dataset.id.in_(ids), Dataset.tenant_id == tenant_id).paginate(
  135. page=1, per_page=len(ids), max_per_page=len(ids), error_out=False
  136. )
  137. return datasets.items, datasets.total
  138. @staticmethod
  139. def create_empty_dataset(
  140. tenant_id: str,
  141. name: str,
  142. description: Optional[str],
  143. indexing_technique: Optional[str],
  144. account: Account,
  145. permission: Optional[str] = None,
  146. provider: str = "vendor",
  147. external_knowledge_api_id: Optional[str] = None,
  148. external_knowledge_id: Optional[str] = None,
  149. ):
  150. # check if dataset name already exists
  151. if Dataset.query.filter_by(name=name, tenant_id=tenant_id).first():
  152. raise DatasetNameDuplicateError(f"Dataset with name {name} already exists.")
  153. embedding_model = None
  154. if indexing_technique == "high_quality":
  155. model_manager = ModelManager()
  156. embedding_model = model_manager.get_default_model_instance(
  157. tenant_id=tenant_id, model_type=ModelType.TEXT_EMBEDDING
  158. )
  159. dataset = Dataset(name=name, indexing_technique=indexing_technique)
  160. # dataset = Dataset(name=name, provider=provider, config=config)
  161. dataset.description = description
  162. dataset.created_by = account.id
  163. dataset.updated_by = account.id
  164. dataset.tenant_id = tenant_id
  165. dataset.embedding_model_provider = embedding_model.provider if embedding_model else None
  166. dataset.embedding_model = embedding_model.model if embedding_model else None
  167. dataset.permission = permission or DatasetPermissionEnum.ONLY_ME
  168. dataset.provider = provider
  169. db.session.add(dataset)
  170. db.session.flush()
  171. if provider == "external" and external_knowledge_api_id:
  172. external_knowledge_api = ExternalDatasetService.get_external_knowledge_api(external_knowledge_api_id)
  173. if not external_knowledge_api:
  174. raise ValueError("External API template not found.")
  175. external_knowledge_binding = ExternalKnowledgeBindings(
  176. tenant_id=tenant_id,
  177. dataset_id=dataset.id,
  178. external_knowledge_api_id=external_knowledge_api_id,
  179. external_knowledge_id=external_knowledge_id,
  180. created_by=account.id,
  181. )
  182. db.session.add(external_knowledge_binding)
  183. db.session.commit()
  184. return dataset
  185. @staticmethod
  186. def get_dataset(dataset_id) -> Optional[Dataset]:
  187. dataset: Optional[Dataset] = Dataset.query.filter_by(id=dataset_id).first()
  188. return dataset
  189. @staticmethod
  190. def check_dataset_model_setting(dataset):
  191. if dataset.indexing_technique == "high_quality":
  192. try:
  193. model_manager = ModelManager()
  194. model_manager.get_model_instance(
  195. tenant_id=dataset.tenant_id,
  196. provider=dataset.embedding_model_provider,
  197. model_type=ModelType.TEXT_EMBEDDING,
  198. model=dataset.embedding_model,
  199. )
  200. except LLMBadRequestError:
  201. raise ValueError(
  202. "No Embedding Model available. Please configure a valid provider "
  203. "in the Settings -> Model Provider."
  204. )
  205. except ProviderTokenNotInitError as ex:
  206. raise ValueError(f"The dataset in unavailable, due to: {ex.description}")
  207. @staticmethod
  208. def check_embedding_model_setting(tenant_id: str, embedding_model_provider: str, embedding_model: str):
  209. try:
  210. model_manager = ModelManager()
  211. model_manager.get_model_instance(
  212. tenant_id=tenant_id,
  213. provider=embedding_model_provider,
  214. model_type=ModelType.TEXT_EMBEDDING,
  215. model=embedding_model,
  216. )
  217. except LLMBadRequestError:
  218. raise ValueError(
  219. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  220. )
  221. except ProviderTokenNotInitError as ex:
  222. raise ValueError(f"The dataset in unavailable, due to: {ex.description}")
  223. @staticmethod
  224. def update_dataset(dataset_id, data, user):
  225. dataset = DatasetService.get_dataset(dataset_id)
  226. if not dataset:
  227. raise ValueError("Dataset not found")
  228. DatasetService.check_dataset_permission(dataset, user)
  229. if dataset.provider == "external":
  230. external_retrieval_model = data.get("external_retrieval_model", None)
  231. if external_retrieval_model:
  232. dataset.retrieval_model = external_retrieval_model
  233. dataset.name = data.get("name", dataset.name)
  234. dataset.description = data.get("description", "")
  235. permission = data.get("permission")
  236. if permission:
  237. dataset.permission = permission
  238. external_knowledge_id = data.get("external_knowledge_id", None)
  239. db.session.add(dataset)
  240. if not external_knowledge_id:
  241. raise ValueError("External knowledge id is required.")
  242. external_knowledge_api_id = data.get("external_knowledge_api_id", None)
  243. if not external_knowledge_api_id:
  244. raise ValueError("External knowledge api id is required.")
  245. external_knowledge_binding = ExternalKnowledgeBindings.query.filter_by(dataset_id=dataset_id).first()
  246. if (
  247. external_knowledge_binding.external_knowledge_id != external_knowledge_id
  248. or external_knowledge_binding.external_knowledge_api_id != external_knowledge_api_id
  249. ):
  250. external_knowledge_binding.external_knowledge_id = external_knowledge_id
  251. external_knowledge_binding.external_knowledge_api_id = external_knowledge_api_id
  252. db.session.add(external_knowledge_binding)
  253. db.session.commit()
  254. else:
  255. data.pop("partial_member_list", None)
  256. data.pop("external_knowledge_api_id", None)
  257. data.pop("external_knowledge_id", None)
  258. data.pop("external_retrieval_model", None)
  259. filtered_data = {k: v for k, v in data.items() if v is not None or k == "description"}
  260. action = None
  261. if dataset.indexing_technique != data["indexing_technique"]:
  262. # if update indexing_technique
  263. if data["indexing_technique"] == "economy":
  264. action = "remove"
  265. filtered_data["embedding_model"] = None
  266. filtered_data["embedding_model_provider"] = None
  267. filtered_data["collection_binding_id"] = None
  268. elif data["indexing_technique"] == "high_quality":
  269. action = "add"
  270. # get embedding model setting
  271. try:
  272. model_manager = ModelManager()
  273. embedding_model = model_manager.get_model_instance(
  274. tenant_id=current_user.current_tenant_id,
  275. provider=data["embedding_model_provider"],
  276. model_type=ModelType.TEXT_EMBEDDING,
  277. model=data["embedding_model"],
  278. )
  279. filtered_data["embedding_model"] = embedding_model.model
  280. filtered_data["embedding_model_provider"] = embedding_model.provider
  281. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  282. embedding_model.provider, embedding_model.model
  283. )
  284. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  285. except LLMBadRequestError:
  286. raise ValueError(
  287. "No Embedding Model available. Please configure a valid provider "
  288. "in the Settings -> Model Provider."
  289. )
  290. except ProviderTokenNotInitError as ex:
  291. raise ValueError(ex.description)
  292. else:
  293. if (
  294. data["embedding_model_provider"] != dataset.embedding_model_provider
  295. or data["embedding_model"] != dataset.embedding_model
  296. ):
  297. action = "update"
  298. try:
  299. model_manager = ModelManager()
  300. embedding_model = model_manager.get_model_instance(
  301. tenant_id=current_user.current_tenant_id,
  302. provider=data["embedding_model_provider"],
  303. model_type=ModelType.TEXT_EMBEDDING,
  304. model=data["embedding_model"],
  305. )
  306. filtered_data["embedding_model"] = embedding_model.model
  307. filtered_data["embedding_model_provider"] = embedding_model.provider
  308. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  309. embedding_model.provider, embedding_model.model
  310. )
  311. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  312. except LLMBadRequestError:
  313. raise ValueError(
  314. "No Embedding Model available. Please configure a valid provider "
  315. "in the Settings -> Model Provider."
  316. )
  317. except ProviderTokenNotInitError as ex:
  318. raise ValueError(ex.description)
  319. filtered_data["updated_by"] = user.id
  320. filtered_data["updated_at"] = datetime.datetime.now()
  321. # update Retrieval model
  322. filtered_data["retrieval_model"] = data["retrieval_model"]
  323. dataset.query.filter_by(id=dataset_id).update(filtered_data)
  324. db.session.commit()
  325. if action:
  326. deal_dataset_vector_index_task.delay(dataset_id, action)
  327. return dataset
  328. @staticmethod
  329. def delete_dataset(dataset_id, user):
  330. dataset = DatasetService.get_dataset(dataset_id)
  331. if dataset is None:
  332. return False
  333. DatasetService.check_dataset_permission(dataset, user)
  334. dataset_was_deleted.send(dataset)
  335. db.session.delete(dataset)
  336. db.session.commit()
  337. return True
  338. @staticmethod
  339. def dataset_use_check(dataset_id) -> bool:
  340. count = AppDatasetJoin.query.filter_by(dataset_id=dataset_id).count()
  341. if count > 0:
  342. return True
  343. return False
  344. @staticmethod
  345. def check_dataset_permission(dataset, user):
  346. if dataset.tenant_id != user.current_tenant_id:
  347. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  348. raise NoPermissionError("You do not have permission to access this dataset.")
  349. if dataset.permission == DatasetPermissionEnum.ONLY_ME and dataset.created_by != user.id:
  350. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  351. raise NoPermissionError("You do not have permission to access this dataset.")
  352. if dataset.permission == "partial_members":
  353. user_permission = DatasetPermission.query.filter_by(dataset_id=dataset.id, account_id=user.id).first()
  354. if not user_permission and dataset.tenant_id != user.current_tenant_id and dataset.created_by != user.id:
  355. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  356. raise NoPermissionError("You do not have permission to access this dataset.")
  357. @staticmethod
  358. def check_dataset_operator_permission(user: Optional[Account] = None, dataset: Optional[Dataset] = None):
  359. if not dataset:
  360. raise ValueError("Dataset not found")
  361. if not user:
  362. raise ValueError("User not found")
  363. if dataset.permission == DatasetPermissionEnum.ONLY_ME:
  364. if dataset.created_by != user.id:
  365. raise NoPermissionError("You do not have permission to access this dataset.")
  366. elif dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM:
  367. if not any(
  368. dp.dataset_id == dataset.id for dp in DatasetPermission.query.filter_by(account_id=user.id).all()
  369. ):
  370. raise NoPermissionError("You do not have permission to access this dataset.")
  371. @staticmethod
  372. def get_dataset_queries(dataset_id: str, page: int, per_page: int):
  373. dataset_queries = (
  374. DatasetQuery.query.filter_by(dataset_id=dataset_id)
  375. .order_by(db.desc(DatasetQuery.created_at))
  376. .paginate(page=page, per_page=per_page, max_per_page=100, error_out=False)
  377. )
  378. return dataset_queries.items, dataset_queries.total
  379. @staticmethod
  380. def get_related_apps(dataset_id: str):
  381. return (
  382. AppDatasetJoin.query.filter(AppDatasetJoin.dataset_id == dataset_id)
  383. .order_by(db.desc(AppDatasetJoin.created_at))
  384. .all()
  385. )
  386. @staticmethod
  387. def get_dataset_auto_disable_logs(dataset_id: str) -> dict:
  388. # get recent 30 days auto disable logs
  389. start_date = datetime.datetime.now() - datetime.timedelta(days=30)
  390. dataset_auto_disable_logs = DatasetAutoDisableLog.query.filter(
  391. DatasetAutoDisableLog.dataset_id == dataset_id,
  392. DatasetAutoDisableLog.created_at >= start_date,
  393. ).all()
  394. if dataset_auto_disable_logs:
  395. return {
  396. "document_ids": [log.document_id for log in dataset_auto_disable_logs],
  397. "count": len(dataset_auto_disable_logs),
  398. }
  399. return {
  400. "document_ids": [],
  401. "count": 0,
  402. }
  403. class DocumentService:
  404. DEFAULT_RULES = {
  405. "mode": "custom",
  406. "rules": {
  407. "pre_processing_rules": [
  408. {"id": "remove_extra_spaces", "enabled": True},
  409. {"id": "remove_urls_emails", "enabled": False},
  410. ],
  411. "segmentation": {"delimiter": "\n", "max_tokens": 500, "chunk_overlap": 50},
  412. },
  413. "limits": {
  414. "indexing_max_segmentation_tokens_length": dify_config.INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH,
  415. },
  416. }
  417. DOCUMENT_METADATA_SCHEMA = {
  418. "book": {
  419. "title": str,
  420. "language": str,
  421. "author": str,
  422. "publisher": str,
  423. "publication_date": str,
  424. "isbn": str,
  425. "category": str,
  426. },
  427. "web_page": {
  428. "title": str,
  429. "url": str,
  430. "language": str,
  431. "publish_date": str,
  432. "author/publisher": str,
  433. "topic/keywords": str,
  434. "description": str,
  435. },
  436. "paper": {
  437. "title": str,
  438. "language": str,
  439. "author": str,
  440. "publish_date": str,
  441. "journal/conference_name": str,
  442. "volume/issue/page_numbers": str,
  443. "doi": str,
  444. "topic/keywords": str,
  445. "abstract": str,
  446. },
  447. "social_media_post": {
  448. "platform": str,
  449. "author/username": str,
  450. "publish_date": str,
  451. "post_url": str,
  452. "topic/tags": str,
  453. },
  454. "wikipedia_entry": {
  455. "title": str,
  456. "language": str,
  457. "web_page_url": str,
  458. "last_edit_date": str,
  459. "editor/contributor": str,
  460. "summary/introduction": str,
  461. },
  462. "personal_document": {
  463. "title": str,
  464. "author": str,
  465. "creation_date": str,
  466. "last_modified_date": str,
  467. "document_type": str,
  468. "tags/category": str,
  469. },
  470. "business_document": {
  471. "title": str,
  472. "author": str,
  473. "creation_date": str,
  474. "last_modified_date": str,
  475. "document_type": str,
  476. "department/team": str,
  477. },
  478. "im_chat_log": {
  479. "chat_platform": str,
  480. "chat_participants/group_name": str,
  481. "start_date": str,
  482. "end_date": str,
  483. "summary": str,
  484. },
  485. "synced_from_notion": {
  486. "title": str,
  487. "language": str,
  488. "author/creator": str,
  489. "creation_date": str,
  490. "last_modified_date": str,
  491. "notion_page_link": str,
  492. "category/tags": str,
  493. "description": str,
  494. },
  495. "synced_from_github": {
  496. "repository_name": str,
  497. "repository_description": str,
  498. "repository_owner/organization": str,
  499. "code_filename": str,
  500. "code_file_path": str,
  501. "programming_language": str,
  502. "github_link": str,
  503. "open_source_license": str,
  504. "commit_date": str,
  505. "commit_author": str,
  506. },
  507. "others": dict,
  508. }
  509. @staticmethod
  510. def get_document(dataset_id: str, document_id: Optional[str] = None) -> Optional[Document]:
  511. if document_id:
  512. document = (
  513. db.session.query(Document).filter(Document.id == document_id, Document.dataset_id == dataset_id).first()
  514. )
  515. return document
  516. else:
  517. return None
  518. @staticmethod
  519. def get_document_by_id(document_id: str) -> Optional[Document]:
  520. document = db.session.query(Document).filter(Document.id == document_id).first()
  521. return document
  522. @staticmethod
  523. def get_document_by_dataset_id(dataset_id: str) -> list[Document]:
  524. documents = db.session.query(Document).filter(Document.dataset_id == dataset_id, Document.enabled == True).all()
  525. return documents
  526. @staticmethod
  527. def get_error_documents_by_dataset_id(dataset_id: str) -> list[Document]:
  528. documents = (
  529. db.session.query(Document)
  530. .filter(Document.dataset_id == dataset_id, Document.indexing_status.in_(["error", "paused"]))
  531. .all()
  532. )
  533. return documents
  534. @staticmethod
  535. def get_batch_documents(dataset_id: str, batch: str) -> list[Document]:
  536. documents = (
  537. db.session.query(Document)
  538. .filter(
  539. Document.batch == batch,
  540. Document.dataset_id == dataset_id,
  541. Document.tenant_id == current_user.current_tenant_id,
  542. )
  543. .all()
  544. )
  545. return documents
  546. @staticmethod
  547. def get_document_file_detail(file_id: str):
  548. file_detail = db.session.query(UploadFile).filter(UploadFile.id == file_id).one_or_none()
  549. return file_detail
  550. @staticmethod
  551. def check_archived(document):
  552. if document.archived:
  553. return True
  554. else:
  555. return False
  556. @staticmethod
  557. def delete_document(document):
  558. # trigger document_was_deleted signal
  559. file_id = None
  560. if document.data_source_type == "upload_file":
  561. if document.data_source_info:
  562. data_source_info = document.data_source_info_dict
  563. if data_source_info and "upload_file_id" in data_source_info:
  564. file_id = data_source_info["upload_file_id"]
  565. document_was_deleted.send(
  566. document.id, dataset_id=document.dataset_id, doc_form=document.doc_form, file_id=file_id
  567. )
  568. db.session.delete(document)
  569. db.session.commit()
  570. @staticmethod
  571. def delete_documents(dataset: Dataset, document_ids: list[str]):
  572. documents = db.session.query(Document).filter(Document.id.in_(document_ids)).all()
  573. file_ids = [
  574. document.data_source_info_dict["upload_file_id"]
  575. for document in documents
  576. if document.data_source_type == "upload_file"
  577. ]
  578. batch_clean_document_task.delay(document_ids, dataset.id, dataset.doc_form, file_ids)
  579. for document in documents:
  580. db.session.delete(document)
  581. db.session.commit()
  582. @staticmethod
  583. def rename_document(dataset_id: str, document_id: str, name: str) -> Document:
  584. dataset = DatasetService.get_dataset(dataset_id)
  585. if not dataset:
  586. raise ValueError("Dataset not found.")
  587. document = DocumentService.get_document(dataset_id, document_id)
  588. if not document:
  589. raise ValueError("Document not found.")
  590. if document.tenant_id != current_user.current_tenant_id:
  591. raise ValueError("No permission.")
  592. document.name = name
  593. db.session.add(document)
  594. db.session.commit()
  595. return document
  596. @staticmethod
  597. def pause_document(document):
  598. if document.indexing_status not in {"waiting", "parsing", "cleaning", "splitting", "indexing"}:
  599. raise DocumentIndexingError()
  600. # update document to be paused
  601. document.is_paused = True
  602. document.paused_by = current_user.id
  603. document.paused_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  604. db.session.add(document)
  605. db.session.commit()
  606. # set document paused flag
  607. indexing_cache_key = "document_{}_is_paused".format(document.id)
  608. redis_client.setnx(indexing_cache_key, "True")
  609. @staticmethod
  610. def recover_document(document):
  611. if not document.is_paused:
  612. raise DocumentIndexingError()
  613. # update document to be recover
  614. document.is_paused = False
  615. document.paused_by = None
  616. document.paused_at = None
  617. db.session.add(document)
  618. db.session.commit()
  619. # delete paused flag
  620. indexing_cache_key = "document_{}_is_paused".format(document.id)
  621. redis_client.delete(indexing_cache_key)
  622. # trigger async task
  623. recover_document_indexing_task.delay(document.dataset_id, document.id)
  624. @staticmethod
  625. def retry_document(dataset_id: str, documents: list[Document]):
  626. for document in documents:
  627. # add retry flag
  628. retry_indexing_cache_key = "document_{}_is_retried".format(document.id)
  629. cache_result = redis_client.get(retry_indexing_cache_key)
  630. if cache_result is not None:
  631. raise ValueError("Document is being retried, please try again later")
  632. # retry document indexing
  633. document.indexing_status = "waiting"
  634. db.session.add(document)
  635. db.session.commit()
  636. redis_client.setex(retry_indexing_cache_key, 600, 1)
  637. # trigger async task
  638. document_ids = [document.id for document in documents]
  639. retry_document_indexing_task.delay(dataset_id, document_ids)
  640. @staticmethod
  641. def sync_website_document(dataset_id: str, document: Document):
  642. # add sync flag
  643. sync_indexing_cache_key = "document_{}_is_sync".format(document.id)
  644. cache_result = redis_client.get(sync_indexing_cache_key)
  645. if cache_result is not None:
  646. raise ValueError("Document is being synced, please try again later")
  647. # sync document indexing
  648. document.indexing_status = "waiting"
  649. data_source_info = document.data_source_info_dict
  650. data_source_info["mode"] = "scrape"
  651. document.data_source_info = json.dumps(data_source_info, ensure_ascii=False)
  652. db.session.add(document)
  653. db.session.commit()
  654. redis_client.setex(sync_indexing_cache_key, 600, 1)
  655. sync_website_document_indexing_task.delay(dataset_id, document.id)
  656. @staticmethod
  657. def get_documents_position(dataset_id):
  658. document = Document.query.filter_by(dataset_id=dataset_id).order_by(Document.position.desc()).first()
  659. if document:
  660. return document.position + 1
  661. else:
  662. return 1
  663. @staticmethod
  664. def save_document_with_dataset_id(
  665. dataset: Dataset,
  666. knowledge_config: KnowledgeConfig,
  667. account: Account | Any,
  668. dataset_process_rule: Optional[DatasetProcessRule] = None,
  669. created_from: str = "web",
  670. ):
  671. # check document limit
  672. features = FeatureService.get_features(current_user.current_tenant_id)
  673. if features.billing.enabled:
  674. if not knowledge_config.original_document_id:
  675. count = 0
  676. if knowledge_config.data_source:
  677. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  678. upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  679. count = len(upload_file_list)
  680. elif knowledge_config.data_source.info_list.data_source_type == "notion_import":
  681. notion_info_list = knowledge_config.data_source.info_list.notion_info_list
  682. for notion_info in notion_info_list: # type: ignore
  683. count = count + len(notion_info.pages)
  684. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  685. website_info = knowledge_config.data_source.info_list.website_info_list
  686. count = len(website_info.urls) # type: ignore
  687. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  688. if count > batch_upload_limit:
  689. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  690. DocumentService.check_documents_upload_quota(count, features)
  691. # if dataset is empty, update dataset data_source_type
  692. if not dataset.data_source_type:
  693. dataset.data_source_type = knowledge_config.data_source.info_list.data_source_type # type: ignore
  694. if not dataset.indexing_technique:
  695. if knowledge_config.indexing_technique not in Dataset.INDEXING_TECHNIQUE_LIST:
  696. raise ValueError("Indexing technique is invalid")
  697. dataset.indexing_technique = knowledge_config.indexing_technique
  698. if knowledge_config.indexing_technique == "high_quality":
  699. model_manager = ModelManager()
  700. embedding_model = model_manager.get_default_model_instance(
  701. tenant_id=current_user.current_tenant_id, model_type=ModelType.TEXT_EMBEDDING
  702. )
  703. dataset.embedding_model = embedding_model.model
  704. dataset.embedding_model_provider = embedding_model.provider
  705. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  706. embedding_model.provider, embedding_model.model
  707. )
  708. dataset.collection_binding_id = dataset_collection_binding.id
  709. if not dataset.retrieval_model:
  710. default_retrieval_model = {
  711. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  712. "reranking_enable": False,
  713. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  714. "top_k": 2,
  715. "score_threshold_enabled": False,
  716. }
  717. dataset.retrieval_model = knowledge_config.retrieval_model.model_dump() or default_retrieval_model # type: ignore
  718. documents = []
  719. if knowledge_config.original_document_id:
  720. document = DocumentService.update_document_with_dataset_id(dataset, knowledge_config, account)
  721. documents.append(document)
  722. batch = document.batch
  723. else:
  724. batch = time.strftime("%Y%m%d%H%M%S") + str(random.randint(100000, 999999))
  725. # save process rule
  726. if not dataset_process_rule:
  727. process_rule = knowledge_config.process_rule
  728. if process_rule:
  729. if process_rule.mode in ("custom", "hierarchical"):
  730. dataset_process_rule = DatasetProcessRule(
  731. dataset_id=dataset.id,
  732. mode=process_rule.mode,
  733. rules=process_rule.rules.model_dump_json() if process_rule.rules else None,
  734. created_by=account.id,
  735. )
  736. elif process_rule.mode == "automatic":
  737. dataset_process_rule = DatasetProcessRule(
  738. dataset_id=dataset.id,
  739. mode=process_rule.mode,
  740. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  741. created_by=account.id,
  742. )
  743. else:
  744. logging.warn(
  745. f"Invalid process rule mode: {process_rule.mode}, can not find dataset process rule"
  746. )
  747. return
  748. db.session.add(dataset_process_rule)
  749. db.session.commit()
  750. lock_name = "add_document_lock_dataset_id_{}".format(dataset.id)
  751. with redis_client.lock(lock_name, timeout=600):
  752. position = DocumentService.get_documents_position(dataset.id)
  753. document_ids = []
  754. duplicate_document_ids = []
  755. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  756. upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  757. for file_id in upload_file_list:
  758. file = (
  759. db.session.query(UploadFile)
  760. .filter(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  761. .first()
  762. )
  763. # raise error if file not found
  764. if not file:
  765. raise FileNotExistsError()
  766. file_name = file.name
  767. data_source_info = {
  768. "upload_file_id": file_id,
  769. }
  770. # check duplicate
  771. if knowledge_config.duplicate:
  772. document = Document.query.filter_by(
  773. dataset_id=dataset.id,
  774. tenant_id=current_user.current_tenant_id,
  775. data_source_type="upload_file",
  776. enabled=True,
  777. name=file_name,
  778. ).first()
  779. if document:
  780. document.dataset_process_rule_id = dataset_process_rule.id # type: ignore
  781. document.updated_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
  782. document.created_from = created_from
  783. document.doc_form = knowledge_config.doc_form
  784. document.doc_language = knowledge_config.doc_language
  785. document.data_source_info = json.dumps(data_source_info)
  786. document.batch = batch
  787. document.indexing_status = "waiting"
  788. db.session.add(document)
  789. documents.append(document)
  790. duplicate_document_ids.append(document.id)
  791. continue
  792. document = DocumentService.build_document(
  793. dataset,
  794. dataset_process_rule.id, # type: ignore
  795. knowledge_config.data_source.info_list.data_source_type,
  796. knowledge_config.doc_form,
  797. knowledge_config.doc_language,
  798. data_source_info,
  799. created_from,
  800. position,
  801. account,
  802. file_name,
  803. batch,
  804. )
  805. db.session.add(document)
  806. db.session.flush()
  807. document_ids.append(document.id)
  808. documents.append(document)
  809. position += 1
  810. elif knowledge_config.data_source.info_list.data_source_type == "notion_import":
  811. notion_info_list = knowledge_config.data_source.info_list.notion_info_list
  812. if not notion_info_list:
  813. raise ValueError("No notion info list found.")
  814. exist_page_ids = []
  815. exist_document = {}
  816. documents = Document.query.filter_by(
  817. dataset_id=dataset.id,
  818. tenant_id=current_user.current_tenant_id,
  819. data_source_type="notion_import",
  820. enabled=True,
  821. ).all()
  822. if documents:
  823. for document in documents:
  824. data_source_info = json.loads(document.data_source_info)
  825. exist_page_ids.append(data_source_info["notion_page_id"])
  826. exist_document[data_source_info["notion_page_id"]] = document.id
  827. for notion_info in notion_info_list:
  828. workspace_id = notion_info.workspace_id
  829. data_source_binding = DataSourceOauthBinding.query.filter(
  830. db.and_(
  831. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  832. DataSourceOauthBinding.provider == "notion",
  833. DataSourceOauthBinding.disabled == False,
  834. DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  835. )
  836. ).first()
  837. if not data_source_binding:
  838. raise ValueError("Data source binding not found.")
  839. for page in notion_info.pages:
  840. if page.page_id not in exist_page_ids:
  841. data_source_info = {
  842. "notion_workspace_id": workspace_id,
  843. "notion_page_id": page.page_id,
  844. "notion_page_icon": page.page_icon.model_dump() if page.page_icon else None,
  845. "type": page.type,
  846. }
  847. document = DocumentService.build_document(
  848. dataset,
  849. dataset_process_rule.id, # type: ignore
  850. knowledge_config.data_source.info_list.data_source_type,
  851. knowledge_config.doc_form,
  852. knowledge_config.doc_language,
  853. data_source_info,
  854. created_from,
  855. position,
  856. account,
  857. page.page_name,
  858. batch,
  859. )
  860. db.session.add(document)
  861. db.session.flush()
  862. document_ids.append(document.id)
  863. documents.append(document)
  864. position += 1
  865. else:
  866. exist_document.pop(page.page_id)
  867. # delete not selected documents
  868. if len(exist_document) > 0:
  869. clean_notion_document_task.delay(list(exist_document.values()), dataset.id)
  870. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  871. website_info = knowledge_config.data_source.info_list.website_info_list
  872. if not website_info:
  873. raise ValueError("No website info list found.")
  874. urls = website_info.urls
  875. for url in urls:
  876. data_source_info = {
  877. "url": url,
  878. "provider": website_info.provider,
  879. "job_id": website_info.job_id,
  880. "only_main_content": website_info.only_main_content,
  881. "mode": "crawl",
  882. }
  883. if len(url) > 255:
  884. document_name = url[:200] + "..."
  885. else:
  886. document_name = url
  887. document = DocumentService.build_document(
  888. dataset,
  889. dataset_process_rule.id, # type: ignore
  890. knowledge_config.data_source.info_list.data_source_type,
  891. knowledge_config.doc_form,
  892. knowledge_config.doc_language,
  893. data_source_info,
  894. created_from,
  895. position,
  896. account,
  897. document_name,
  898. batch,
  899. )
  900. db.session.add(document)
  901. db.session.flush()
  902. document_ids.append(document.id)
  903. documents.append(document)
  904. position += 1
  905. db.session.commit()
  906. # trigger async task
  907. if document_ids:
  908. document_indexing_task.delay(dataset.id, document_ids)
  909. if duplicate_document_ids:
  910. duplicate_document_indexing_task.delay(dataset.id, duplicate_document_ids)
  911. return documents, batch
  912. @staticmethod
  913. def check_documents_upload_quota(count: int, features: FeatureModel):
  914. can_upload_size = features.documents_upload_quota.limit - features.documents_upload_quota.size
  915. if count > can_upload_size:
  916. raise ValueError(
  917. f"You have reached the limit of your subscription. Only {can_upload_size} documents can be uploaded."
  918. )
  919. @staticmethod
  920. def build_document(
  921. dataset: Dataset,
  922. process_rule_id: str,
  923. data_source_type: str,
  924. document_form: str,
  925. document_language: str,
  926. data_source_info: dict,
  927. created_from: str,
  928. position: int,
  929. account: Account,
  930. name: str,
  931. batch: str,
  932. ):
  933. document = Document(
  934. tenant_id=dataset.tenant_id,
  935. dataset_id=dataset.id,
  936. position=position,
  937. data_source_type=data_source_type,
  938. data_source_info=json.dumps(data_source_info),
  939. dataset_process_rule_id=process_rule_id,
  940. batch=batch,
  941. name=name,
  942. created_from=created_from,
  943. created_by=account.id,
  944. doc_form=document_form,
  945. doc_language=document_language,
  946. )
  947. return document
  948. @staticmethod
  949. def get_tenant_documents_count():
  950. documents_count = Document.query.filter(
  951. Document.completed_at.isnot(None),
  952. Document.enabled == True,
  953. Document.archived == False,
  954. Document.tenant_id == current_user.current_tenant_id,
  955. ).count()
  956. return documents_count
  957. @staticmethod
  958. def update_document_with_dataset_id(
  959. dataset: Dataset,
  960. document_data: KnowledgeConfig,
  961. account: Account,
  962. dataset_process_rule: Optional[DatasetProcessRule] = None,
  963. created_from: str = "web",
  964. ):
  965. DatasetService.check_dataset_model_setting(dataset)
  966. document = DocumentService.get_document(dataset.id, document_data.original_document_id)
  967. if document is None:
  968. raise NotFound("Document not found")
  969. if document.display_status != "available":
  970. raise ValueError("Document is not available")
  971. # save process rule
  972. if document_data.process_rule:
  973. process_rule = document_data.process_rule
  974. if process_rule.mode in {"custom", "hierarchical"}:
  975. dataset_process_rule = DatasetProcessRule(
  976. dataset_id=dataset.id,
  977. mode=process_rule.mode,
  978. rules=process_rule.rules.model_dump_json() if process_rule.rules else None,
  979. created_by=account.id,
  980. )
  981. elif process_rule.mode == "automatic":
  982. dataset_process_rule = DatasetProcessRule(
  983. dataset_id=dataset.id,
  984. mode=process_rule.mode,
  985. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  986. created_by=account.id,
  987. )
  988. if dataset_process_rule is not None:
  989. db.session.add(dataset_process_rule)
  990. db.session.commit()
  991. document.dataset_process_rule_id = dataset_process_rule.id
  992. # update document data source
  993. if document_data.data_source:
  994. file_name = ""
  995. data_source_info = {}
  996. if document_data.data_source.info_list.data_source_type == "upload_file":
  997. if not document_data.data_source.info_list.file_info_list:
  998. raise ValueError("No file info list found.")
  999. upload_file_list = document_data.data_source.info_list.file_info_list.file_ids
  1000. for file_id in upload_file_list:
  1001. file = (
  1002. db.session.query(UploadFile)
  1003. .filter(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  1004. .first()
  1005. )
  1006. # raise error if file not found
  1007. if not file:
  1008. raise FileNotExistsError()
  1009. file_name = file.name
  1010. data_source_info = {
  1011. "upload_file_id": file_id,
  1012. }
  1013. elif document_data.data_source.info_list.data_source_type == "notion_import":
  1014. if not document_data.data_source.info_list.notion_info_list:
  1015. raise ValueError("No notion info list found.")
  1016. notion_info_list = document_data.data_source.info_list.notion_info_list
  1017. for notion_info in notion_info_list:
  1018. workspace_id = notion_info.workspace_id
  1019. data_source_binding = DataSourceOauthBinding.query.filter(
  1020. db.and_(
  1021. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  1022. DataSourceOauthBinding.provider == "notion",
  1023. DataSourceOauthBinding.disabled == False,
  1024. DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  1025. )
  1026. ).first()
  1027. if not data_source_binding:
  1028. raise ValueError("Data source binding not found.")
  1029. for page in notion_info.pages:
  1030. data_source_info = {
  1031. "notion_workspace_id": workspace_id,
  1032. "notion_page_id": page.page_id,
  1033. "notion_page_icon": page.page_icon.model_dump() if page.page_icon else None, # type: ignore
  1034. "type": page.type,
  1035. }
  1036. elif document_data.data_source.info_list.data_source_type == "website_crawl":
  1037. website_info = document_data.data_source.info_list.website_info_list
  1038. if website_info:
  1039. urls = website_info.urls
  1040. for url in urls:
  1041. data_source_info = {
  1042. "url": url,
  1043. "provider": website_info.provider,
  1044. "job_id": website_info.job_id,
  1045. "only_main_content": website_info.only_main_content, # type: ignore
  1046. "mode": "crawl",
  1047. }
  1048. document.data_source_type = document_data.data_source.info_list.data_source_type
  1049. document.data_source_info = json.dumps(data_source_info)
  1050. document.name = file_name
  1051. # update document name
  1052. if document_data.name:
  1053. document.name = document_data.name
  1054. # update document to be waiting
  1055. document.indexing_status = "waiting"
  1056. document.completed_at = None
  1057. document.processing_started_at = None
  1058. document.parsing_completed_at = None
  1059. document.cleaning_completed_at = None
  1060. document.splitting_completed_at = None
  1061. document.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1062. document.created_from = created_from
  1063. document.doc_form = document_data.doc_form
  1064. db.session.add(document)
  1065. db.session.commit()
  1066. # update document segment
  1067. update_params = {DocumentSegment.status: "re_segment"}
  1068. DocumentSegment.query.filter_by(document_id=document.id).update(update_params)
  1069. db.session.commit()
  1070. # trigger async task
  1071. document_indexing_update_task.delay(document.dataset_id, document.id)
  1072. return document
  1073. @staticmethod
  1074. def save_document_without_dataset_id(tenant_id: str, knowledge_config: KnowledgeConfig, account: Account):
  1075. features = FeatureService.get_features(current_user.current_tenant_id)
  1076. if features.billing.enabled:
  1077. count = 0
  1078. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  1079. upload_file_list = (
  1080. knowledge_config.data_source.info_list.file_info_list.file_ids
  1081. if knowledge_config.data_source.info_list.file_info_list
  1082. else []
  1083. )
  1084. count = len(upload_file_list)
  1085. elif knowledge_config.data_source.info_list.data_source_type == "notion_import":
  1086. notion_info_list = knowledge_config.data_source.info_list.notion_info_list
  1087. if notion_info_list:
  1088. for notion_info in notion_info_list:
  1089. count = count + len(notion_info.pages)
  1090. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  1091. website_info = knowledge_config.data_source.info_list.website_info_list
  1092. if website_info:
  1093. count = len(website_info.urls)
  1094. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  1095. if count > batch_upload_limit:
  1096. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  1097. DocumentService.check_documents_upload_quota(count, features)
  1098. dataset_collection_binding_id = None
  1099. retrieval_model = None
  1100. if knowledge_config.indexing_technique == "high_quality":
  1101. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  1102. knowledge_config.embedding_model_provider, # type: ignore
  1103. knowledge_config.embedding_model, # type: ignore
  1104. )
  1105. dataset_collection_binding_id = dataset_collection_binding.id
  1106. if knowledge_config.retrieval_model:
  1107. retrieval_model = knowledge_config.retrieval_model
  1108. else:
  1109. retrieval_model = RetrievalModel(
  1110. search_method=RetrievalMethod.SEMANTIC_SEARCH.value,
  1111. reranking_enable=False,
  1112. reranking_model=RerankingModel(reranking_provider_name="", reranking_model_name=""),
  1113. top_k=2,
  1114. score_threshold_enabled=False,
  1115. )
  1116. # save dataset
  1117. dataset = Dataset(
  1118. tenant_id=tenant_id,
  1119. name="",
  1120. data_source_type=knowledge_config.data_source.info_list.data_source_type,
  1121. indexing_technique=knowledge_config.indexing_technique,
  1122. created_by=account.id,
  1123. embedding_model=knowledge_config.embedding_model,
  1124. embedding_model_provider=knowledge_config.embedding_model_provider,
  1125. collection_binding_id=dataset_collection_binding_id,
  1126. retrieval_model=retrieval_model.model_dump() if retrieval_model else None,
  1127. )
  1128. db.session.add(dataset) # type: ignore
  1129. db.session.flush()
  1130. documents, batch = DocumentService.save_document_with_dataset_id(dataset, knowledge_config, account)
  1131. cut_length = 18
  1132. cut_name = documents[0].name[:cut_length]
  1133. dataset.name = cut_name + "..."
  1134. dataset.description = "useful for when you want to answer queries about the " + documents[0].name
  1135. db.session.commit()
  1136. return dataset, documents, batch
  1137. @classmethod
  1138. def document_create_args_validate(cls, knowledge_config: KnowledgeConfig):
  1139. if not knowledge_config.data_source and not knowledge_config.process_rule:
  1140. raise ValueError("Data source or Process rule is required")
  1141. else:
  1142. if knowledge_config.data_source:
  1143. DocumentService.data_source_args_validate(knowledge_config)
  1144. if knowledge_config.process_rule:
  1145. DocumentService.process_rule_args_validate(knowledge_config)
  1146. @classmethod
  1147. def data_source_args_validate(cls, knowledge_config: KnowledgeConfig):
  1148. if not knowledge_config.data_source:
  1149. raise ValueError("Data source is required")
  1150. if knowledge_config.data_source.info_list.data_source_type not in Document.DATA_SOURCES:
  1151. raise ValueError("Data source type is invalid")
  1152. if not knowledge_config.data_source.info_list:
  1153. raise ValueError("Data source info is required")
  1154. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  1155. if not knowledge_config.data_source.info_list.file_info_list:
  1156. raise ValueError("File source info is required")
  1157. if knowledge_config.data_source.info_list.data_source_type == "notion_import":
  1158. if not knowledge_config.data_source.info_list.notion_info_list:
  1159. raise ValueError("Notion source info is required")
  1160. if knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  1161. if not knowledge_config.data_source.info_list.website_info_list:
  1162. raise ValueError("Website source info is required")
  1163. @classmethod
  1164. def process_rule_args_validate(cls, knowledge_config: KnowledgeConfig):
  1165. if not knowledge_config.process_rule:
  1166. raise ValueError("Process rule is required")
  1167. if not knowledge_config.process_rule.mode:
  1168. raise ValueError("Process rule mode is required")
  1169. if knowledge_config.process_rule.mode not in DatasetProcessRule.MODES:
  1170. raise ValueError("Process rule mode is invalid")
  1171. if knowledge_config.process_rule.mode == "automatic":
  1172. knowledge_config.process_rule.rules = None
  1173. else:
  1174. if not knowledge_config.process_rule.rules:
  1175. raise ValueError("Process rule rules is required")
  1176. if knowledge_config.process_rule.rules.pre_processing_rules is None:
  1177. raise ValueError("Process rule pre_processing_rules is required")
  1178. unique_pre_processing_rule_dicts = {}
  1179. for pre_processing_rule in knowledge_config.process_rule.rules.pre_processing_rules:
  1180. if not pre_processing_rule.id:
  1181. raise ValueError("Process rule pre_processing_rules id is required")
  1182. if not isinstance(pre_processing_rule.enabled, bool):
  1183. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  1184. unique_pre_processing_rule_dicts[pre_processing_rule.id] = pre_processing_rule
  1185. knowledge_config.process_rule.rules.pre_processing_rules = list(unique_pre_processing_rule_dicts.values())
  1186. if not knowledge_config.process_rule.rules.segmentation:
  1187. raise ValueError("Process rule segmentation is required")
  1188. if not knowledge_config.process_rule.rules.segmentation.separator:
  1189. raise ValueError("Process rule segmentation separator is required")
  1190. if not isinstance(knowledge_config.process_rule.rules.segmentation.separator, str):
  1191. raise ValueError("Process rule segmentation separator is invalid")
  1192. if not (
  1193. knowledge_config.process_rule.mode == "hierarchical"
  1194. and knowledge_config.process_rule.rules.parent_mode == "full-doc"
  1195. ):
  1196. if not knowledge_config.process_rule.rules.segmentation.max_tokens:
  1197. raise ValueError("Process rule segmentation max_tokens is required")
  1198. if not isinstance(knowledge_config.process_rule.rules.segmentation.max_tokens, int):
  1199. raise ValueError("Process rule segmentation max_tokens is invalid")
  1200. @classmethod
  1201. def estimate_args_validate(cls, args: dict):
  1202. if "info_list" not in args or not args["info_list"]:
  1203. raise ValueError("Data source info is required")
  1204. if not isinstance(args["info_list"], dict):
  1205. raise ValueError("Data info is invalid")
  1206. if "process_rule" not in args or not args["process_rule"]:
  1207. raise ValueError("Process rule is required")
  1208. if not isinstance(args["process_rule"], dict):
  1209. raise ValueError("Process rule is invalid")
  1210. if "mode" not in args["process_rule"] or not args["process_rule"]["mode"]:
  1211. raise ValueError("Process rule mode is required")
  1212. if args["process_rule"]["mode"] not in DatasetProcessRule.MODES:
  1213. raise ValueError("Process rule mode is invalid")
  1214. if args["process_rule"]["mode"] == "automatic":
  1215. args["process_rule"]["rules"] = {}
  1216. else:
  1217. if "rules" not in args["process_rule"] or not args["process_rule"]["rules"]:
  1218. raise ValueError("Process rule rules is required")
  1219. if not isinstance(args["process_rule"]["rules"], dict):
  1220. raise ValueError("Process rule rules is invalid")
  1221. if (
  1222. "pre_processing_rules" not in args["process_rule"]["rules"]
  1223. or args["process_rule"]["rules"]["pre_processing_rules"] is None
  1224. ):
  1225. raise ValueError("Process rule pre_processing_rules is required")
  1226. if not isinstance(args["process_rule"]["rules"]["pre_processing_rules"], list):
  1227. raise ValueError("Process rule pre_processing_rules is invalid")
  1228. unique_pre_processing_rule_dicts = {}
  1229. for pre_processing_rule in args["process_rule"]["rules"]["pre_processing_rules"]:
  1230. if "id" not in pre_processing_rule or not pre_processing_rule["id"]:
  1231. raise ValueError("Process rule pre_processing_rules id is required")
  1232. if pre_processing_rule["id"] not in DatasetProcessRule.PRE_PROCESSING_RULES:
  1233. raise ValueError("Process rule pre_processing_rules id is invalid")
  1234. if "enabled" not in pre_processing_rule or pre_processing_rule["enabled"] is None:
  1235. raise ValueError("Process rule pre_processing_rules enabled is required")
  1236. if not isinstance(pre_processing_rule["enabled"], bool):
  1237. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  1238. unique_pre_processing_rule_dicts[pre_processing_rule["id"]] = pre_processing_rule
  1239. args["process_rule"]["rules"]["pre_processing_rules"] = list(unique_pre_processing_rule_dicts.values())
  1240. if (
  1241. "segmentation" not in args["process_rule"]["rules"]
  1242. or args["process_rule"]["rules"]["segmentation"] is None
  1243. ):
  1244. raise ValueError("Process rule segmentation is required")
  1245. if not isinstance(args["process_rule"]["rules"]["segmentation"], dict):
  1246. raise ValueError("Process rule segmentation is invalid")
  1247. if (
  1248. "separator" not in args["process_rule"]["rules"]["segmentation"]
  1249. or not args["process_rule"]["rules"]["segmentation"]["separator"]
  1250. ):
  1251. raise ValueError("Process rule segmentation separator is required")
  1252. if not isinstance(args["process_rule"]["rules"]["segmentation"]["separator"], str):
  1253. raise ValueError("Process rule segmentation separator is invalid")
  1254. if (
  1255. "max_tokens" not in args["process_rule"]["rules"]["segmentation"]
  1256. or not args["process_rule"]["rules"]["segmentation"]["max_tokens"]
  1257. ):
  1258. raise ValueError("Process rule segmentation max_tokens is required")
  1259. if not isinstance(args["process_rule"]["rules"]["segmentation"]["max_tokens"], int):
  1260. raise ValueError("Process rule segmentation max_tokens is invalid")
  1261. class SegmentService:
  1262. @classmethod
  1263. def segment_create_args_validate(cls, args: dict, document: Document):
  1264. if document.doc_form == "qa_model":
  1265. if "answer" not in args or not args["answer"]:
  1266. raise ValueError("Answer is required")
  1267. if not args["answer"].strip():
  1268. raise ValueError("Answer is empty")
  1269. if "content" not in args or not args["content"] or not args["content"].strip():
  1270. raise ValueError("Content is empty")
  1271. @classmethod
  1272. def create_segment(cls, args: dict, document: Document, dataset: Dataset):
  1273. content = args["content"]
  1274. doc_id = str(uuid.uuid4())
  1275. segment_hash = helper.generate_text_hash(content)
  1276. tokens = 0
  1277. if dataset.indexing_technique == "high_quality":
  1278. model_manager = ModelManager()
  1279. embedding_model = model_manager.get_model_instance(
  1280. tenant_id=current_user.current_tenant_id,
  1281. provider=dataset.embedding_model_provider,
  1282. model_type=ModelType.TEXT_EMBEDDING,
  1283. model=dataset.embedding_model,
  1284. )
  1285. # calc embedding use tokens
  1286. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])
  1287. lock_name = "add_segment_lock_document_id_{}".format(document.id)
  1288. with redis_client.lock(lock_name, timeout=600):
  1289. max_position = (
  1290. db.session.query(func.max(DocumentSegment.position))
  1291. .filter(DocumentSegment.document_id == document.id)
  1292. .scalar()
  1293. )
  1294. segment_document = DocumentSegment(
  1295. tenant_id=current_user.current_tenant_id,
  1296. dataset_id=document.dataset_id,
  1297. document_id=document.id,
  1298. index_node_id=doc_id,
  1299. index_node_hash=segment_hash,
  1300. position=max_position + 1 if max_position else 1,
  1301. content=content,
  1302. word_count=len(content),
  1303. tokens=tokens,
  1304. status="completed",
  1305. indexing_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1306. completed_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1307. created_by=current_user.id,
  1308. )
  1309. if document.doc_form == "qa_model":
  1310. segment_document.word_count += len(args["answer"])
  1311. segment_document.answer = args["answer"]
  1312. db.session.add(segment_document)
  1313. # update document word count
  1314. document.word_count += segment_document.word_count
  1315. db.session.add(document)
  1316. db.session.commit()
  1317. # save vector index
  1318. try:
  1319. VectorService.create_segments_vector([args["keywords"]], [segment_document], dataset, document.doc_form)
  1320. except Exception as e:
  1321. logging.exception("create segment index failed")
  1322. segment_document.enabled = False
  1323. segment_document.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1324. segment_document.status = "error"
  1325. segment_document.error = str(e)
  1326. db.session.commit()
  1327. segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment_document.id).first()
  1328. return segment
  1329. @classmethod
  1330. def multi_create_segment(cls, segments: list, document: Document, dataset: Dataset):
  1331. lock_name = "multi_add_segment_lock_document_id_{}".format(document.id)
  1332. increment_word_count = 0
  1333. with redis_client.lock(lock_name, timeout=600):
  1334. embedding_model = None
  1335. if dataset.indexing_technique == "high_quality":
  1336. model_manager = ModelManager()
  1337. embedding_model = model_manager.get_model_instance(
  1338. tenant_id=current_user.current_tenant_id,
  1339. provider=dataset.embedding_model_provider,
  1340. model_type=ModelType.TEXT_EMBEDDING,
  1341. model=dataset.embedding_model,
  1342. )
  1343. max_position = (
  1344. db.session.query(func.max(DocumentSegment.position))
  1345. .filter(DocumentSegment.document_id == document.id)
  1346. .scalar()
  1347. )
  1348. pre_segment_data_list = []
  1349. segment_data_list = []
  1350. keywords_list = []
  1351. position = max_position + 1 if max_position else 1
  1352. for segment_item in segments:
  1353. content = segment_item["content"]
  1354. doc_id = str(uuid.uuid4())
  1355. segment_hash = helper.generate_text_hash(content)
  1356. tokens = 0
  1357. if dataset.indexing_technique == "high_quality" and embedding_model:
  1358. # calc embedding use tokens
  1359. if document.doc_form == "qa_model":
  1360. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content + segment_item["answer"]])
  1361. else:
  1362. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])
  1363. segment_document = DocumentSegment(
  1364. tenant_id=current_user.current_tenant_id,
  1365. dataset_id=document.dataset_id,
  1366. document_id=document.id,
  1367. index_node_id=doc_id,
  1368. index_node_hash=segment_hash,
  1369. position=position,
  1370. content=content,
  1371. word_count=len(content),
  1372. tokens=tokens,
  1373. status="completed",
  1374. indexing_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1375. completed_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1376. created_by=current_user.id,
  1377. )
  1378. if document.doc_form == "qa_model":
  1379. segment_document.answer = segment_item["answer"]
  1380. segment_document.word_count += len(segment_item["answer"])
  1381. increment_word_count += segment_document.word_count
  1382. db.session.add(segment_document)
  1383. segment_data_list.append(segment_document)
  1384. position += 1
  1385. pre_segment_data_list.append(segment_document)
  1386. if "keywords" in segment_item:
  1387. keywords_list.append(segment_item["keywords"])
  1388. else:
  1389. keywords_list.append(None)
  1390. # update document word count
  1391. document.word_count += increment_word_count
  1392. db.session.add(document)
  1393. try:
  1394. # save vector index
  1395. VectorService.create_segments_vector(keywords_list, pre_segment_data_list, dataset, document.doc_form)
  1396. except Exception as e:
  1397. logging.exception("create segment index failed")
  1398. for segment_document in segment_data_list:
  1399. segment_document.enabled = False
  1400. segment_document.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1401. segment_document.status = "error"
  1402. segment_document.error = str(e)
  1403. db.session.commit()
  1404. return segment_data_list
  1405. @classmethod
  1406. def update_segment(cls, args: SegmentUpdateArgs, segment: DocumentSegment, document: Document, dataset: Dataset):
  1407. indexing_cache_key = "segment_{}_indexing".format(segment.id)
  1408. cache_result = redis_client.get(indexing_cache_key)
  1409. if cache_result is not None:
  1410. raise ValueError("Segment is indexing, please try again later")
  1411. if args.enabled is not None:
  1412. action = args.enabled
  1413. if segment.enabled != action:
  1414. if not action:
  1415. segment.enabled = action
  1416. segment.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1417. segment.disabled_by = current_user.id
  1418. db.session.add(segment)
  1419. db.session.commit()
  1420. # Set cache to prevent indexing the same segment multiple times
  1421. redis_client.setex(indexing_cache_key, 600, 1)
  1422. disable_segment_from_index_task.delay(segment.id)
  1423. return segment
  1424. if not segment.enabled:
  1425. if args.enabled is not None:
  1426. if not args.enabled:
  1427. raise ValueError("Can't update disabled segment")
  1428. else:
  1429. raise ValueError("Can't update disabled segment")
  1430. try:
  1431. word_count_change = segment.word_count
  1432. content = args.content or segment.content
  1433. if segment.content == content:
  1434. segment.word_count = len(content)
  1435. if document.doc_form == "qa_model":
  1436. segment.answer = args.answer
  1437. segment.word_count += len(args.answer) if args.answer else 0
  1438. word_count_change = segment.word_count - word_count_change
  1439. if args.keywords:
  1440. segment.keywords = args.keywords
  1441. segment.enabled = True
  1442. segment.disabled_at = None
  1443. segment.disabled_by = None
  1444. db.session.add(segment)
  1445. db.session.commit()
  1446. # update document word count
  1447. if word_count_change != 0:
  1448. document.word_count = max(0, document.word_count + word_count_change)
  1449. db.session.add(document)
  1450. # update segment index task
  1451. if args.enabled:
  1452. VectorService.create_segments_vector(
  1453. [args.keywords] if args.keywords else None,
  1454. [segment],
  1455. dataset,
  1456. document.doc_form,
  1457. )
  1458. if document.doc_form == IndexType.PARENT_CHILD_INDEX and args.regenerate_child_chunks:
  1459. # regenerate child chunks
  1460. # get embedding model instance
  1461. if dataset.indexing_technique == "high_quality":
  1462. # check embedding model setting
  1463. model_manager = ModelManager()
  1464. if dataset.embedding_model_provider:
  1465. embedding_model_instance = model_manager.get_model_instance(
  1466. tenant_id=dataset.tenant_id,
  1467. provider=dataset.embedding_model_provider,
  1468. model_type=ModelType.TEXT_EMBEDDING,
  1469. model=dataset.embedding_model,
  1470. )
  1471. else:
  1472. embedding_model_instance = model_manager.get_default_model_instance(
  1473. tenant_id=dataset.tenant_id,
  1474. model_type=ModelType.TEXT_EMBEDDING,
  1475. )
  1476. else:
  1477. raise ValueError("The knowledge base index technique is not high quality!")
  1478. # get the process rule
  1479. processing_rule = (
  1480. db.session.query(DatasetProcessRule)
  1481. .filter(DatasetProcessRule.id == document.dataset_process_rule_id)
  1482. .first()
  1483. )
  1484. if not processing_rule:
  1485. raise ValueError("No processing rule found.")
  1486. VectorService.generate_child_chunks(
  1487. segment, document, dataset, embedding_model_instance, processing_rule, True
  1488. )
  1489. else:
  1490. segment_hash = helper.generate_text_hash(content)
  1491. tokens = 0
  1492. if dataset.indexing_technique == "high_quality":
  1493. model_manager = ModelManager()
  1494. embedding_model = model_manager.get_model_instance(
  1495. tenant_id=current_user.current_tenant_id,
  1496. provider=dataset.embedding_model_provider,
  1497. model_type=ModelType.TEXT_EMBEDDING,
  1498. model=dataset.embedding_model,
  1499. )
  1500. # calc embedding use tokens
  1501. if document.doc_form == "qa_model":
  1502. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content + segment.answer])
  1503. else:
  1504. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])
  1505. segment.content = content
  1506. segment.index_node_hash = segment_hash
  1507. segment.word_count = len(content)
  1508. segment.tokens = tokens
  1509. segment.status = "completed"
  1510. segment.indexing_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1511. segment.completed_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1512. segment.updated_by = current_user.id
  1513. segment.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1514. segment.enabled = True
  1515. segment.disabled_at = None
  1516. segment.disabled_by = None
  1517. if document.doc_form == "qa_model":
  1518. segment.answer = args.answer
  1519. segment.word_count += len(args.answer) if args.answer else 0
  1520. word_count_change = segment.word_count - word_count_change
  1521. # update document word count
  1522. if word_count_change != 0:
  1523. document.word_count = max(0, document.word_count + word_count_change)
  1524. db.session.add(document)
  1525. db.session.add(segment)
  1526. db.session.commit()
  1527. if document.doc_form == IndexType.PARENT_CHILD_INDEX and args.regenerate_child_chunks:
  1528. # get embedding model instance
  1529. if dataset.indexing_technique == "high_quality":
  1530. # check embedding model setting
  1531. model_manager = ModelManager()
  1532. if dataset.embedding_model_provider:
  1533. embedding_model_instance = model_manager.get_model_instance(
  1534. tenant_id=dataset.tenant_id,
  1535. provider=dataset.embedding_model_provider,
  1536. model_type=ModelType.TEXT_EMBEDDING,
  1537. model=dataset.embedding_model,
  1538. )
  1539. else:
  1540. embedding_model_instance = model_manager.get_default_model_instance(
  1541. tenant_id=dataset.tenant_id,
  1542. model_type=ModelType.TEXT_EMBEDDING,
  1543. )
  1544. else:
  1545. raise ValueError("The knowledge base index technique is not high quality!")
  1546. # get the process rule
  1547. processing_rule = (
  1548. db.session.query(DatasetProcessRule)
  1549. .filter(DatasetProcessRule.id == document.dataset_process_rule_id)
  1550. .first()
  1551. )
  1552. if not processing_rule:
  1553. raise ValueError("No processing rule found.")
  1554. VectorService.generate_child_chunks(
  1555. segment, document, dataset, embedding_model_instance, processing_rule, True
  1556. )
  1557. elif document.doc_form in (IndexType.PARAGRAPH_INDEX, IndexType.QA_INDEX):
  1558. # update segment vector index
  1559. VectorService.update_segment_vector(args.keywords, segment, dataset)
  1560. except Exception as e:
  1561. logging.exception("update segment index failed")
  1562. segment.enabled = False
  1563. segment.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1564. segment.status = "error"
  1565. segment.error = str(e)
  1566. db.session.commit()
  1567. new_segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment.id).first()
  1568. return new_segment
  1569. @classmethod
  1570. def delete_segment(cls, segment: DocumentSegment, document: Document, dataset: Dataset):
  1571. indexing_cache_key = "segment_{}_delete_indexing".format(segment.id)
  1572. cache_result = redis_client.get(indexing_cache_key)
  1573. if cache_result is not None:
  1574. raise ValueError("Segment is deleting.")
  1575. # enabled segment need to delete index
  1576. if segment.enabled:
  1577. # send delete segment index task
  1578. redis_client.setex(indexing_cache_key, 600, 1)
  1579. delete_segment_from_index_task.delay([segment.index_node_id], dataset.id, document.id)
  1580. db.session.delete(segment)
  1581. # update document word count
  1582. document.word_count -= segment.word_count
  1583. db.session.add(document)
  1584. db.session.commit()
  1585. @classmethod
  1586. def delete_segments(cls, segment_ids: list, document: Document, dataset: Dataset):
  1587. index_node_ids = (
  1588. DocumentSegment.query.with_entities(DocumentSegment.index_node_id)
  1589. .filter(
  1590. DocumentSegment.id.in_(segment_ids),
  1591. DocumentSegment.dataset_id == dataset.id,
  1592. DocumentSegment.document_id == document.id,
  1593. DocumentSegment.tenant_id == current_user.current_tenant_id,
  1594. )
  1595. .all()
  1596. )
  1597. index_node_ids = [index_node_id[0] for index_node_id in index_node_ids]
  1598. delete_segment_from_index_task.delay(index_node_ids, dataset.id, document.id)
  1599. db.session.query(DocumentSegment).filter(DocumentSegment.id.in_(segment_ids)).delete()
  1600. db.session.commit()
  1601. @classmethod
  1602. def update_segments_status(cls, segment_ids: list, action: str, dataset: Dataset, document: Document):
  1603. if action == "enable":
  1604. segments = (
  1605. db.session.query(DocumentSegment)
  1606. .filter(
  1607. DocumentSegment.id.in_(segment_ids),
  1608. DocumentSegment.dataset_id == dataset.id,
  1609. DocumentSegment.document_id == document.id,
  1610. DocumentSegment.enabled == False,
  1611. )
  1612. .all()
  1613. )
  1614. if not segments:
  1615. return
  1616. real_deal_segmment_ids = []
  1617. for segment in segments:
  1618. indexing_cache_key = "segment_{}_indexing".format(segment.id)
  1619. cache_result = redis_client.get(indexing_cache_key)
  1620. if cache_result is not None:
  1621. continue
  1622. segment.enabled = True
  1623. segment.disabled_at = None
  1624. segment.disabled_by = None
  1625. db.session.add(segment)
  1626. real_deal_segmment_ids.append(segment.id)
  1627. db.session.commit()
  1628. enable_segments_to_index_task.delay(real_deal_segmment_ids, dataset.id, document.id)
  1629. elif action == "disable":
  1630. segments = (
  1631. db.session.query(DocumentSegment)
  1632. .filter(
  1633. DocumentSegment.id.in_(segment_ids),
  1634. DocumentSegment.dataset_id == dataset.id,
  1635. DocumentSegment.document_id == document.id,
  1636. DocumentSegment.enabled == True,
  1637. )
  1638. .all()
  1639. )
  1640. if not segments:
  1641. return
  1642. real_deal_segmment_ids = []
  1643. for segment in segments:
  1644. indexing_cache_key = "segment_{}_indexing".format(segment.id)
  1645. cache_result = redis_client.get(indexing_cache_key)
  1646. if cache_result is not None:
  1647. continue
  1648. segment.enabled = False
  1649. segment.disabled_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
  1650. segment.disabled_by = current_user.id
  1651. db.session.add(segment)
  1652. real_deal_segmment_ids.append(segment.id)
  1653. db.session.commit()
  1654. disable_segments_from_index_task.delay(real_deal_segmment_ids, dataset.id, document.id)
  1655. else:
  1656. raise InvalidActionError()
  1657. @classmethod
  1658. def create_child_chunk(
  1659. cls, content: str, segment: DocumentSegment, document: Document, dataset: Dataset
  1660. ) -> ChildChunk:
  1661. lock_name = "add_child_lock_{}".format(segment.id)
  1662. with redis_client.lock(lock_name, timeout=20):
  1663. index_node_id = str(uuid.uuid4())
  1664. index_node_hash = helper.generate_text_hash(content)
  1665. child_chunk_count = (
  1666. db.session.query(ChildChunk)
  1667. .filter(
  1668. ChildChunk.tenant_id == current_user.current_tenant_id,
  1669. ChildChunk.dataset_id == dataset.id,
  1670. ChildChunk.document_id == document.id,
  1671. ChildChunk.segment_id == segment.id,
  1672. )
  1673. .count()
  1674. )
  1675. max_position = (
  1676. db.session.query(func.max(ChildChunk.position))
  1677. .filter(
  1678. ChildChunk.tenant_id == current_user.current_tenant_id,
  1679. ChildChunk.dataset_id == dataset.id,
  1680. ChildChunk.document_id == document.id,
  1681. ChildChunk.segment_id == segment.id,
  1682. )
  1683. .scalar()
  1684. )
  1685. child_chunk = ChildChunk(
  1686. tenant_id=current_user.current_tenant_id,
  1687. dataset_id=dataset.id,
  1688. document_id=document.id,
  1689. segment_id=segment.id,
  1690. position=max_position + 1,
  1691. index_node_id=index_node_id,
  1692. index_node_hash=index_node_hash,
  1693. content=content,
  1694. word_count=len(content),
  1695. type="customized",
  1696. created_by=current_user.id,
  1697. )
  1698. db.session.add(child_chunk)
  1699. # save vector index
  1700. try:
  1701. VectorService.create_child_chunk_vector(child_chunk, dataset)
  1702. except Exception as e:
  1703. logging.exception("create child chunk index failed")
  1704. db.session.rollback()
  1705. raise ChildChunkIndexingError(str(e))
  1706. db.session.commit()
  1707. return child_chunk
  1708. @classmethod
  1709. def update_child_chunks(
  1710. cls,
  1711. child_chunks_update_args: list[ChildChunkUpdateArgs],
  1712. segment: DocumentSegment,
  1713. document: Document,
  1714. dataset: Dataset,
  1715. ) -> list[ChildChunk]:
  1716. child_chunks = (
  1717. db.session.query(ChildChunk)
  1718. .filter(
  1719. ChildChunk.dataset_id == dataset.id,
  1720. ChildChunk.document_id == document.id,
  1721. ChildChunk.segment_id == segment.id,
  1722. )
  1723. .all()
  1724. )
  1725. child_chunks_map = {chunk.id: chunk for chunk in child_chunks}
  1726. new_child_chunks, update_child_chunks, delete_child_chunks, new_child_chunks_args = [], [], [], []
  1727. for child_chunk_update_args in child_chunks_update_args:
  1728. if child_chunk_update_args.id:
  1729. child_chunk = child_chunks_map.pop(child_chunk_update_args.id, None)
  1730. if child_chunk:
  1731. if child_chunk.content != child_chunk_update_args.content:
  1732. child_chunk.content = child_chunk_update_args.content
  1733. child_chunk.word_count = len(child_chunk.content)
  1734. child_chunk.updated_by = current_user.id
  1735. child_chunk.updated_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
  1736. child_chunk.type = "customized"
  1737. update_child_chunks.append(child_chunk)
  1738. else:
  1739. new_child_chunks_args.append(child_chunk_update_args)
  1740. if child_chunks_map:
  1741. delete_child_chunks = list(child_chunks_map.values())
  1742. try:
  1743. if update_child_chunks:
  1744. db.session.bulk_save_objects(update_child_chunks)
  1745. if delete_child_chunks:
  1746. for child_chunk in delete_child_chunks:
  1747. db.session.delete(child_chunk)
  1748. if new_child_chunks_args:
  1749. child_chunk_count = len(child_chunks)
  1750. for position, args in enumerate(new_child_chunks_args, start=child_chunk_count + 1):
  1751. index_node_id = str(uuid.uuid4())
  1752. index_node_hash = helper.generate_text_hash(args.content)
  1753. child_chunk = ChildChunk(
  1754. tenant_id=current_user.current_tenant_id,
  1755. dataset_id=dataset.id,
  1756. document_id=document.id,
  1757. segment_id=segment.id,
  1758. position=position,
  1759. index_node_id=index_node_id,
  1760. index_node_hash=index_node_hash,
  1761. content=args.content,
  1762. word_count=len(args.content),
  1763. type="customized",
  1764. created_by=current_user.id,
  1765. )
  1766. db.session.add(child_chunk)
  1767. db.session.flush()
  1768. new_child_chunks.append(child_chunk)
  1769. VectorService.update_child_chunk_vector(new_child_chunks, update_child_chunks, delete_child_chunks, dataset)
  1770. db.session.commit()
  1771. except Exception as e:
  1772. logging.exception("update child chunk index failed")
  1773. db.session.rollback()
  1774. raise ChildChunkIndexingError(str(e))
  1775. return sorted(new_child_chunks + update_child_chunks, key=lambda x: x.position)
  1776. @classmethod
  1777. def update_child_chunk(
  1778. cls,
  1779. content: str,
  1780. child_chunk: ChildChunk,
  1781. segment: DocumentSegment,
  1782. document: Document,
  1783. dataset: Dataset,
  1784. ) -> ChildChunk:
  1785. try:
  1786. child_chunk.content = content
  1787. child_chunk.word_count = len(content)
  1788. child_chunk.updated_by = current_user.id
  1789. child_chunk.updated_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
  1790. child_chunk.type = "customized"
  1791. db.session.add(child_chunk)
  1792. VectorService.update_child_chunk_vector([], [child_chunk], [], dataset)
  1793. db.session.commit()
  1794. except Exception as e:
  1795. logging.exception("update child chunk index failed")
  1796. db.session.rollback()
  1797. raise ChildChunkIndexingError(str(e))
  1798. return child_chunk
  1799. @classmethod
  1800. def delete_child_chunk(cls, child_chunk: ChildChunk, dataset: Dataset):
  1801. db.session.delete(child_chunk)
  1802. try:
  1803. VectorService.delete_child_chunk_vector(child_chunk, dataset)
  1804. except Exception as e:
  1805. logging.exception("delete child chunk index failed")
  1806. db.session.rollback()
  1807. raise ChildChunkDeleteIndexError(str(e))
  1808. db.session.commit()
  1809. @classmethod
  1810. def get_child_chunks(
  1811. cls, segment_id: str, document_id: str, dataset_id: str, page: int, limit: int, keyword: Optional[str] = None
  1812. ):
  1813. query = ChildChunk.query.filter_by(
  1814. tenant_id=current_user.current_tenant_id,
  1815. dataset_id=dataset_id,
  1816. document_id=document_id,
  1817. segment_id=segment_id,
  1818. ).order_by(ChildChunk.position.asc())
  1819. if keyword:
  1820. query = query.where(ChildChunk.content.ilike(f"%{keyword}%"))
  1821. return query.paginate(page=page, per_page=limit, max_per_page=100, error_out=False)
  1822. class DatasetCollectionBindingService:
  1823. @classmethod
  1824. def get_dataset_collection_binding(
  1825. cls, provider_name: str, model_name: str, collection_type: str = "dataset"
  1826. ) -> DatasetCollectionBinding:
  1827. dataset_collection_binding = (
  1828. db.session.query(DatasetCollectionBinding)
  1829. .filter(
  1830. DatasetCollectionBinding.provider_name == provider_name,
  1831. DatasetCollectionBinding.model_name == model_name,
  1832. DatasetCollectionBinding.type == collection_type,
  1833. )
  1834. .order_by(DatasetCollectionBinding.created_at)
  1835. .first()
  1836. )
  1837. if not dataset_collection_binding:
  1838. dataset_collection_binding = DatasetCollectionBinding(
  1839. provider_name=provider_name,
  1840. model_name=model_name,
  1841. collection_name=Dataset.gen_collection_name_by_id(str(uuid.uuid4())),
  1842. type=collection_type,
  1843. )
  1844. db.session.add(dataset_collection_binding)
  1845. db.session.commit()
  1846. return dataset_collection_binding
  1847. @classmethod
  1848. def get_dataset_collection_binding_by_id_and_type(
  1849. cls, collection_binding_id: str, collection_type: str = "dataset"
  1850. ) -> DatasetCollectionBinding:
  1851. dataset_collection_binding = (
  1852. db.session.query(DatasetCollectionBinding)
  1853. .filter(
  1854. DatasetCollectionBinding.id == collection_binding_id, DatasetCollectionBinding.type == collection_type
  1855. )
  1856. .order_by(DatasetCollectionBinding.created_at)
  1857. .first()
  1858. )
  1859. if not dataset_collection_binding:
  1860. raise ValueError("Dataset collection binding not found")
  1861. return dataset_collection_binding
  1862. class DatasetPermissionService:
  1863. @classmethod
  1864. def get_dataset_partial_member_list(cls, dataset_id):
  1865. user_list_query = (
  1866. db.session.query(
  1867. DatasetPermission.account_id,
  1868. )
  1869. .filter(DatasetPermission.dataset_id == dataset_id)
  1870. .all()
  1871. )
  1872. user_list = []
  1873. for user in user_list_query:
  1874. user_list.append(user.account_id)
  1875. return user_list
  1876. @classmethod
  1877. def update_partial_member_list(cls, tenant_id, dataset_id, user_list):
  1878. try:
  1879. db.session.query(DatasetPermission).filter(DatasetPermission.dataset_id == dataset_id).delete()
  1880. permissions = []
  1881. for user in user_list:
  1882. permission = DatasetPermission(
  1883. tenant_id=tenant_id,
  1884. dataset_id=dataset_id,
  1885. account_id=user["user_id"],
  1886. )
  1887. permissions.append(permission)
  1888. db.session.add_all(permissions)
  1889. db.session.commit()
  1890. except Exception as e:
  1891. db.session.rollback()
  1892. raise e
  1893. @classmethod
  1894. def check_permission(cls, user, dataset, requested_permission, requested_partial_member_list):
  1895. if not user.is_dataset_editor:
  1896. raise NoPermissionError("User does not have permission to edit this dataset.")
  1897. if user.is_dataset_operator and dataset.permission != requested_permission:
  1898. raise NoPermissionError("Dataset operators cannot change the dataset permissions.")
  1899. if user.is_dataset_operator and requested_permission == "partial_members":
  1900. if not requested_partial_member_list:
  1901. raise ValueError("Partial member list is required when setting to partial members.")
  1902. local_member_list = cls.get_dataset_partial_member_list(dataset.id)
  1903. request_member_list = [user["user_id"] for user in requested_partial_member_list]
  1904. if set(local_member_list) != set(request_member_list):
  1905. raise ValueError("Dataset operators cannot change the dataset permissions.")
  1906. @classmethod
  1907. def clear_partial_member_list(cls, dataset_id):
  1908. try:
  1909. db.session.query(DatasetPermission).filter(DatasetPermission.dataset_id == dataset_id).delete()
  1910. db.session.commit()
  1911. except Exception as e:
  1912. db.session.rollback()
  1913. raise e