您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

dataset_service.py 122KB

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