dataset_service.py 95 KB

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