dataset_service.py 76 KB

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