You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rag_pipeline.py 53KB

6 달 전
5 달 전
5 달 전
6 달 전
6 달 전
5 달 전
6 달 전
4 달 전
6 달 전
5 달 전
6 달 전
4 달 전
4 달 전
5 달 전
4 달 전
5 달 전
5 달 전
4 달 전
3 달 전
5 달 전
5 달 전
6 달 전
5 달 전
6 달 전
6 달 전
5 달 전
6 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
6 달 전
3 달 전
6 달 전
5 달 전
6 달 전
5 달 전
5 달 전
6 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
4 달 전
6 달 전
6 달 전
5 달 전
6 달 전
4 달 전
4 달 전
6 달 전
4 달 전
6 달 전
4 달 전
6 달 전
4 달 전
4 달 전
6 달 전
4 달 전
6 달 전
4 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
6 달 전
6 달 전
6 달 전
6 달 전
3 달 전
6 달 전
3 달 전
3 달 전
6 달 전
3 달 전
3 달 전
6 달 전
3 달 전
3 달 전
3 달 전
3 달 전
3 달 전
3 달 전
5 달 전
2 달 전
5 달 전
3 달 전
3 달 전
3 달 전
2 달 전
2 달 전
4 달 전
4 달 전
4 달 전
4 달 전
3 달 전
5 달 전
4 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
6 달 전
5 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
5 달 전
6 달 전
4 달 전
6 달 전
4 달 전
5 달 전
4 달 전
5 달 전
5 달 전
4 달 전
5 달 전
5 달 전
4 달 전
5 달 전
4 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
4 달 전
5 달 전
5 달 전
4 달 전
5 달 전
4 달 전
5 달 전
5 달 전
4 달 전
5 달 전
4 달 전
5 달 전
4 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
4 달 전
5 달 전
5 달 전
5 달 전
5 달 전
4 달 전
5 달 전
5 달 전
5 달 전
5 달 전
5 달 전
4 달 전
4 달 전
4 달 전
4 달 전
4 달 전
4 달 전
5 달 전
4 달 전
4 달 전
4 달 전
5 달 전
3 달 전
3 달 전
3 달 전
3 달 전
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. import json
  2. import logging
  3. import re
  4. import threading
  5. import time
  6. from collections.abc import Callable, Generator, Mapping, Sequence
  7. from datetime import UTC, datetime
  8. from typing import Any, Optional, cast
  9. from uuid import uuid4
  10. from flask_login import current_user
  11. from sqlalchemy import func, or_, select
  12. from sqlalchemy.orm import Session, sessionmaker
  13. import contexts
  14. from configs import dify_config
  15. from core.app.entities.app_invoke_entities import InvokeFrom
  16. from core.datasource.entities.datasource_entities import (
  17. DatasourceMessage,
  18. DatasourceProviderType,
  19. GetOnlineDocumentPageContentRequest,
  20. OnlineDocumentPagesMessage,
  21. OnlineDriveBrowseFilesRequest,
  22. OnlineDriveBrowseFilesResponse,
  23. WebsiteCrawlMessage,
  24. )
  25. from core.datasource.online_document.online_document_plugin import OnlineDocumentDatasourcePlugin
  26. from core.datasource.online_drive.online_drive_plugin import OnlineDriveDatasourcePlugin
  27. from core.datasource.website_crawl.website_crawl_plugin import WebsiteCrawlDatasourcePlugin
  28. from core.helper import marketplace
  29. from core.rag.entities.event import (
  30. DatasourceCompletedEvent,
  31. DatasourceErrorEvent,
  32. DatasourceProcessingEvent,
  33. )
  34. from core.repositories.factory import DifyCoreRepositoryFactory
  35. from core.repositories.sqlalchemy_workflow_node_execution_repository import SQLAlchemyWorkflowNodeExecutionRepository
  36. from core.variables.variables import Variable
  37. from core.workflow.entities.variable_pool import VariablePool
  38. from core.workflow.entities.workflow_node_execution import (
  39. WorkflowNodeExecution,
  40. WorkflowNodeExecutionStatus,
  41. )
  42. from core.workflow.enums import ErrorStrategy, NodeType, SystemVariableKey
  43. from core.workflow.errors import WorkflowNodeRunFailedError
  44. from core.workflow.graph_events import NodeRunFailedEvent, NodeRunSucceededEvent
  45. from core.workflow.graph_events.base import GraphNodeEventBase
  46. from core.workflow.node_events.base import NodeRunResult
  47. from core.workflow.nodes.base.node import Node
  48. from core.workflow.nodes.node_mapping import LATEST_VERSION, NODE_TYPE_CLASSES_MAPPING
  49. from core.workflow.repositories.workflow_node_execution_repository import OrderConfig
  50. from core.workflow.system_variable import SystemVariable
  51. from core.workflow.workflow_entry import WorkflowEntry
  52. from extensions.ext_database import db
  53. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  54. from models.account import Account
  55. from models.dataset import Document, Pipeline, PipelineCustomizedTemplate, PipelineRecommendedPlugin # type: ignore
  56. from models.enums import WorkflowRunTriggeredFrom
  57. from models.model import EndUser
  58. from models.workflow import (
  59. Workflow,
  60. WorkflowNodeExecutionModel,
  61. WorkflowNodeExecutionTriggeredFrom,
  62. WorkflowRun,
  63. WorkflowType,
  64. )
  65. from repositories.factory import DifyAPIRepositoryFactory
  66. from services.dataset_service import DatasetService
  67. from services.datasource_provider_service import DatasourceProviderService
  68. from services.entities.knowledge_entities.rag_pipeline_entities import (
  69. KnowledgeConfiguration,
  70. PipelineTemplateInfoEntity,
  71. )
  72. from services.errors.app import WorkflowHashNotEqualError
  73. from services.rag_pipeline.pipeline_template.pipeline_template_factory import PipelineTemplateRetrievalFactory
  74. from services.tools.builtin_tools_manage_service import BuiltinToolManageService
  75. from services.workflow_draft_variable_service import DraftVariableSaver, DraftVarLoader
  76. logger = logging.getLogger(__name__)
  77. class RagPipelineService:
  78. def __init__(self, session_maker: sessionmaker | None = None):
  79. """Initialize RagPipelineService with repository dependencies."""
  80. if session_maker is None:
  81. session_maker = sessionmaker(bind=db.engine, expire_on_commit=False)
  82. self._node_execution_service_repo = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(
  83. session_maker
  84. )
  85. @classmethod
  86. def get_pipeline_templates(cls, type: str = "built-in", language: str = "en-US") -> dict:
  87. if type == "built-in":
  88. mode = dify_config.HOSTED_FETCH_PIPELINE_TEMPLATES_MODE
  89. retrieval_instance = PipelineTemplateRetrievalFactory.get_pipeline_template_factory(mode)()
  90. result = retrieval_instance.get_pipeline_templates(language)
  91. if not result.get("pipeline_templates") and language != "en-US":
  92. template_retrieval = PipelineTemplateRetrievalFactory.get_built_in_pipeline_template_retrieval()
  93. result = template_retrieval.fetch_pipeline_templates_from_builtin("en-US")
  94. return result
  95. else:
  96. mode = "customized"
  97. retrieval_instance = PipelineTemplateRetrievalFactory.get_pipeline_template_factory(mode)()
  98. result = retrieval_instance.get_pipeline_templates(language)
  99. return result
  100. @classmethod
  101. def get_pipeline_template_detail(cls, template_id: str, type: str = "built-in") -> Optional[dict]:
  102. """
  103. Get pipeline template detail.
  104. :param template_id: template id
  105. :return:
  106. """
  107. if type == "built-in":
  108. mode = dify_config.HOSTED_FETCH_PIPELINE_TEMPLATES_MODE
  109. retrieval_instance = PipelineTemplateRetrievalFactory.get_pipeline_template_factory(mode)()
  110. built_in_result: Optional[dict] = retrieval_instance.get_pipeline_template_detail(template_id)
  111. return built_in_result
  112. else:
  113. mode = "customized"
  114. retrieval_instance = PipelineTemplateRetrievalFactory.get_pipeline_template_factory(mode)()
  115. customized_result: Optional[dict] = retrieval_instance.get_pipeline_template_detail(template_id)
  116. return customized_result
  117. @classmethod
  118. def update_customized_pipeline_template(cls, template_id: str, template_info: PipelineTemplateInfoEntity):
  119. """
  120. Update pipeline template.
  121. :param template_id: template id
  122. :param template_info: template info
  123. """
  124. customized_template: PipelineCustomizedTemplate | None = (
  125. db.session.query(PipelineCustomizedTemplate)
  126. .filter(
  127. PipelineCustomizedTemplate.id == template_id,
  128. PipelineCustomizedTemplate.tenant_id == current_user.current_tenant_id,
  129. )
  130. .first()
  131. )
  132. if not customized_template:
  133. raise ValueError("Customized pipeline template not found.")
  134. # check template name is exist
  135. template_name = template_info.name
  136. if template_name:
  137. template = (
  138. db.session.query(PipelineCustomizedTemplate)
  139. .filter(
  140. PipelineCustomizedTemplate.name == template_name,
  141. PipelineCustomizedTemplate.tenant_id == current_user.current_tenant_id,
  142. PipelineCustomizedTemplate.id != template_id,
  143. )
  144. .first()
  145. )
  146. if template:
  147. raise ValueError("Template name is already exists")
  148. customized_template.name = template_info.name
  149. customized_template.description = template_info.description
  150. customized_template.icon = template_info.icon_info.model_dump()
  151. customized_template.updated_by = current_user.id
  152. db.session.commit()
  153. return customized_template
  154. @classmethod
  155. def delete_customized_pipeline_template(cls, template_id: str):
  156. """
  157. Delete customized pipeline template.
  158. """
  159. customized_template: PipelineCustomizedTemplate | None = (
  160. db.session.query(PipelineCustomizedTemplate)
  161. .filter(
  162. PipelineCustomizedTemplate.id == template_id,
  163. PipelineCustomizedTemplate.tenant_id == current_user.current_tenant_id,
  164. )
  165. .first()
  166. )
  167. if not customized_template:
  168. raise ValueError("Customized pipeline template not found.")
  169. db.session.delete(customized_template)
  170. db.session.commit()
  171. def get_draft_workflow(self, pipeline: Pipeline) -> Optional[Workflow]:
  172. """
  173. Get draft workflow
  174. """
  175. # fetch draft workflow by rag pipeline
  176. workflow = (
  177. db.session.query(Workflow)
  178. .filter(
  179. Workflow.tenant_id == pipeline.tenant_id,
  180. Workflow.app_id == pipeline.id,
  181. Workflow.version == "draft",
  182. )
  183. .first()
  184. )
  185. # return draft workflow
  186. return workflow
  187. def get_published_workflow(self, pipeline: Pipeline) -> Optional[Workflow]:
  188. """
  189. Get published workflow
  190. """
  191. if not pipeline.workflow_id:
  192. return None
  193. # fetch published workflow by workflow_id
  194. workflow = (
  195. db.session.query(Workflow)
  196. .filter(
  197. Workflow.tenant_id == pipeline.tenant_id,
  198. Workflow.app_id == pipeline.id,
  199. Workflow.id == pipeline.workflow_id,
  200. )
  201. .first()
  202. )
  203. return workflow
  204. def get_all_published_workflow(
  205. self,
  206. *,
  207. session: Session,
  208. pipeline: Pipeline,
  209. page: int,
  210. limit: int,
  211. user_id: str | None,
  212. named_only: bool = False,
  213. ) -> tuple[Sequence[Workflow], bool]:
  214. """
  215. Get published workflow with pagination
  216. """
  217. if not pipeline.workflow_id:
  218. return [], False
  219. stmt = (
  220. select(Workflow)
  221. .where(Workflow.app_id == pipeline.id)
  222. .order_by(Workflow.version.desc())
  223. .limit(limit + 1)
  224. .offset((page - 1) * limit)
  225. )
  226. if user_id:
  227. stmt = stmt.where(Workflow.created_by == user_id)
  228. if named_only:
  229. stmt = stmt.where(Workflow.marked_name != "")
  230. workflows = session.scalars(stmt).all()
  231. has_more = len(workflows) > limit
  232. if has_more:
  233. workflows = workflows[:-1]
  234. return workflows, has_more
  235. def sync_draft_workflow(
  236. self,
  237. *,
  238. pipeline: Pipeline,
  239. graph: dict,
  240. unique_hash: Optional[str],
  241. account: Account,
  242. environment_variables: Sequence[Variable],
  243. conversation_variables: Sequence[Variable],
  244. rag_pipeline_variables: list,
  245. ) -> Workflow:
  246. """
  247. Sync draft workflow
  248. :raises WorkflowHashNotEqualError
  249. """
  250. # fetch draft workflow by app_model
  251. workflow = self.get_draft_workflow(pipeline=pipeline)
  252. if workflow and workflow.unique_hash != unique_hash:
  253. raise WorkflowHashNotEqualError()
  254. # create draft workflow if not found
  255. if not workflow:
  256. workflow = Workflow(
  257. tenant_id=pipeline.tenant_id,
  258. app_id=pipeline.id,
  259. features="{}",
  260. type=WorkflowType.RAG_PIPELINE.value,
  261. version="draft",
  262. graph=json.dumps(graph),
  263. created_by=account.id,
  264. environment_variables=environment_variables,
  265. conversation_variables=conversation_variables,
  266. rag_pipeline_variables=rag_pipeline_variables,
  267. )
  268. db.session.add(workflow)
  269. db.session.flush()
  270. pipeline.workflow_id = workflow.id
  271. # update draft workflow if found
  272. else:
  273. workflow.graph = json.dumps(graph)
  274. workflow.updated_by = account.id
  275. workflow.updated_at = datetime.now(UTC).replace(tzinfo=None)
  276. workflow.environment_variables = environment_variables
  277. workflow.conversation_variables = conversation_variables
  278. workflow.rag_pipeline_variables = rag_pipeline_variables
  279. # commit db session changes
  280. db.session.commit()
  281. # trigger workflow events TODO
  282. # app_draft_workflow_was_synced.send(pipeline, synced_draft_workflow=workflow)
  283. # return draft workflow
  284. return workflow
  285. def publish_workflow(
  286. self,
  287. *,
  288. session: Session,
  289. pipeline: Pipeline,
  290. account: Account,
  291. ) -> Workflow:
  292. draft_workflow_stmt = select(Workflow).where(
  293. Workflow.tenant_id == pipeline.tenant_id,
  294. Workflow.app_id == pipeline.id,
  295. Workflow.version == "draft",
  296. )
  297. draft_workflow = session.scalar(draft_workflow_stmt)
  298. if not draft_workflow:
  299. raise ValueError("No valid workflow found.")
  300. # create new workflow
  301. workflow = Workflow.new(
  302. tenant_id=pipeline.tenant_id,
  303. app_id=pipeline.id,
  304. type=draft_workflow.type,
  305. version=str(datetime.now(UTC).replace(tzinfo=None)),
  306. graph=draft_workflow.graph,
  307. features=draft_workflow.features,
  308. created_by=account.id,
  309. environment_variables=draft_workflow.environment_variables,
  310. conversation_variables=draft_workflow.conversation_variables,
  311. rag_pipeline_variables=draft_workflow.rag_pipeline_variables,
  312. marked_name="",
  313. marked_comment="",
  314. )
  315. # commit db session changes
  316. session.add(workflow)
  317. graph = workflow.graph_dict
  318. nodes = graph.get("nodes", [])
  319. for node in nodes:
  320. if node.get("data", {}).get("type") == "knowledge-index":
  321. knowledge_configuration = node.get("data", {})
  322. knowledge_configuration = KnowledgeConfiguration(**knowledge_configuration)
  323. # update dataset
  324. dataset = pipeline.dataset
  325. if not dataset:
  326. raise ValueError("Dataset not found")
  327. DatasetService.update_rag_pipeline_dataset_settings(
  328. session=session,
  329. dataset=dataset,
  330. knowledge_configuration=knowledge_configuration,
  331. has_published=pipeline.is_published,
  332. )
  333. # return new workflow
  334. return workflow
  335. def get_default_block_configs(self) -> list[dict]:
  336. """
  337. Get default block configs
  338. """
  339. # return default block config
  340. default_block_configs = []
  341. for node_class_mapping in NODE_TYPE_CLASSES_MAPPING.values():
  342. node_class = node_class_mapping[LATEST_VERSION]
  343. default_config = node_class.get_default_config()
  344. if default_config:
  345. default_block_configs.append(default_config)
  346. return default_block_configs
  347. def get_default_block_config(self, node_type: str, filters: Optional[dict] = None) -> Optional[dict]:
  348. """
  349. Get default config of node.
  350. :param node_type: node type
  351. :param filters: filter by node config parameters.
  352. :return:
  353. """
  354. node_type_enum = NodeType(node_type)
  355. # return default block config
  356. if node_type_enum not in NODE_TYPE_CLASSES_MAPPING:
  357. return None
  358. node_class = NODE_TYPE_CLASSES_MAPPING[node_type_enum][LATEST_VERSION]
  359. default_config = node_class.get_default_config(filters=filters)
  360. if not default_config:
  361. return None
  362. return default_config
  363. def run_draft_workflow_node(
  364. self, pipeline: Pipeline, node_id: str, user_inputs: dict, account: Account
  365. ) -> WorkflowNodeExecutionModel | None:
  366. """
  367. Run draft workflow node
  368. """
  369. # fetch draft workflow by app_model
  370. draft_workflow = self.get_draft_workflow(pipeline=pipeline)
  371. if not draft_workflow:
  372. raise ValueError("Workflow not initialized")
  373. # run draft workflow node
  374. start_at = time.perf_counter()
  375. node_config = draft_workflow.get_node_config_by_id(node_id)
  376. eclosing_node_type_and_id = draft_workflow.get_enclosing_node_type_and_id(node_config)
  377. if eclosing_node_type_and_id:
  378. _, enclosing_node_id = eclosing_node_type_and_id
  379. else:
  380. enclosing_node_id = None
  381. workflow_node_execution = self._handle_node_run_result(
  382. getter=lambda: WorkflowEntry.single_step_run(
  383. workflow=draft_workflow,
  384. node_id=node_id,
  385. user_inputs=user_inputs,
  386. user_id=account.id,
  387. variable_pool=VariablePool(
  388. system_variables=SystemVariable.empty(),
  389. user_inputs=user_inputs,
  390. environment_variables=[],
  391. conversation_variables=[],
  392. rag_pipeline_variables=[],
  393. ),
  394. variable_loader=DraftVarLoader(
  395. engine=db.engine,
  396. app_id=pipeline.id,
  397. tenant_id=pipeline.tenant_id,
  398. ),
  399. ),
  400. start_at=start_at,
  401. tenant_id=pipeline.tenant_id,
  402. node_id=node_id,
  403. )
  404. workflow_node_execution.workflow_id = draft_workflow.id
  405. # Create repository and save the node execution
  406. repository = DifyCoreRepositoryFactory.create_workflow_node_execution_repository(
  407. session_factory=db.engine,
  408. user=account,
  409. app_id=pipeline.id,
  410. triggered_from=WorkflowNodeExecutionTriggeredFrom.SINGLE_STEP,
  411. )
  412. repository.save(workflow_node_execution)
  413. # Convert node_execution to WorkflowNodeExecution after save
  414. workflow_node_execution_db_model = self._node_execution_service_repo.get_execution_by_id(workflow_node_execution.id)
  415. with Session(bind=db.engine) as session, session.begin():
  416. draft_var_saver = DraftVariableSaver(
  417. session=session,
  418. app_id=pipeline.id,
  419. node_id=workflow_node_execution.node_id,
  420. node_type=NodeType(workflow_node_execution.node_type),
  421. enclosing_node_id=enclosing_node_id,
  422. node_execution_id=workflow_node_execution.id,
  423. user=account,
  424. )
  425. draft_var_saver.save(
  426. process_data=workflow_node_execution.process_data,
  427. outputs=workflow_node_execution.outputs,
  428. )
  429. session.commit()
  430. return workflow_node_execution_db_model
  431. def run_datasource_workflow_node(
  432. self,
  433. pipeline: Pipeline,
  434. node_id: str,
  435. user_inputs: dict,
  436. account: Account,
  437. datasource_type: str,
  438. is_published: bool,
  439. credential_id: Optional[str] = None,
  440. ) -> Generator[Mapping[str, Any], None, None]:
  441. """
  442. Run published workflow datasource
  443. """
  444. try:
  445. if is_published:
  446. # fetch published workflow by app_model
  447. workflow = self.get_published_workflow(pipeline=pipeline)
  448. else:
  449. workflow = self.get_draft_workflow(pipeline=pipeline)
  450. if not workflow:
  451. raise ValueError("Workflow not initialized")
  452. # run draft workflow node
  453. datasource_node_data = None
  454. datasource_nodes = workflow.graph_dict.get("nodes", [])
  455. for datasource_node in datasource_nodes:
  456. if datasource_node.get("id") == node_id:
  457. datasource_node_data = datasource_node.get("data", {})
  458. break
  459. if not datasource_node_data:
  460. raise ValueError("Datasource node data not found")
  461. variables_map = {}
  462. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  463. for key, value in datasource_parameters.items():
  464. if value.get("value") and isinstance(value.get("value"), str):
  465. pattern = r"\{\{#([a-zA-Z0-9_]{1,50}(?:\.[a-zA-Z0-9_][a-zA-Z0-9_]{0,29}){1,10})#\}\}"
  466. match = re.match(pattern, value["value"])
  467. if match:
  468. full_path = match.group(1)
  469. last_part = full_path.split(".")[-1]
  470. if last_part in user_inputs:
  471. variables_map[key] = user_inputs[last_part]
  472. else:
  473. variables_map[key] = value["value"]
  474. else:
  475. variables_map[key] = value["value"]
  476. else:
  477. variables_map[key] = value["value"]
  478. from core.datasource.datasource_manager import DatasourceManager
  479. datasource_runtime = DatasourceManager.get_datasource_runtime(
  480. provider_id=f"{datasource_node_data.get('plugin_id')}/{datasource_node_data.get('provider_name')}",
  481. datasource_name=datasource_node_data.get("datasource_name"),
  482. tenant_id=pipeline.tenant_id,
  483. datasource_type=DatasourceProviderType(datasource_type),
  484. )
  485. datasource_provider_service = DatasourceProviderService()
  486. credentials = datasource_provider_service.get_datasource_credentials(
  487. tenant_id=pipeline.tenant_id,
  488. provider=datasource_node_data.get("provider_name"),
  489. plugin_id=datasource_node_data.get("plugin_id"),
  490. credential_id=credential_id,
  491. )
  492. if credentials:
  493. datasource_runtime.runtime.credentials = credentials
  494. match datasource_type:
  495. case DatasourceProviderType.ONLINE_DOCUMENT:
  496. datasource_runtime = cast(OnlineDocumentDatasourcePlugin, datasource_runtime)
  497. online_document_result: Generator[OnlineDocumentPagesMessage, None, None] = (
  498. datasource_runtime.get_online_document_pages(
  499. user_id=account.id,
  500. datasource_parameters=user_inputs,
  501. provider_type=datasource_runtime.datasource_provider_type(),
  502. )
  503. )
  504. start_time = time.time()
  505. start_event = DatasourceProcessingEvent(
  506. total=0,
  507. completed=0,
  508. )
  509. yield start_event.model_dump()
  510. try:
  511. for message in online_document_result:
  512. end_time = time.time()
  513. online_document_event = DatasourceCompletedEvent(
  514. data=message.result, time_consuming=round(end_time - start_time, 2)
  515. )
  516. yield online_document_event.model_dump()
  517. except Exception as e:
  518. logger.exception("Error during online document.")
  519. yield DatasourceErrorEvent(error=str(e)).model_dump()
  520. case DatasourceProviderType.ONLINE_DRIVE:
  521. datasource_runtime = cast(OnlineDriveDatasourcePlugin, datasource_runtime)
  522. online_drive_result: Generator[OnlineDriveBrowseFilesResponse, None, None] = (
  523. datasource_runtime.online_drive_browse_files(
  524. user_id=account.id,
  525. request=OnlineDriveBrowseFilesRequest(
  526. bucket=user_inputs.get("bucket"),
  527. prefix=user_inputs.get("prefix", ""),
  528. max_keys=user_inputs.get("max_keys", 20),
  529. next_page_parameters=user_inputs.get("next_page_parameters"),
  530. ),
  531. provider_type=datasource_runtime.datasource_provider_type(),
  532. )
  533. )
  534. start_time = time.time()
  535. start_event = DatasourceProcessingEvent(
  536. total=0,
  537. completed=0,
  538. )
  539. yield start_event.model_dump()
  540. for message in online_drive_result:
  541. end_time = time.time()
  542. online_drive_event = DatasourceCompletedEvent(
  543. data=message.result,
  544. time_consuming=round(end_time - start_time, 2),
  545. total=None,
  546. completed=None,
  547. )
  548. yield online_drive_event.model_dump()
  549. case DatasourceProviderType.WEBSITE_CRAWL:
  550. datasource_runtime = cast(WebsiteCrawlDatasourcePlugin, datasource_runtime)
  551. website_crawl_result: Generator[WebsiteCrawlMessage, None, None] = (
  552. datasource_runtime.get_website_crawl(
  553. user_id=account.id,
  554. datasource_parameters=variables_map,
  555. provider_type=datasource_runtime.datasource_provider_type(),
  556. )
  557. )
  558. start_time = time.time()
  559. try:
  560. for message in website_crawl_result:
  561. end_time = time.time()
  562. if message.result.status == "completed":
  563. crawl_event = DatasourceCompletedEvent(
  564. data=message.result.web_info_list or [],
  565. total=message.result.total,
  566. completed=message.result.completed,
  567. time_consuming=round(end_time - start_time, 2),
  568. )
  569. else:
  570. crawl_event = DatasourceProcessingEvent(
  571. total=message.result.total,
  572. completed=message.result.completed,
  573. )
  574. yield crawl_event.model_dump()
  575. except Exception as e:
  576. logger.exception("Error during website crawl.")
  577. yield DatasourceErrorEvent(error=str(e)).model_dump()
  578. case _:
  579. raise ValueError(f"Unsupported datasource provider: {datasource_runtime.datasource_provider_type}")
  580. except Exception as e:
  581. logger.exception("Error in run_datasource_workflow_node.")
  582. yield DatasourceErrorEvent(error=str(e)).model_dump()
  583. def run_datasource_node_preview(
  584. self,
  585. pipeline: Pipeline,
  586. node_id: str,
  587. user_inputs: dict,
  588. account: Account,
  589. datasource_type: str,
  590. is_published: bool,
  591. credential_id: Optional[str] = None,
  592. ) -> Mapping[str, Any]:
  593. """
  594. Run published workflow datasource
  595. """
  596. try:
  597. if is_published:
  598. # fetch published workflow by app_model
  599. workflow = self.get_published_workflow(pipeline=pipeline)
  600. else:
  601. workflow = self.get_draft_workflow(pipeline=pipeline)
  602. if not workflow:
  603. raise ValueError("Workflow not initialized")
  604. # run draft workflow node
  605. datasource_node_data = None
  606. datasource_nodes = workflow.graph_dict.get("nodes", [])
  607. for datasource_node in datasource_nodes:
  608. if datasource_node.get("id") == node_id:
  609. datasource_node_data = datasource_node.get("data", {})
  610. break
  611. if not datasource_node_data:
  612. raise ValueError("Datasource node data not found")
  613. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  614. for key, value in datasource_parameters.items():
  615. if not user_inputs.get(key):
  616. user_inputs[key] = value["value"]
  617. from core.datasource.datasource_manager import DatasourceManager
  618. datasource_runtime = DatasourceManager.get_datasource_runtime(
  619. provider_id=f"{datasource_node_data.get('plugin_id')}/{datasource_node_data.get('provider_name')}",
  620. datasource_name=datasource_node_data.get("datasource_name"),
  621. tenant_id=pipeline.tenant_id,
  622. datasource_type=DatasourceProviderType(datasource_type),
  623. )
  624. datasource_provider_service = DatasourceProviderService()
  625. credentials = datasource_provider_service.get_datasource_credentials(
  626. tenant_id=pipeline.tenant_id,
  627. provider=datasource_node_data.get("provider_name"),
  628. plugin_id=datasource_node_data.get("plugin_id"),
  629. credential_id=credential_id,
  630. )
  631. if credentials:
  632. datasource_runtime.runtime.credentials = credentials
  633. match datasource_type:
  634. case DatasourceProviderType.ONLINE_DOCUMENT:
  635. datasource_runtime = cast(OnlineDocumentDatasourcePlugin, datasource_runtime)
  636. online_document_result: Generator[DatasourceMessage, None, None] = (
  637. datasource_runtime.get_online_document_page_content(
  638. user_id=account.id,
  639. datasource_parameters=GetOnlineDocumentPageContentRequest(
  640. workspace_id=user_inputs.get("workspace_id", ""),
  641. page_id=user_inputs.get("page_id", ""),
  642. type=user_inputs.get("type", ""),
  643. ),
  644. provider_type=datasource_type,
  645. )
  646. )
  647. try:
  648. variables: dict[str, Any] = {}
  649. for message in online_document_result:
  650. if message.type == DatasourceMessage.MessageType.VARIABLE:
  651. assert isinstance(message.message, DatasourceMessage.VariableMessage)
  652. variable_name = message.message.variable_name
  653. variable_value = message.message.variable_value
  654. if message.message.stream:
  655. if not isinstance(variable_value, str):
  656. raise ValueError("When 'stream' is True, 'variable_value' must be a string.")
  657. if variable_name not in variables:
  658. variables[variable_name] = ""
  659. variables[variable_name] += variable_value
  660. else:
  661. variables[variable_name] = variable_value
  662. return variables
  663. except Exception as e:
  664. logger.exception("Error during get online document content.")
  665. raise RuntimeError(str(e))
  666. # TODO Online Drive
  667. case _:
  668. raise ValueError(f"Unsupported datasource provider: {datasource_runtime.datasource_provider_type}")
  669. except Exception as e:
  670. logger.exception("Error in run_datasource_node_preview.")
  671. raise RuntimeError(str(e))
  672. def run_free_workflow_node(
  673. self, node_data: dict, tenant_id: str, user_id: str, node_id: str, user_inputs: dict[str, Any]
  674. ) -> WorkflowNodeExecution:
  675. """
  676. Run draft workflow node
  677. """
  678. # run draft workflow node
  679. start_at = time.perf_counter()
  680. workflow_node_execution = self._handle_node_run_result(
  681. getter=lambda: WorkflowEntry.run_free_node(
  682. node_id=node_id,
  683. node_data=node_data,
  684. tenant_id=tenant_id,
  685. user_id=user_id,
  686. user_inputs=user_inputs,
  687. ),
  688. start_at=start_at,
  689. tenant_id=tenant_id,
  690. node_id=node_id,
  691. )
  692. return workflow_node_execution
  693. def _handle_node_run_result(
  694. self,
  695. getter: Callable[[], tuple[Node, Generator[GraphNodeEventBase, None, None]]],
  696. start_at: float,
  697. tenant_id: str,
  698. node_id: str,
  699. ) -> WorkflowNodeExecution:
  700. """
  701. Handle node run result
  702. :param getter: Callable[[], tuple[BaseNode, Generator[RunEvent | InNodeEvent, None, None]]]
  703. :param start_at: float
  704. :param tenant_id: str
  705. :param node_id: str
  706. """
  707. try:
  708. node_instance, generator = getter()
  709. node_run_result: NodeRunResult | None = None
  710. for event in generator:
  711. if isinstance(event, (NodeRunSucceededEvent, NodeRunFailedEvent)):
  712. node_run_result = event.node_run_result
  713. # sign output files
  714. node_run_result.outputs = WorkflowEntry.handle_special_values(node_run_result.outputs) or {}
  715. break
  716. if not node_run_result:
  717. raise ValueError("Node run failed with no run result")
  718. # single step debug mode error handling return
  719. if node_run_result.status == WorkflowNodeExecutionStatus.FAILED and node_instance.error_strategy:
  720. node_error_args: dict[str, Any] = {
  721. "status": WorkflowNodeExecutionStatus.EXCEPTION,
  722. "error": node_run_result.error,
  723. "inputs": node_run_result.inputs,
  724. "metadata": {"error_strategy": node_instance.error_strategy},
  725. }
  726. if node_instance.error_strategy is ErrorStrategy.DEFAULT_VALUE:
  727. node_run_result = NodeRunResult(
  728. **node_error_args,
  729. outputs={
  730. **node_instance.default_value_dict,
  731. "error_message": node_run_result.error,
  732. "error_type": node_run_result.error_type,
  733. },
  734. )
  735. else:
  736. node_run_result = NodeRunResult(
  737. **node_error_args,
  738. outputs={
  739. "error_message": node_run_result.error,
  740. "error_type": node_run_result.error_type,
  741. },
  742. )
  743. run_succeeded = node_run_result.status in (
  744. WorkflowNodeExecutionStatus.SUCCEEDED,
  745. WorkflowNodeExecutionStatus.EXCEPTION,
  746. )
  747. error = node_run_result.error if not run_succeeded else None
  748. except WorkflowNodeRunFailedError as e:
  749. node_instance = e._node
  750. run_succeeded = False
  751. node_run_result = None
  752. error = e._error
  753. workflow_node_execution = WorkflowNodeExecution(
  754. id=str(uuid4()),
  755. workflow_id=node_instance.workflow_id,
  756. index=1,
  757. node_id=node_id,
  758. node_type=node_instance.node_type,
  759. title=node_instance.title,
  760. elapsed_time=time.perf_counter() - start_at,
  761. finished_at=datetime.now(UTC).replace(tzinfo=None),
  762. created_at=datetime.now(UTC).replace(tzinfo=None),
  763. )
  764. if run_succeeded and node_run_result:
  765. # create workflow node execution
  766. inputs = WorkflowEntry.handle_special_values(node_run_result.inputs) if node_run_result.inputs else None
  767. process_data = (
  768. WorkflowEntry.handle_special_values(node_run_result.process_data)
  769. if node_run_result.process_data
  770. else None
  771. )
  772. outputs = WorkflowEntry.handle_special_values(node_run_result.outputs) if node_run_result.outputs else None
  773. workflow_node_execution.inputs = inputs
  774. workflow_node_execution.process_data = process_data
  775. workflow_node_execution.outputs = outputs
  776. workflow_node_execution.metadata = node_run_result.metadata
  777. if node_run_result.status == WorkflowNodeExecutionStatus.SUCCEEDED:
  778. workflow_node_execution.status = WorkflowNodeExecutionStatus.SUCCEEDED
  779. elif node_run_result.status == WorkflowNodeExecutionStatus.EXCEPTION:
  780. workflow_node_execution.status = WorkflowNodeExecutionStatus.EXCEPTION
  781. workflow_node_execution.error = node_run_result.error
  782. else:
  783. # create workflow node execution
  784. workflow_node_execution.status = WorkflowNodeExecutionStatus.FAILED
  785. workflow_node_execution.error = error
  786. # update document status
  787. variable_pool = node_instance.graph_runtime_state.variable_pool
  788. invoke_from = variable_pool.get(["sys", SystemVariableKey.INVOKE_FROM])
  789. if invoke_from:
  790. if invoke_from.value == InvokeFrom.PUBLISHED.value:
  791. document_id = variable_pool.get(["sys", SystemVariableKey.DOCUMENT_ID])
  792. if document_id:
  793. document = db.session.query(Document).filter(Document.id == document_id.value).first()
  794. if document:
  795. document.indexing_status = "error"
  796. document.error = error
  797. db.session.add(document)
  798. db.session.commit()
  799. return workflow_node_execution
  800. def update_workflow(
  801. self, *, session: Session, workflow_id: str, tenant_id: str, account_id: str, data: dict
  802. ) -> Optional[Workflow]:
  803. """
  804. Update workflow attributes
  805. :param session: SQLAlchemy database session
  806. :param workflow_id: Workflow ID
  807. :param tenant_id: Tenant ID
  808. :param account_id: Account ID (for permission check)
  809. :param data: Dictionary containing fields to update
  810. :return: Updated workflow or None if not found
  811. """
  812. stmt = select(Workflow).where(Workflow.id == workflow_id, Workflow.tenant_id == tenant_id)
  813. workflow = session.scalar(stmt)
  814. if not workflow:
  815. return None
  816. allowed_fields = ["marked_name", "marked_comment"]
  817. for field, value in data.items():
  818. if field in allowed_fields:
  819. setattr(workflow, field, value)
  820. workflow.updated_by = account_id
  821. workflow.updated_at = datetime.now(UTC).replace(tzinfo=None)
  822. return workflow
  823. def get_first_step_parameters(self, pipeline: Pipeline, node_id: str, is_draft: bool = False) -> list[dict]:
  824. """
  825. Get first step parameters of rag pipeline
  826. """
  827. workflow = (
  828. self.get_draft_workflow(pipeline=pipeline) if is_draft else self.get_published_workflow(pipeline=pipeline)
  829. )
  830. if not workflow:
  831. raise ValueError("Workflow not initialized")
  832. datasource_node_data = None
  833. datasource_nodes = workflow.graph_dict.get("nodes", [])
  834. for datasource_node in datasource_nodes:
  835. if datasource_node.get("id") == node_id:
  836. datasource_node_data = datasource_node.get("data", {})
  837. break
  838. if not datasource_node_data:
  839. raise ValueError("Datasource node data not found")
  840. variables = workflow.rag_pipeline_variables
  841. if variables:
  842. variables_map = {item["variable"]: item for item in variables}
  843. else:
  844. return []
  845. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  846. user_input_variables = []
  847. for key, value in datasource_parameters.items():
  848. if value.get("value") and isinstance(value.get("value"), str):
  849. pattern = r"\{\{#([a-zA-Z0-9_]{1,50}(?:\.[a-zA-Z0-9_][a-zA-Z0-9_]{0,29}){1,10})#\}\}"
  850. match = re.match(pattern, value["value"])
  851. if match:
  852. full_path = match.group(1)
  853. last_part = full_path.split(".")[-1]
  854. user_input_variables.append(variables_map.get(last_part, {}))
  855. return user_input_variables
  856. def get_second_step_parameters(self, pipeline: Pipeline, node_id: str, is_draft: bool = False) -> list[dict]:
  857. """
  858. Get second step parameters of rag pipeline
  859. """
  860. workflow = (
  861. self.get_draft_workflow(pipeline=pipeline) if is_draft else self.get_published_workflow(pipeline=pipeline)
  862. )
  863. if not workflow:
  864. raise ValueError("Workflow not initialized")
  865. # get second step node
  866. rag_pipeline_variables = workflow.rag_pipeline_variables
  867. if not rag_pipeline_variables:
  868. return []
  869. variables_map = {item["variable"]: item for item in rag_pipeline_variables}
  870. # get datasource node data
  871. datasource_node_data = None
  872. datasource_nodes = workflow.graph_dict.get("nodes", [])
  873. for datasource_node in datasource_nodes:
  874. if datasource_node.get("id") == node_id:
  875. datasource_node_data = datasource_node.get("data", {})
  876. break
  877. if datasource_node_data:
  878. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  879. for key, value in datasource_parameters.items():
  880. if value.get("value") and isinstance(value.get("value"), str):
  881. pattern = r"\{\{#([a-zA-Z0-9_]{1,50}(?:\.[a-zA-Z0-9_][a-zA-Z0-9_]{0,29}){1,10})#\}\}"
  882. match = re.match(pattern, value["value"])
  883. if match:
  884. full_path = match.group(1)
  885. last_part = full_path.split(".")[-1]
  886. variables_map.pop(last_part)
  887. all_second_step_variables = list(variables_map.values())
  888. datasource_provider_variables = [
  889. item
  890. for item in all_second_step_variables
  891. if item.get("belong_to_node_id") == node_id or item.get("belong_to_node_id") == "shared"
  892. ]
  893. return datasource_provider_variables
  894. def get_rag_pipeline_paginate_workflow_runs(self, pipeline: Pipeline, args: dict) -> InfiniteScrollPagination:
  895. """
  896. Get debug workflow run list
  897. Only return triggered_from == debugging
  898. :param app_model: app model
  899. :param args: request args
  900. """
  901. limit = int(args.get("limit", 20))
  902. base_query = db.session.query(WorkflowRun).filter(
  903. WorkflowRun.tenant_id == pipeline.tenant_id,
  904. WorkflowRun.app_id == pipeline.id,
  905. or_(
  906. WorkflowRun.triggered_from == WorkflowRunTriggeredFrom.RAG_PIPELINE_RUN.value,
  907. WorkflowRun.triggered_from == WorkflowRunTriggeredFrom.RAG_PIPELINE_DEBUGGING.value,
  908. ),
  909. )
  910. if args.get("last_id"):
  911. last_workflow_run = base_query.filter(
  912. WorkflowRun.id == args.get("last_id"),
  913. ).first()
  914. if not last_workflow_run:
  915. raise ValueError("Last workflow run not exists")
  916. workflow_runs = (
  917. base_query.filter(
  918. WorkflowRun.created_at < last_workflow_run.created_at, WorkflowRun.id != last_workflow_run.id
  919. )
  920. .order_by(WorkflowRun.created_at.desc())
  921. .limit(limit)
  922. .all()
  923. )
  924. else:
  925. workflow_runs = base_query.order_by(WorkflowRun.created_at.desc()).limit(limit).all()
  926. has_more = False
  927. if len(workflow_runs) == limit:
  928. current_page_first_workflow_run = workflow_runs[-1]
  929. rest_count = base_query.filter(
  930. WorkflowRun.created_at < current_page_first_workflow_run.created_at,
  931. WorkflowRun.id != current_page_first_workflow_run.id,
  932. ).count()
  933. if rest_count > 0:
  934. has_more = True
  935. return InfiniteScrollPagination(data=workflow_runs, limit=limit, has_more=has_more)
  936. def get_rag_pipeline_workflow_run(self, pipeline: Pipeline, run_id: str) -> Optional[WorkflowRun]:
  937. """
  938. Get workflow run detail
  939. :param app_model: app model
  940. :param run_id: workflow run id
  941. """
  942. workflow_run = (
  943. db.session.query(WorkflowRun)
  944. .filter(
  945. WorkflowRun.tenant_id == pipeline.tenant_id,
  946. WorkflowRun.app_id == pipeline.id,
  947. WorkflowRun.id == run_id,
  948. )
  949. .first()
  950. )
  951. return workflow_run
  952. def get_rag_pipeline_workflow_run_node_executions(
  953. self,
  954. pipeline: Pipeline,
  955. run_id: str,
  956. user: Account | EndUser,
  957. ) -> list[WorkflowNodeExecutionModel]:
  958. """
  959. Get workflow run node execution list
  960. """
  961. workflow_run = self.get_rag_pipeline_workflow_run(pipeline, run_id)
  962. contexts.plugin_tool_providers.set({})
  963. contexts.plugin_tool_providers_lock.set(threading.Lock())
  964. if not workflow_run:
  965. return []
  966. # Use the repository to get the node execution
  967. repository = SQLAlchemyWorkflowNodeExecutionRepository(
  968. session_factory=db.engine, app_id=pipeline.id, user=user, triggered_from=None
  969. )
  970. # Use the repository to get the node executions with ordering
  971. order_config = OrderConfig(order_by=["index"], order_direction="desc")
  972. node_executions = repository.get_db_models_by_workflow_run(
  973. workflow_run_id=run_id,
  974. order_config=order_config,
  975. triggered_from=WorkflowNodeExecutionTriggeredFrom.RAG_PIPELINE_RUN,
  976. )
  977. return list(node_executions)
  978. @classmethod
  979. def publish_customized_pipeline_template(cls, pipeline_id: str, args: dict):
  980. """
  981. Publish customized pipeline template
  982. """
  983. pipeline = db.session.query(Pipeline).filter(Pipeline.id == pipeline_id).first()
  984. if not pipeline:
  985. raise ValueError("Pipeline not found")
  986. if not pipeline.workflow_id:
  987. raise ValueError("Pipeline workflow not found")
  988. workflow = db.session.query(Workflow).filter(Workflow.id == pipeline.workflow_id).first()
  989. if not workflow:
  990. raise ValueError("Workflow not found")
  991. dataset = pipeline.dataset
  992. if not dataset:
  993. raise ValueError("Dataset not found")
  994. # check template name is exist
  995. template_name = args.get("name")
  996. if template_name:
  997. template = (
  998. db.session.query(PipelineCustomizedTemplate)
  999. .filter(
  1000. PipelineCustomizedTemplate.name == template_name,
  1001. PipelineCustomizedTemplate.tenant_id == pipeline.tenant_id,
  1002. )
  1003. .first()
  1004. )
  1005. if template:
  1006. raise ValueError("Template name is already exists")
  1007. max_position = (
  1008. db.session.query(func.max(PipelineCustomizedTemplate.position))
  1009. .filter(PipelineCustomizedTemplate.tenant_id == pipeline.tenant_id)
  1010. .scalar()
  1011. )
  1012. from services.rag_pipeline.rag_pipeline_dsl_service import RagPipelineDslService
  1013. dsl = RagPipelineDslService.export_rag_pipeline_dsl(pipeline=pipeline, include_secret=True)
  1014. pipeline_customized_template = PipelineCustomizedTemplate(
  1015. name=args.get("name"),
  1016. description=args.get("description"),
  1017. icon=args.get("icon_info"),
  1018. tenant_id=pipeline.tenant_id,
  1019. yaml_content=dsl,
  1020. position=max_position + 1 if max_position else 1,
  1021. chunk_structure=dataset.chunk_structure,
  1022. language="en-US",
  1023. created_by=current_user.id,
  1024. )
  1025. db.session.add(pipeline_customized_template)
  1026. db.session.commit()
  1027. def is_workflow_exist(self, pipeline: Pipeline) -> bool:
  1028. return (
  1029. db.session.query(Workflow)
  1030. .filter(
  1031. Workflow.tenant_id == pipeline.tenant_id,
  1032. Workflow.app_id == pipeline.id,
  1033. Workflow.version == Workflow.VERSION_DRAFT,
  1034. )
  1035. .count()
  1036. ) > 0
  1037. def get_node_last_run(
  1038. self, pipeline: Pipeline, workflow: Workflow, node_id: str
  1039. ) -> WorkflowNodeExecutionModel | None:
  1040. # TODO(QuantumGhost): This query is not fully covered by index.
  1041. criteria = (
  1042. WorkflowNodeExecutionModel.tenant_id == pipeline.tenant_id,
  1043. WorkflowNodeExecutionModel.app_id == pipeline.id,
  1044. WorkflowNodeExecutionModel.workflow_id == workflow.id,
  1045. WorkflowNodeExecutionModel.node_id == node_id,
  1046. )
  1047. node_exec = (
  1048. db.session.query(WorkflowNodeExecutionModel)
  1049. .filter(*criteria)
  1050. .order_by(WorkflowNodeExecutionModel.created_at.desc())
  1051. .first()
  1052. )
  1053. return node_exec
  1054. def set_datasource_variables(self, pipeline: Pipeline, args: dict, current_user: Account | EndUser):
  1055. """
  1056. Set datasource variables
  1057. """
  1058. # fetch draft workflow by app_model
  1059. draft_workflow = self.get_draft_workflow(pipeline=pipeline)
  1060. if not draft_workflow:
  1061. raise ValueError("Workflow not initialized")
  1062. # run draft workflow node
  1063. start_at = time.perf_counter()
  1064. node_id = args.get("start_node_id")
  1065. if not node_id:
  1066. raise ValueError("Node id is required")
  1067. node_config = draft_workflow.get_node_config_by_id(node_id)
  1068. eclosing_node_type_and_id = draft_workflow.get_enclosing_node_type_and_id(node_config)
  1069. if eclosing_node_type_and_id:
  1070. _, enclosing_node_id = eclosing_node_type_and_id
  1071. else:
  1072. enclosing_node_id = None
  1073. system_inputs = SystemVariable(
  1074. datasource_type=args.get("datasource_type", "online_document"),
  1075. datasource_info=args.get("datasource_info", {}),
  1076. )
  1077. workflow_node_execution = self._handle_node_run_result(
  1078. getter=lambda: WorkflowEntry.single_step_run(
  1079. workflow=draft_workflow,
  1080. node_id=node_id,
  1081. user_inputs={},
  1082. user_id=current_user.id,
  1083. variable_pool=VariablePool(
  1084. system_variables=system_inputs,
  1085. user_inputs={},
  1086. environment_variables=[],
  1087. conversation_variables=[],
  1088. rag_pipeline_variables=[],
  1089. ),
  1090. variable_loader=DraftVarLoader(
  1091. engine=db.engine,
  1092. app_id=pipeline.id,
  1093. tenant_id=pipeline.tenant_id,
  1094. ),
  1095. ),
  1096. start_at=start_at,
  1097. tenant_id=pipeline.tenant_id,
  1098. node_id=node_id,
  1099. )
  1100. workflow_node_execution.workflow_id = draft_workflow.id
  1101. # Create repository and save the node execution
  1102. repository = SQLAlchemyWorkflowNodeExecutionRepository(
  1103. session_factory=db.engine,
  1104. user=current_user,
  1105. app_id=pipeline.id,
  1106. triggered_from=WorkflowNodeExecutionTriggeredFrom.SINGLE_STEP,
  1107. )
  1108. repository.save(workflow_node_execution)
  1109. # Convert node_execution to WorkflowNodeExecution after save
  1110. workflow_node_execution_db_model = repository.to_db_model(workflow_node_execution)
  1111. with Session(bind=db.engine) as session, session.begin():
  1112. draft_var_saver = DraftVariableSaver(
  1113. session=session,
  1114. app_id=pipeline.id,
  1115. node_id=workflow_node_execution_db_model.node_id,
  1116. node_type=NodeType(workflow_node_execution_db_model.node_type),
  1117. enclosing_node_id=enclosing_node_id,
  1118. node_execution_id=workflow_node_execution.id,
  1119. )
  1120. draft_var_saver.save(
  1121. process_data=workflow_node_execution.process_data,
  1122. outputs=workflow_node_execution.outputs,
  1123. )
  1124. session.commit()
  1125. return workflow_node_execution_db_model
  1126. def get_recommended_plugins(self) -> list[dict]:
  1127. # Query active recommended plugins
  1128. pipeline_recommended_plugins = (
  1129. db.session.query(PipelineRecommendedPlugin)
  1130. .filter(PipelineRecommendedPlugin.active == True)
  1131. .order_by(PipelineRecommendedPlugin.position.asc())
  1132. .all()
  1133. )
  1134. if not pipeline_recommended_plugins:
  1135. return []
  1136. # Batch fetch plugin manifests
  1137. plugin_ids = [plugin.plugin_id for plugin in pipeline_recommended_plugins]
  1138. plugin_manifests = marketplace.batch_fetch_plugin_manifests(plugin_ids)
  1139. builtin_tools = BuiltinToolManageService.list_builtin_tools(
  1140. user_id=current_user.id,
  1141. tenant_id=current_user.current_tenant_id,
  1142. )
  1143. installed_plugin_ids = {tool.plugin_id for tool in builtin_tools}
  1144. # Build recommended plugins list
  1145. return [
  1146. {
  1147. "plugin_id": manifest.plugin_id,
  1148. "name": manifest.name,
  1149. "icon": manifest.icon,
  1150. "plugin_unique_identifier": manifest.latest_package_identifier,
  1151. "installed": manifest.plugin_id in installed_plugin_ids,
  1152. }
  1153. for manifest in plugin_manifests
  1154. ]