dataset_service.py 112 KB

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