Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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