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

dataset_service.py 121KB

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