dataset_service.py 97 KB

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