dataset_service.py 95 KB

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