dataset_service.py 96 KB

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