dataset_service.py 103 KB

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