You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset_service.py 109KB

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