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

dataset_service.py 108KB

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