dataset_service.py 103 KB

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