Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

dataset_service.py 109KB

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