dataset_service.py 129 KB

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