您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

dataset_service.py 122KB

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