Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

dataset_service.py 123KB

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