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

dataset_service.py 147KB

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