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

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