dataset_service.py 102 KB

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