dataset_service.py 77 KB

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