dataset_service.py 97 KB

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