Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

rag_pipeline.py 54KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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(
  415. workflow_node_execution.id
  416. )
  417. with Session(bind=db.engine) as session, session.begin():
  418. draft_var_saver = DraftVariableSaver(
  419. session=session,
  420. app_id=pipeline.id,
  421. node_id=workflow_node_execution.node_id,
  422. node_type=NodeType(workflow_node_execution.node_type),
  423. enclosing_node_id=enclosing_node_id,
  424. node_execution_id=workflow_node_execution.id,
  425. user=account,
  426. )
  427. draft_var_saver.save(
  428. process_data=workflow_node_execution.process_data,
  429. outputs=workflow_node_execution.outputs,
  430. )
  431. session.commit()
  432. return workflow_node_execution_db_model
  433. def run_datasource_workflow_node(
  434. self,
  435. pipeline: Pipeline,
  436. node_id: str,
  437. user_inputs: dict,
  438. account: Account,
  439. datasource_type: str,
  440. is_published: bool,
  441. credential_id: Optional[str] = None,
  442. ) -> Generator[Mapping[str, Any], None, None]:
  443. """
  444. Run published workflow datasource
  445. """
  446. try:
  447. if is_published:
  448. # fetch published workflow by app_model
  449. workflow = self.get_published_workflow(pipeline=pipeline)
  450. else:
  451. workflow = self.get_draft_workflow(pipeline=pipeline)
  452. if not workflow:
  453. raise ValueError("Workflow not initialized")
  454. # run draft workflow node
  455. datasource_node_data = None
  456. datasource_nodes = workflow.graph_dict.get("nodes", [])
  457. for datasource_node in datasource_nodes:
  458. if datasource_node.get("id") == node_id:
  459. datasource_node_data = datasource_node.get("data", {})
  460. break
  461. if not datasource_node_data:
  462. raise ValueError("Datasource node data not found")
  463. variables_map = {}
  464. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  465. for key, value in datasource_parameters.items():
  466. param_value = value.get("value")
  467. if not param_value:
  468. variables_map[key] = param_value
  469. elif isinstance(param_value, str):
  470. # handle string type parameter value, check if it contains variable reference pattern
  471. pattern = r"\{\{#([a-zA-Z0-9_]{1,50}(?:\.[a-zA-Z0-9_][a-zA-Z0-9_]{0,29}){1,10})#\}\}"
  472. match = re.match(pattern, param_value)
  473. if match:
  474. # extract variable path and try to get value from user inputs
  475. full_path = match.group(1)
  476. last_part = full_path.split(".")[-1]
  477. variables_map[key] = user_inputs.get(last_part, param_value)
  478. else:
  479. variables_map[key] = param_value
  480. elif isinstance(param_value, list) and param_value:
  481. # handle list type parameter value, check if the last element is in user inputs
  482. last_part = param_value[-1]
  483. variables_map[key] = user_inputs.get(last_part, param_value)
  484. else:
  485. # other type directly use original value
  486. variables_map[key] = param_value
  487. from core.datasource.datasource_manager import DatasourceManager
  488. datasource_runtime = DatasourceManager.get_datasource_runtime(
  489. provider_id=f"{datasource_node_data.get('plugin_id')}/{datasource_node_data.get('provider_name')}",
  490. datasource_name=datasource_node_data.get("datasource_name"),
  491. tenant_id=pipeline.tenant_id,
  492. datasource_type=DatasourceProviderType(datasource_type),
  493. )
  494. datasource_provider_service = DatasourceProviderService()
  495. credentials = datasource_provider_service.get_datasource_credentials(
  496. tenant_id=pipeline.tenant_id,
  497. provider=datasource_node_data.get("provider_name"),
  498. plugin_id=datasource_node_data.get("plugin_id"),
  499. credential_id=credential_id,
  500. )
  501. if credentials:
  502. datasource_runtime.runtime.credentials = credentials
  503. match datasource_type:
  504. case DatasourceProviderType.ONLINE_DOCUMENT:
  505. datasource_runtime = cast(OnlineDocumentDatasourcePlugin, datasource_runtime)
  506. online_document_result: Generator[OnlineDocumentPagesMessage, None, None] = (
  507. datasource_runtime.get_online_document_pages(
  508. user_id=account.id,
  509. datasource_parameters=user_inputs,
  510. provider_type=datasource_runtime.datasource_provider_type(),
  511. )
  512. )
  513. start_time = time.time()
  514. start_event = DatasourceProcessingEvent(
  515. total=0,
  516. completed=0,
  517. )
  518. yield start_event.model_dump()
  519. try:
  520. for message in online_document_result:
  521. end_time = time.time()
  522. online_document_event = DatasourceCompletedEvent(
  523. data=message.result, time_consuming=round(end_time - start_time, 2)
  524. )
  525. yield online_document_event.model_dump()
  526. except Exception as e:
  527. logger.exception("Error during online document.")
  528. yield DatasourceErrorEvent(error=str(e)).model_dump()
  529. case DatasourceProviderType.ONLINE_DRIVE:
  530. datasource_runtime = cast(OnlineDriveDatasourcePlugin, datasource_runtime)
  531. online_drive_result: Generator[OnlineDriveBrowseFilesResponse, None, None] = (
  532. datasource_runtime.online_drive_browse_files(
  533. user_id=account.id,
  534. request=OnlineDriveBrowseFilesRequest(
  535. bucket=user_inputs.get("bucket"),
  536. prefix=user_inputs.get("prefix", ""),
  537. max_keys=user_inputs.get("max_keys", 20),
  538. next_page_parameters=user_inputs.get("next_page_parameters"),
  539. ),
  540. provider_type=datasource_runtime.datasource_provider_type(),
  541. )
  542. )
  543. start_time = time.time()
  544. start_event = DatasourceProcessingEvent(
  545. total=0,
  546. completed=0,
  547. )
  548. yield start_event.model_dump()
  549. for message in online_drive_result:
  550. end_time = time.time()
  551. online_drive_event = DatasourceCompletedEvent(
  552. data=message.result,
  553. time_consuming=round(end_time - start_time, 2),
  554. total=None,
  555. completed=None,
  556. )
  557. yield online_drive_event.model_dump()
  558. case DatasourceProviderType.WEBSITE_CRAWL:
  559. datasource_runtime = cast(WebsiteCrawlDatasourcePlugin, datasource_runtime)
  560. website_crawl_result: Generator[WebsiteCrawlMessage, None, None] = (
  561. datasource_runtime.get_website_crawl(
  562. user_id=account.id,
  563. datasource_parameters=variables_map,
  564. provider_type=datasource_runtime.datasource_provider_type(),
  565. )
  566. )
  567. start_time = time.time()
  568. try:
  569. for message in website_crawl_result:
  570. end_time = time.time()
  571. if message.result.status == "completed":
  572. crawl_event = DatasourceCompletedEvent(
  573. data=message.result.web_info_list or [],
  574. total=message.result.total,
  575. completed=message.result.completed,
  576. time_consuming=round(end_time - start_time, 2),
  577. )
  578. else:
  579. crawl_event = DatasourceProcessingEvent(
  580. total=message.result.total,
  581. completed=message.result.completed,
  582. )
  583. yield crawl_event.model_dump()
  584. except Exception as e:
  585. logger.exception("Error during website crawl.")
  586. yield DatasourceErrorEvent(error=str(e)).model_dump()
  587. case _:
  588. raise ValueError(f"Unsupported datasource provider: {datasource_runtime.datasource_provider_type}")
  589. except Exception as e:
  590. logger.exception("Error in run_datasource_workflow_node.")
  591. yield DatasourceErrorEvent(error=str(e)).model_dump()
  592. def run_datasource_node_preview(
  593. self,
  594. pipeline: Pipeline,
  595. node_id: str,
  596. user_inputs: dict,
  597. account: Account,
  598. datasource_type: str,
  599. is_published: bool,
  600. credential_id: Optional[str] = None,
  601. ) -> Mapping[str, Any]:
  602. """
  603. Run published workflow datasource
  604. """
  605. try:
  606. if is_published:
  607. # fetch published workflow by app_model
  608. workflow = self.get_published_workflow(pipeline=pipeline)
  609. else:
  610. workflow = self.get_draft_workflow(pipeline=pipeline)
  611. if not workflow:
  612. raise ValueError("Workflow not initialized")
  613. # run draft workflow node
  614. datasource_node_data = None
  615. datasource_nodes = workflow.graph_dict.get("nodes", [])
  616. for datasource_node in datasource_nodes:
  617. if datasource_node.get("id") == node_id:
  618. datasource_node_data = datasource_node.get("data", {})
  619. break
  620. if not datasource_node_data:
  621. raise ValueError("Datasource node data not found")
  622. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  623. for key, value in datasource_parameters.items():
  624. if not user_inputs.get(key):
  625. user_inputs[key] = value["value"]
  626. from core.datasource.datasource_manager import DatasourceManager
  627. datasource_runtime = DatasourceManager.get_datasource_runtime(
  628. provider_id=f"{datasource_node_data.get('plugin_id')}/{datasource_node_data.get('provider_name')}",
  629. datasource_name=datasource_node_data.get("datasource_name"),
  630. tenant_id=pipeline.tenant_id,
  631. datasource_type=DatasourceProviderType(datasource_type),
  632. )
  633. datasource_provider_service = DatasourceProviderService()
  634. credentials = datasource_provider_service.get_datasource_credentials(
  635. tenant_id=pipeline.tenant_id,
  636. provider=datasource_node_data.get("provider_name"),
  637. plugin_id=datasource_node_data.get("plugin_id"),
  638. credential_id=credential_id,
  639. )
  640. if credentials:
  641. datasource_runtime.runtime.credentials = credentials
  642. match datasource_type:
  643. case DatasourceProviderType.ONLINE_DOCUMENT:
  644. datasource_runtime = cast(OnlineDocumentDatasourcePlugin, datasource_runtime)
  645. online_document_result: Generator[DatasourceMessage, None, None] = (
  646. datasource_runtime.get_online_document_page_content(
  647. user_id=account.id,
  648. datasource_parameters=GetOnlineDocumentPageContentRequest(
  649. workspace_id=user_inputs.get("workspace_id", ""),
  650. page_id=user_inputs.get("page_id", ""),
  651. type=user_inputs.get("type", ""),
  652. ),
  653. provider_type=datasource_type,
  654. )
  655. )
  656. try:
  657. variables: dict[str, Any] = {}
  658. for message in online_document_result:
  659. if message.type == DatasourceMessage.MessageType.VARIABLE:
  660. assert isinstance(message.message, DatasourceMessage.VariableMessage)
  661. variable_name = message.message.variable_name
  662. variable_value = message.message.variable_value
  663. if message.message.stream:
  664. if not isinstance(variable_value, str):
  665. raise ValueError("When 'stream' is True, 'variable_value' must be a string.")
  666. if variable_name not in variables:
  667. variables[variable_name] = ""
  668. variables[variable_name] += variable_value
  669. else:
  670. variables[variable_name] = variable_value
  671. return variables
  672. except Exception as e:
  673. logger.exception("Error during get online document content.")
  674. raise RuntimeError(str(e))
  675. # TODO Online Drive
  676. case _:
  677. raise ValueError(f"Unsupported datasource provider: {datasource_runtime.datasource_provider_type}")
  678. except Exception as e:
  679. logger.exception("Error in run_datasource_node_preview.")
  680. raise RuntimeError(str(e))
  681. def run_free_workflow_node(
  682. self, node_data: dict, tenant_id: str, user_id: str, node_id: str, user_inputs: dict[str, Any]
  683. ) -> WorkflowNodeExecution:
  684. """
  685. Run draft workflow node
  686. """
  687. # run draft workflow node
  688. start_at = time.perf_counter()
  689. workflow_node_execution = self._handle_node_run_result(
  690. getter=lambda: WorkflowEntry.run_free_node(
  691. node_id=node_id,
  692. node_data=node_data,
  693. tenant_id=tenant_id,
  694. user_id=user_id,
  695. user_inputs=user_inputs,
  696. ),
  697. start_at=start_at,
  698. tenant_id=tenant_id,
  699. node_id=node_id,
  700. )
  701. return workflow_node_execution
  702. def _handle_node_run_result(
  703. self,
  704. getter: Callable[[], tuple[Node, Generator[GraphNodeEventBase, None, None]]],
  705. start_at: float,
  706. tenant_id: str,
  707. node_id: str,
  708. ) -> WorkflowNodeExecution:
  709. """
  710. Handle node run result
  711. :param getter: Callable[[], tuple[BaseNode, Generator[RunEvent | InNodeEvent, None, None]]]
  712. :param start_at: float
  713. :param tenant_id: str
  714. :param node_id: str
  715. """
  716. try:
  717. node_instance, generator = getter()
  718. node_run_result: NodeRunResult | None = None
  719. for event in generator:
  720. if isinstance(event, (NodeRunSucceededEvent, NodeRunFailedEvent)):
  721. node_run_result = event.node_run_result
  722. # sign output files
  723. node_run_result.outputs = WorkflowEntry.handle_special_values(node_run_result.outputs) or {}
  724. break
  725. if not node_run_result:
  726. raise ValueError("Node run failed with no run result")
  727. # single step debug mode error handling return
  728. if node_run_result.status == WorkflowNodeExecutionStatus.FAILED and node_instance.error_strategy:
  729. node_error_args: dict[str, Any] = {
  730. "status": WorkflowNodeExecutionStatus.EXCEPTION,
  731. "error": node_run_result.error,
  732. "inputs": node_run_result.inputs,
  733. "metadata": {"error_strategy": node_instance.error_strategy},
  734. }
  735. if node_instance.error_strategy is ErrorStrategy.DEFAULT_VALUE:
  736. node_run_result = NodeRunResult(
  737. **node_error_args,
  738. outputs={
  739. **node_instance.default_value_dict,
  740. "error_message": node_run_result.error,
  741. "error_type": node_run_result.error_type,
  742. },
  743. )
  744. else:
  745. node_run_result = NodeRunResult(
  746. **node_error_args,
  747. outputs={
  748. "error_message": node_run_result.error,
  749. "error_type": node_run_result.error_type,
  750. },
  751. )
  752. run_succeeded = node_run_result.status in (
  753. WorkflowNodeExecutionStatus.SUCCEEDED,
  754. WorkflowNodeExecutionStatus.EXCEPTION,
  755. )
  756. error = node_run_result.error if not run_succeeded else None
  757. except WorkflowNodeRunFailedError as e:
  758. node_instance = e._node
  759. run_succeeded = False
  760. node_run_result = None
  761. error = e._error
  762. workflow_node_execution = WorkflowNodeExecution(
  763. id=str(uuid4()),
  764. workflow_id=node_instance.workflow_id,
  765. index=1,
  766. node_id=node_id,
  767. node_type=node_instance.node_type,
  768. title=node_instance.title,
  769. elapsed_time=time.perf_counter() - start_at,
  770. finished_at=datetime.now(UTC).replace(tzinfo=None),
  771. created_at=datetime.now(UTC).replace(tzinfo=None),
  772. )
  773. if run_succeeded and node_run_result:
  774. # create workflow node execution
  775. inputs = WorkflowEntry.handle_special_values(node_run_result.inputs) if node_run_result.inputs else None
  776. process_data = (
  777. WorkflowEntry.handle_special_values(node_run_result.process_data)
  778. if node_run_result.process_data
  779. else None
  780. )
  781. outputs = WorkflowEntry.handle_special_values(node_run_result.outputs) if node_run_result.outputs else None
  782. workflow_node_execution.inputs = inputs
  783. workflow_node_execution.process_data = process_data
  784. workflow_node_execution.outputs = outputs
  785. workflow_node_execution.metadata = node_run_result.metadata
  786. if node_run_result.status == WorkflowNodeExecutionStatus.SUCCEEDED:
  787. workflow_node_execution.status = WorkflowNodeExecutionStatus.SUCCEEDED
  788. elif node_run_result.status == WorkflowNodeExecutionStatus.EXCEPTION:
  789. workflow_node_execution.status = WorkflowNodeExecutionStatus.EXCEPTION
  790. workflow_node_execution.error = node_run_result.error
  791. else:
  792. # create workflow node execution
  793. workflow_node_execution.status = WorkflowNodeExecutionStatus.FAILED
  794. workflow_node_execution.error = error
  795. # update document status
  796. variable_pool = node_instance.graph_runtime_state.variable_pool
  797. invoke_from = variable_pool.get(["sys", SystemVariableKey.INVOKE_FROM])
  798. if invoke_from:
  799. if invoke_from.value == InvokeFrom.PUBLISHED.value:
  800. document_id = variable_pool.get(["sys", SystemVariableKey.DOCUMENT_ID])
  801. if document_id:
  802. document = db.session.query(Document).filter(Document.id == document_id.value).first()
  803. if document:
  804. document.indexing_status = "error"
  805. document.error = error
  806. db.session.add(document)
  807. db.session.commit()
  808. return workflow_node_execution
  809. def update_workflow(
  810. self, *, session: Session, workflow_id: str, tenant_id: str, account_id: str, data: dict
  811. ) -> Optional[Workflow]:
  812. """
  813. Update workflow attributes
  814. :param session: SQLAlchemy database session
  815. :param workflow_id: Workflow ID
  816. :param tenant_id: Tenant ID
  817. :param account_id: Account ID (for permission check)
  818. :param data: Dictionary containing fields to update
  819. :return: Updated workflow or None if not found
  820. """
  821. stmt = select(Workflow).where(Workflow.id == workflow_id, Workflow.tenant_id == tenant_id)
  822. workflow = session.scalar(stmt)
  823. if not workflow:
  824. return None
  825. allowed_fields = ["marked_name", "marked_comment"]
  826. for field, value in data.items():
  827. if field in allowed_fields:
  828. setattr(workflow, field, value)
  829. workflow.updated_by = account_id
  830. workflow.updated_at = datetime.now(UTC).replace(tzinfo=None)
  831. return workflow
  832. def get_first_step_parameters(self, pipeline: Pipeline, node_id: str, is_draft: bool = False) -> list[dict]:
  833. """
  834. Get first step parameters of rag pipeline
  835. """
  836. workflow = (
  837. self.get_draft_workflow(pipeline=pipeline) if is_draft else self.get_published_workflow(pipeline=pipeline)
  838. )
  839. if not workflow:
  840. raise ValueError("Workflow not initialized")
  841. datasource_node_data = None
  842. datasource_nodes = workflow.graph_dict.get("nodes", [])
  843. for datasource_node in datasource_nodes:
  844. if datasource_node.get("id") == node_id:
  845. datasource_node_data = datasource_node.get("data", {})
  846. break
  847. if not datasource_node_data:
  848. raise ValueError("Datasource node data not found")
  849. variables = workflow.rag_pipeline_variables
  850. if variables:
  851. variables_map = {item["variable"]: item for item in variables}
  852. else:
  853. return []
  854. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  855. user_input_variables = []
  856. for key, value in datasource_parameters.items():
  857. if value.get("value") and isinstance(value.get("value"), str):
  858. pattern = r"\{\{#([a-zA-Z0-9_]{1,50}(?:\.[a-zA-Z0-9_][a-zA-Z0-9_]{0,29}){1,10})#\}\}"
  859. match = re.match(pattern, value["value"])
  860. if match:
  861. full_path = match.group(1)
  862. last_part = full_path.split(".")[-1]
  863. user_input_variables.append(variables_map.get(last_part, {}))
  864. elif value.get("value") and isinstance(value.get("value"), list):
  865. last_part = value.get("value")[-1]
  866. user_input_variables.append(variables_map.get(last_part, {}))
  867. return user_input_variables
  868. def get_second_step_parameters(self, pipeline: Pipeline, node_id: str, is_draft: bool = False) -> list[dict]:
  869. """
  870. Get second step parameters of rag pipeline
  871. """
  872. workflow = (
  873. self.get_draft_workflow(pipeline=pipeline) if is_draft else self.get_published_workflow(pipeline=pipeline)
  874. )
  875. if not workflow:
  876. raise ValueError("Workflow not initialized")
  877. # get second step node
  878. rag_pipeline_variables = workflow.rag_pipeline_variables
  879. if not rag_pipeline_variables:
  880. return []
  881. variables_map = {item["variable"]: item for item in rag_pipeline_variables}
  882. # get datasource node data
  883. datasource_node_data = None
  884. datasource_nodes = workflow.graph_dict.get("nodes", [])
  885. for datasource_node in datasource_nodes:
  886. if datasource_node.get("id") == node_id:
  887. datasource_node_data = datasource_node.get("data", {})
  888. break
  889. if datasource_node_data:
  890. datasource_parameters = datasource_node_data.get("datasource_parameters", {})
  891. for key, value in datasource_parameters.items():
  892. if value.get("value") and isinstance(value.get("value"), str):
  893. pattern = r"\{\{#([a-zA-Z0-9_]{1,50}(?:\.[a-zA-Z0-9_][a-zA-Z0-9_]{0,29}){1,10})#\}\}"
  894. match = re.match(pattern, value["value"])
  895. if match:
  896. full_path = match.group(1)
  897. last_part = full_path.split(".")[-1]
  898. variables_map.pop(last_part)
  899. elif value.get("value") and isinstance(value.get("value"), list):
  900. last_part = value.get("value")[-1]
  901. variables_map.pop(last_part)
  902. all_second_step_variables = list(variables_map.values())
  903. datasource_provider_variables = [
  904. item
  905. for item in all_second_step_variables
  906. if item.get("belong_to_node_id") == node_id or item.get("belong_to_node_id") == "shared"
  907. ]
  908. return datasource_provider_variables
  909. def get_rag_pipeline_paginate_workflow_runs(self, pipeline: Pipeline, args: dict) -> InfiniteScrollPagination:
  910. """
  911. Get debug workflow run list
  912. Only return triggered_from == debugging
  913. :param app_model: app model
  914. :param args: request args
  915. """
  916. limit = int(args.get("limit", 20))
  917. base_query = db.session.query(WorkflowRun).filter(
  918. WorkflowRun.tenant_id == pipeline.tenant_id,
  919. WorkflowRun.app_id == pipeline.id,
  920. or_(
  921. WorkflowRun.triggered_from == WorkflowRunTriggeredFrom.RAG_PIPELINE_RUN.value,
  922. WorkflowRun.triggered_from == WorkflowRunTriggeredFrom.RAG_PIPELINE_DEBUGGING.value,
  923. ),
  924. )
  925. if args.get("last_id"):
  926. last_workflow_run = base_query.filter(
  927. WorkflowRun.id == args.get("last_id"),
  928. ).first()
  929. if not last_workflow_run:
  930. raise ValueError("Last workflow run not exists")
  931. workflow_runs = (
  932. base_query.filter(
  933. WorkflowRun.created_at < last_workflow_run.created_at, WorkflowRun.id != last_workflow_run.id
  934. )
  935. .order_by(WorkflowRun.created_at.desc())
  936. .limit(limit)
  937. .all()
  938. )
  939. else:
  940. workflow_runs = base_query.order_by(WorkflowRun.created_at.desc()).limit(limit).all()
  941. has_more = False
  942. if len(workflow_runs) == limit:
  943. current_page_first_workflow_run = workflow_runs[-1]
  944. rest_count = base_query.filter(
  945. WorkflowRun.created_at < current_page_first_workflow_run.created_at,
  946. WorkflowRun.id != current_page_first_workflow_run.id,
  947. ).count()
  948. if rest_count > 0:
  949. has_more = True
  950. return InfiniteScrollPagination(data=workflow_runs, limit=limit, has_more=has_more)
  951. def get_rag_pipeline_workflow_run(self, pipeline: Pipeline, run_id: str) -> Optional[WorkflowRun]:
  952. """
  953. Get workflow run detail
  954. :param app_model: app model
  955. :param run_id: workflow run id
  956. """
  957. workflow_run = (
  958. db.session.query(WorkflowRun)
  959. .filter(
  960. WorkflowRun.tenant_id == pipeline.tenant_id,
  961. WorkflowRun.app_id == pipeline.id,
  962. WorkflowRun.id == run_id,
  963. )
  964. .first()
  965. )
  966. return workflow_run
  967. def get_rag_pipeline_workflow_run_node_executions(
  968. self,
  969. pipeline: Pipeline,
  970. run_id: str,
  971. user: Account | EndUser,
  972. ) -> list[WorkflowNodeExecutionModel]:
  973. """
  974. Get workflow run node execution list
  975. """
  976. workflow_run = self.get_rag_pipeline_workflow_run(pipeline, run_id)
  977. contexts.plugin_tool_providers.set({})
  978. contexts.plugin_tool_providers_lock.set(threading.Lock())
  979. if not workflow_run:
  980. return []
  981. # Use the repository to get the node execution
  982. repository = SQLAlchemyWorkflowNodeExecutionRepository(
  983. session_factory=db.engine, app_id=pipeline.id, user=user, triggered_from=None
  984. )
  985. # Use the repository to get the node executions with ordering
  986. order_config = OrderConfig(order_by=["created_at"], order_direction="asc")
  987. node_executions = repository.get_db_models_by_workflow_run(
  988. workflow_run_id=run_id,
  989. order_config=order_config,
  990. triggered_from=WorkflowNodeExecutionTriggeredFrom.RAG_PIPELINE_RUN,
  991. )
  992. return list(node_executions)
  993. @classmethod
  994. def publish_customized_pipeline_template(cls, pipeline_id: str, args: dict):
  995. """
  996. Publish customized pipeline template
  997. """
  998. pipeline = db.session.query(Pipeline).filter(Pipeline.id == pipeline_id).first()
  999. if not pipeline:
  1000. raise ValueError("Pipeline not found")
  1001. if not pipeline.workflow_id:
  1002. raise ValueError("Pipeline workflow not found")
  1003. workflow = db.session.query(Workflow).filter(Workflow.id == pipeline.workflow_id).first()
  1004. if not workflow:
  1005. raise ValueError("Workflow not found")
  1006. dataset = pipeline.dataset
  1007. if not dataset:
  1008. raise ValueError("Dataset not found")
  1009. # check template name is exist
  1010. template_name = args.get("name")
  1011. if template_name:
  1012. template = (
  1013. db.session.query(PipelineCustomizedTemplate)
  1014. .filter(
  1015. PipelineCustomizedTemplate.name == template_name,
  1016. PipelineCustomizedTemplate.tenant_id == pipeline.tenant_id,
  1017. )
  1018. .first()
  1019. )
  1020. if template:
  1021. raise ValueError("Template name is already exists")
  1022. max_position = (
  1023. db.session.query(func.max(PipelineCustomizedTemplate.position))
  1024. .filter(PipelineCustomizedTemplate.tenant_id == pipeline.tenant_id)
  1025. .scalar()
  1026. )
  1027. from services.rag_pipeline.rag_pipeline_dsl_service import RagPipelineDslService
  1028. dsl = RagPipelineDslService.export_rag_pipeline_dsl(pipeline=pipeline, include_secret=True)
  1029. pipeline_customized_template = PipelineCustomizedTemplate(
  1030. name=args.get("name"),
  1031. description=args.get("description"),
  1032. icon=args.get("icon_info"),
  1033. tenant_id=pipeline.tenant_id,
  1034. yaml_content=dsl,
  1035. position=max_position + 1 if max_position else 1,
  1036. chunk_structure=dataset.chunk_structure,
  1037. language="en-US",
  1038. created_by=current_user.id,
  1039. )
  1040. db.session.add(pipeline_customized_template)
  1041. db.session.commit()
  1042. def is_workflow_exist(self, pipeline: Pipeline) -> bool:
  1043. return (
  1044. db.session.query(Workflow)
  1045. .filter(
  1046. Workflow.tenant_id == pipeline.tenant_id,
  1047. Workflow.app_id == pipeline.id,
  1048. Workflow.version == Workflow.VERSION_DRAFT,
  1049. )
  1050. .count()
  1051. ) > 0
  1052. def get_node_last_run(
  1053. self, pipeline: Pipeline, workflow: Workflow, node_id: str
  1054. ) -> WorkflowNodeExecutionModel | None:
  1055. node_execution_service_repo = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(
  1056. sessionmaker(db.engine)
  1057. )
  1058. node_exec = node_execution_service_repo.get_node_last_execution(
  1059. tenant_id=pipeline.tenant_id,
  1060. app_id=pipeline.id,
  1061. workflow_id=workflow.id,
  1062. node_id=node_id,
  1063. )
  1064. return node_exec
  1065. def set_datasource_variables(self, pipeline: Pipeline, args: dict, current_user: Account):
  1066. """
  1067. Set datasource variables
  1068. """
  1069. # fetch draft workflow by app_model
  1070. draft_workflow = self.get_draft_workflow(pipeline=pipeline)
  1071. if not draft_workflow:
  1072. raise ValueError("Workflow not initialized")
  1073. # run draft workflow node
  1074. start_at = time.perf_counter()
  1075. node_id = args.get("start_node_id")
  1076. if not node_id:
  1077. raise ValueError("Node id is required")
  1078. node_config = draft_workflow.get_node_config_by_id(node_id)
  1079. eclosing_node_type_and_id = draft_workflow.get_enclosing_node_type_and_id(node_config)
  1080. if eclosing_node_type_and_id:
  1081. _, enclosing_node_id = eclosing_node_type_and_id
  1082. else:
  1083. enclosing_node_id = None
  1084. system_inputs = SystemVariable(
  1085. datasource_type=args.get("datasource_type", "online_document"),
  1086. datasource_info=args.get("datasource_info", {}),
  1087. )
  1088. workflow_node_execution = self._handle_node_run_result(
  1089. getter=lambda: WorkflowEntry.single_step_run(
  1090. workflow=draft_workflow,
  1091. node_id=node_id,
  1092. user_inputs={},
  1093. user_id=current_user.id,
  1094. variable_pool=VariablePool(
  1095. system_variables=system_inputs,
  1096. user_inputs={},
  1097. environment_variables=[],
  1098. conversation_variables=[],
  1099. rag_pipeline_variables=[],
  1100. ),
  1101. variable_loader=DraftVarLoader(
  1102. engine=db.engine,
  1103. app_id=pipeline.id,
  1104. tenant_id=pipeline.tenant_id,
  1105. ),
  1106. ),
  1107. start_at=start_at,
  1108. tenant_id=pipeline.tenant_id,
  1109. node_id=node_id,
  1110. )
  1111. workflow_node_execution.workflow_id = draft_workflow.id
  1112. # Create repository and save the node execution
  1113. repository = SQLAlchemyWorkflowNodeExecutionRepository(
  1114. session_factory=db.engine,
  1115. user=current_user,
  1116. app_id=pipeline.id,
  1117. triggered_from=WorkflowNodeExecutionTriggeredFrom.SINGLE_STEP,
  1118. )
  1119. repository.save(workflow_node_execution)
  1120. # Convert node_execution to WorkflowNodeExecution after save
  1121. workflow_node_execution_db_model = repository._to_db_model(workflow_node_execution)
  1122. with Session(bind=db.engine) as session, session.begin():
  1123. draft_var_saver = DraftVariableSaver(
  1124. session=session,
  1125. app_id=pipeline.id,
  1126. node_id=workflow_node_execution_db_model.node_id,
  1127. node_type=NodeType(workflow_node_execution_db_model.node_type),
  1128. enclosing_node_id=enclosing_node_id,
  1129. node_execution_id=workflow_node_execution.id,
  1130. user=current_user,
  1131. )
  1132. draft_var_saver.save(
  1133. process_data=workflow_node_execution.process_data,
  1134. outputs=workflow_node_execution.outputs,
  1135. )
  1136. session.commit()
  1137. return workflow_node_execution_db_model
  1138. def get_recommended_plugins(self) -> dict:
  1139. # Query active recommended plugins
  1140. pipeline_recommended_plugins = (
  1141. db.session.query(PipelineRecommendedPlugin)
  1142. .filter(PipelineRecommendedPlugin.active == True)
  1143. .order_by(PipelineRecommendedPlugin.position.asc())
  1144. .all()
  1145. )
  1146. if not pipeline_recommended_plugins:
  1147. return {
  1148. "installed_recommended_plugins": [],
  1149. "uninstalled_recommended_plugins": [],
  1150. }
  1151. # Batch fetch plugin manifests
  1152. plugin_ids = [plugin.plugin_id for plugin in pipeline_recommended_plugins]
  1153. providers = BuiltinToolManageService.list_builtin_tools(
  1154. user_id=current_user.id,
  1155. tenant_id=current_user.current_tenant_id,
  1156. )
  1157. providers_map = {provider.plugin_id: provider.to_dict() for provider in providers}
  1158. plugin_manifests = marketplace.batch_fetch_plugin_manifests(plugin_ids)
  1159. plugin_manifests_map = {manifest.plugin_id: manifest for manifest in plugin_manifests}
  1160. installed_plugin_list = []
  1161. uninstalled_plugin_list = []
  1162. for plugin_id in plugin_ids:
  1163. if providers_map.get(plugin_id):
  1164. installed_plugin_list.append(providers_map.get(plugin_id))
  1165. else:
  1166. plugin_manifest = plugin_manifests_map.get(plugin_id)
  1167. if plugin_manifest:
  1168. uninstalled_plugin_list.append(
  1169. {
  1170. "plugin_id": plugin_id,
  1171. "name": plugin_manifest.name,
  1172. "icon": plugin_manifest.icon,
  1173. "plugin_unique_identifier": plugin_manifest.latest_package_identifier,
  1174. }
  1175. )
  1176. # Build recommended plugins list
  1177. return {
  1178. "installed_recommended_plugins": installed_plugin_list,
  1179. "uninstalled_recommended_plugins": uninstalled_plugin_list,
  1180. }