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

dataset_service.py 128KB

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