dataset_service.py 76 KB

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