dataset_service.py 76 KB

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