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 128KB

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