You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset_service.py 122KB

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