Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

dataset_service.py 93KB

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