dataset_service.py 103 KB

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