dataset_service.py 127 KB

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