Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

dataset_service.py 122KB

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