dataset_service.py 111 KB

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