Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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