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

dataset_service.py 121KB

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