Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

dataset_service.py 122KB

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