dataset_service.py 99 KB

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