dataset_service.py 116 KB

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