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

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