dataset_service.py 116 KB

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