Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

dataset_service.py 147KB

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