dataset_service.py 78 KB

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