dataset_service.py 98 KB

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