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

dataset_service.py 123KB

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