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 122KB

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