dataset_service.py 98 KB

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