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.

workflow_service.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. import json
  2. import time
  3. import uuid
  4. from collections.abc import Callable, Generator, Mapping, Sequence
  5. from typing import Any, Optional, cast
  6. from uuid import uuid4
  7. from sqlalchemy import select
  8. from sqlalchemy.orm import Session, sessionmaker
  9. from core.app.app_config.entities import VariableEntityType
  10. from core.app.apps.advanced_chat.app_config_manager import AdvancedChatAppConfigManager
  11. from core.app.apps.workflow.app_config_manager import WorkflowAppConfigManager
  12. from core.file import File
  13. from core.repositories import DifyCoreRepositoryFactory
  14. from core.variables import Variable
  15. from core.variables.variables import VariableUnion
  16. from core.workflow.entities.node_entities import NodeRunResult
  17. from core.workflow.entities.variable_pool import VariablePool
  18. from core.workflow.entities.workflow_node_execution import WorkflowNodeExecution, WorkflowNodeExecutionStatus
  19. from core.workflow.errors import WorkflowNodeRunFailedError
  20. from core.workflow.graph_engine.entities.event import InNodeEvent
  21. from core.workflow.nodes import NodeType
  22. from core.workflow.nodes.base.node import BaseNode
  23. from core.workflow.nodes.enums import ErrorStrategy
  24. from core.workflow.nodes.event import RunCompletedEvent
  25. from core.workflow.nodes.event.types import NodeEvent
  26. from core.workflow.nodes.node_mapping import LATEST_VERSION, NODE_TYPE_CLASSES_MAPPING
  27. from core.workflow.nodes.start.entities import StartNodeData
  28. from core.workflow.system_variable import SystemVariable
  29. from core.workflow.workflow_entry import WorkflowEntry
  30. from events.app_event import app_draft_workflow_was_synced, app_published_workflow_was_updated
  31. from extensions.ext_database import db
  32. from factories.file_factory import build_from_mapping, build_from_mappings
  33. from libs.datetime_utils import naive_utc_now
  34. from models.account import Account
  35. from models.model import App, AppMode
  36. from models.tools import WorkflowToolProvider
  37. from models.workflow import (
  38. Workflow,
  39. WorkflowNodeExecutionModel,
  40. WorkflowNodeExecutionTriggeredFrom,
  41. WorkflowType,
  42. )
  43. from repositories.factory import DifyAPIRepositoryFactory
  44. from services.errors.app import IsDraftWorkflowError, WorkflowHashNotEqualError
  45. from services.workflow.workflow_converter import WorkflowConverter
  46. from .errors.workflow_service import DraftWorkflowDeletionError, WorkflowInUseError
  47. from .workflow_draft_variable_service import (
  48. DraftVariableSaver,
  49. DraftVarLoader,
  50. WorkflowDraftVariableService,
  51. )
  52. class WorkflowService:
  53. """
  54. Workflow Service
  55. """
  56. def __init__(self, session_maker: sessionmaker | None = None):
  57. """Initialize WorkflowService with repository dependencies."""
  58. if session_maker is None:
  59. session_maker = sessionmaker(bind=db.engine, expire_on_commit=False)
  60. self._node_execution_service_repo = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(
  61. session_maker
  62. )
  63. def get_node_last_run(self, app_model: App, workflow: Workflow, node_id: str) -> WorkflowNodeExecutionModel | None:
  64. """
  65. Get the most recent execution for a specific node.
  66. Args:
  67. app_model: The application model
  68. workflow: The workflow model
  69. node_id: The node identifier
  70. Returns:
  71. The most recent WorkflowNodeExecutionModel for the node, or None if not found
  72. """
  73. return self._node_execution_service_repo.get_node_last_execution(
  74. tenant_id=app_model.tenant_id,
  75. app_id=app_model.id,
  76. workflow_id=workflow.id,
  77. node_id=node_id,
  78. )
  79. def is_workflow_exist(self, app_model: App) -> bool:
  80. return (
  81. db.session.query(Workflow)
  82. .where(
  83. Workflow.tenant_id == app_model.tenant_id,
  84. Workflow.app_id == app_model.id,
  85. Workflow.version == Workflow.VERSION_DRAFT,
  86. )
  87. .count()
  88. ) > 0
  89. def get_draft_workflow(self, app_model: App) -> Optional[Workflow]:
  90. """
  91. Get draft workflow
  92. """
  93. # fetch draft workflow by app_model
  94. workflow = (
  95. db.session.query(Workflow)
  96. .where(
  97. Workflow.tenant_id == app_model.tenant_id,
  98. Workflow.app_id == app_model.id,
  99. Workflow.version == Workflow.VERSION_DRAFT,
  100. )
  101. .first()
  102. )
  103. # return draft workflow
  104. return workflow
  105. def get_published_workflow_by_id(self, app_model: App, workflow_id: str) -> Optional[Workflow]:
  106. # fetch published workflow by workflow_id
  107. workflow = (
  108. db.session.query(Workflow)
  109. .where(
  110. Workflow.tenant_id == app_model.tenant_id,
  111. Workflow.app_id == app_model.id,
  112. Workflow.id == workflow_id,
  113. )
  114. .first()
  115. )
  116. if not workflow:
  117. return None
  118. if workflow.version == Workflow.VERSION_DRAFT:
  119. raise IsDraftWorkflowError(f"Workflow is draft version, id={workflow_id}")
  120. return workflow
  121. def get_published_workflow(self, app_model: App) -> Optional[Workflow]:
  122. """
  123. Get published workflow
  124. """
  125. if not app_model.workflow_id:
  126. return None
  127. # fetch published workflow by workflow_id
  128. workflow = (
  129. db.session.query(Workflow)
  130. .where(
  131. Workflow.tenant_id == app_model.tenant_id,
  132. Workflow.app_id == app_model.id,
  133. Workflow.id == app_model.workflow_id,
  134. )
  135. .first()
  136. )
  137. return workflow
  138. def get_all_published_workflow(
  139. self,
  140. *,
  141. session: Session,
  142. app_model: App,
  143. page: int,
  144. limit: int,
  145. user_id: str | None,
  146. named_only: bool = False,
  147. ) -> tuple[Sequence[Workflow], bool]:
  148. """
  149. Get published workflow with pagination
  150. """
  151. if not app_model.workflow_id:
  152. return [], False
  153. stmt = (
  154. select(Workflow)
  155. .where(Workflow.app_id == app_model.id)
  156. .order_by(Workflow.version.desc())
  157. .limit(limit + 1)
  158. .offset((page - 1) * limit)
  159. )
  160. if user_id:
  161. stmt = stmt.where(Workflow.created_by == user_id)
  162. if named_only:
  163. stmt = stmt.where(Workflow.marked_name != "")
  164. workflows = session.scalars(stmt).all()
  165. has_more = len(workflows) > limit
  166. if has_more:
  167. workflows = workflows[:-1]
  168. return workflows, has_more
  169. def sync_draft_workflow(
  170. self,
  171. *,
  172. app_model: App,
  173. graph: dict,
  174. features: dict,
  175. unique_hash: Optional[str],
  176. account: Account,
  177. environment_variables: Sequence[Variable],
  178. conversation_variables: Sequence[Variable],
  179. ) -> Workflow:
  180. """
  181. Sync draft workflow
  182. :raises WorkflowHashNotEqualError
  183. """
  184. # fetch draft workflow by app_model
  185. workflow = self.get_draft_workflow(app_model=app_model)
  186. if workflow and workflow.unique_hash != unique_hash:
  187. raise WorkflowHashNotEqualError()
  188. # validate features structure
  189. self.validate_features_structure(app_model=app_model, features=features)
  190. # create draft workflow if not found
  191. if not workflow:
  192. workflow = Workflow(
  193. tenant_id=app_model.tenant_id,
  194. app_id=app_model.id,
  195. type=WorkflowType.from_app_mode(app_model.mode).value,
  196. version=Workflow.VERSION_DRAFT,
  197. graph=json.dumps(graph),
  198. features=json.dumps(features),
  199. created_by=account.id,
  200. environment_variables=environment_variables,
  201. conversation_variables=conversation_variables,
  202. )
  203. db.session.add(workflow)
  204. # update draft workflow if found
  205. else:
  206. workflow.graph = json.dumps(graph)
  207. workflow.features = json.dumps(features)
  208. workflow.updated_by = account.id
  209. workflow.updated_at = naive_utc_now()
  210. workflow.environment_variables = environment_variables
  211. workflow.conversation_variables = conversation_variables
  212. # commit db session changes
  213. db.session.commit()
  214. # trigger app workflow events
  215. app_draft_workflow_was_synced.send(app_model, synced_draft_workflow=workflow)
  216. # return draft workflow
  217. return workflow
  218. def publish_workflow(
  219. self,
  220. *,
  221. session: Session,
  222. app_model: App,
  223. account: Account,
  224. marked_name: str = "",
  225. marked_comment: str = "",
  226. ) -> Workflow:
  227. draft_workflow_stmt = select(Workflow).where(
  228. Workflow.tenant_id == app_model.tenant_id,
  229. Workflow.app_id == app_model.id,
  230. Workflow.version == Workflow.VERSION_DRAFT,
  231. )
  232. draft_workflow = session.scalar(draft_workflow_stmt)
  233. if not draft_workflow:
  234. raise ValueError("No valid workflow found.")
  235. # create new workflow
  236. workflow = Workflow.new(
  237. tenant_id=app_model.tenant_id,
  238. app_id=app_model.id,
  239. type=draft_workflow.type,
  240. version=Workflow.version_from_datetime(naive_utc_now()),
  241. graph=draft_workflow.graph,
  242. features=draft_workflow.features,
  243. created_by=account.id,
  244. environment_variables=draft_workflow.environment_variables,
  245. conversation_variables=draft_workflow.conversation_variables,
  246. marked_name=marked_name,
  247. marked_comment=marked_comment,
  248. )
  249. # commit db session changes
  250. session.add(workflow)
  251. # trigger app workflow events
  252. app_published_workflow_was_updated.send(app_model, published_workflow=workflow)
  253. # return new workflow
  254. return workflow
  255. def get_default_block_configs(self) -> list[dict]:
  256. """
  257. Get default block configs
  258. """
  259. # return default block config
  260. default_block_configs = []
  261. for node_class_mapping in NODE_TYPE_CLASSES_MAPPING.values():
  262. node_class = node_class_mapping[LATEST_VERSION]
  263. default_config = node_class.get_default_config()
  264. if default_config:
  265. default_block_configs.append(default_config)
  266. return default_block_configs
  267. def get_default_block_config(self, node_type: str, filters: Optional[dict] = None) -> Optional[dict]:
  268. """
  269. Get default config of node.
  270. :param node_type: node type
  271. :param filters: filter by node config parameters.
  272. :return:
  273. """
  274. node_type_enum = NodeType(node_type)
  275. # return default block config
  276. if node_type_enum not in NODE_TYPE_CLASSES_MAPPING:
  277. return None
  278. node_class = NODE_TYPE_CLASSES_MAPPING[node_type_enum][LATEST_VERSION]
  279. default_config = node_class.get_default_config(filters=filters)
  280. if not default_config:
  281. return None
  282. return default_config
  283. def run_draft_workflow_node(
  284. self,
  285. app_model: App,
  286. draft_workflow: Workflow,
  287. node_id: str,
  288. user_inputs: Mapping[str, Any],
  289. account: Account,
  290. query: str = "",
  291. files: Sequence[File] | None = None,
  292. ) -> WorkflowNodeExecutionModel:
  293. """
  294. Run draft workflow node
  295. """
  296. files = files or []
  297. with Session(bind=db.engine, expire_on_commit=False) as session, session.begin():
  298. draft_var_srv = WorkflowDraftVariableService(session)
  299. draft_var_srv.prefill_conversation_variable_default_values(draft_workflow)
  300. node_config = draft_workflow.get_node_config_by_id(node_id)
  301. node_type = Workflow.get_node_type_from_node_config(node_config)
  302. node_data = node_config.get("data", {})
  303. if node_type == NodeType.START:
  304. with Session(bind=db.engine) as session, session.begin():
  305. draft_var_srv = WorkflowDraftVariableService(session)
  306. conversation_id = draft_var_srv.get_or_create_conversation(
  307. account_id=account.id,
  308. app=app_model,
  309. workflow=draft_workflow,
  310. )
  311. start_data = StartNodeData.model_validate(node_data)
  312. user_inputs = _rebuild_file_for_user_inputs_in_start_node(
  313. tenant_id=draft_workflow.tenant_id, start_node_data=start_data, user_inputs=user_inputs
  314. )
  315. # init variable pool
  316. variable_pool = _setup_variable_pool(
  317. query=query,
  318. files=files or [],
  319. user_id=account.id,
  320. user_inputs=user_inputs,
  321. workflow=draft_workflow,
  322. # NOTE(QuantumGhost): We rely on `DraftVarLoader` to load conversation variables.
  323. conversation_variables=[],
  324. node_type=node_type,
  325. conversation_id=conversation_id,
  326. )
  327. else:
  328. variable_pool = VariablePool(
  329. system_variables=SystemVariable.empty(),
  330. user_inputs=user_inputs,
  331. environment_variables=draft_workflow.environment_variables,
  332. conversation_variables=[],
  333. )
  334. variable_loader = DraftVarLoader(
  335. engine=db.engine,
  336. app_id=app_model.id,
  337. tenant_id=app_model.tenant_id,
  338. )
  339. enclosing_node_type_and_id = draft_workflow.get_enclosing_node_type_and_id(node_config)
  340. if enclosing_node_type_and_id:
  341. _, enclosing_node_id = enclosing_node_type_and_id
  342. else:
  343. enclosing_node_id = None
  344. run = WorkflowEntry.single_step_run(
  345. workflow=draft_workflow,
  346. node_id=node_id,
  347. user_inputs=user_inputs,
  348. user_id=account.id,
  349. variable_pool=variable_pool,
  350. variable_loader=variable_loader,
  351. )
  352. # run draft workflow node
  353. start_at = time.perf_counter()
  354. node_execution = self._handle_node_run_result(
  355. invoke_node_fn=lambda: run,
  356. start_at=start_at,
  357. node_id=node_id,
  358. )
  359. # Set workflow_id on the NodeExecution
  360. node_execution.workflow_id = draft_workflow.id
  361. # Create repository and save the node execution
  362. repository = DifyCoreRepositoryFactory.create_workflow_node_execution_repository(
  363. session_factory=db.engine,
  364. user=account,
  365. app_id=app_model.id,
  366. triggered_from=WorkflowNodeExecutionTriggeredFrom.SINGLE_STEP,
  367. )
  368. repository.save(node_execution)
  369. workflow_node_execution = self._node_execution_service_repo.get_execution_by_id(node_execution.id)
  370. if workflow_node_execution is None:
  371. raise ValueError(f"WorkflowNodeExecution with id {node_execution.id} not found after saving")
  372. with Session(bind=db.engine) as session, session.begin():
  373. draft_var_saver = DraftVariableSaver(
  374. session=session,
  375. app_id=app_model.id,
  376. node_id=workflow_node_execution.node_id,
  377. node_type=NodeType(workflow_node_execution.node_type),
  378. enclosing_node_id=enclosing_node_id,
  379. node_execution_id=node_execution.id,
  380. )
  381. draft_var_saver.save(process_data=node_execution.process_data, outputs=node_execution.outputs)
  382. session.commit()
  383. return workflow_node_execution
  384. def run_free_workflow_node(
  385. self, node_data: dict, tenant_id: str, user_id: str, node_id: str, user_inputs: dict[str, Any]
  386. ) -> WorkflowNodeExecution:
  387. """
  388. Run draft workflow node
  389. """
  390. # run draft workflow node
  391. start_at = time.perf_counter()
  392. node_execution = self._handle_node_run_result(
  393. invoke_node_fn=lambda: WorkflowEntry.run_free_node(
  394. node_id=node_id,
  395. node_data=node_data,
  396. tenant_id=tenant_id,
  397. user_id=user_id,
  398. user_inputs=user_inputs,
  399. ),
  400. start_at=start_at,
  401. node_id=node_id,
  402. )
  403. return node_execution
  404. def _handle_node_run_result(
  405. self,
  406. invoke_node_fn: Callable[[], tuple[BaseNode, Generator[NodeEvent | InNodeEvent, None, None]]],
  407. start_at: float,
  408. node_id: str,
  409. ) -> WorkflowNodeExecution:
  410. try:
  411. node, node_events = invoke_node_fn()
  412. node_run_result: NodeRunResult | None = None
  413. for event in node_events:
  414. if isinstance(event, RunCompletedEvent):
  415. node_run_result = event.run_result
  416. # sign output files
  417. # node_run_result.outputs = WorkflowEntry.handle_special_values(node_run_result.outputs)
  418. break
  419. if not node_run_result:
  420. raise ValueError("Node run failed with no run result")
  421. # single step debug mode error handling return
  422. if node_run_result.status == WorkflowNodeExecutionStatus.FAILED and node.continue_on_error:
  423. node_error_args: dict[str, Any] = {
  424. "status": WorkflowNodeExecutionStatus.EXCEPTION,
  425. "error": node_run_result.error,
  426. "inputs": node_run_result.inputs,
  427. "metadata": {"error_strategy": node.error_strategy},
  428. }
  429. if node.error_strategy is ErrorStrategy.DEFAULT_VALUE:
  430. node_run_result = NodeRunResult(
  431. **node_error_args,
  432. outputs={
  433. **node.default_value_dict,
  434. "error_message": node_run_result.error,
  435. "error_type": node_run_result.error_type,
  436. },
  437. )
  438. else:
  439. node_run_result = NodeRunResult(
  440. **node_error_args,
  441. outputs={
  442. "error_message": node_run_result.error,
  443. "error_type": node_run_result.error_type,
  444. },
  445. )
  446. run_succeeded = node_run_result.status in (
  447. WorkflowNodeExecutionStatus.SUCCEEDED,
  448. WorkflowNodeExecutionStatus.EXCEPTION,
  449. )
  450. error = node_run_result.error if not run_succeeded else None
  451. except WorkflowNodeRunFailedError as e:
  452. node = e._node
  453. run_succeeded = False
  454. node_run_result = None
  455. error = e._error
  456. # Create a NodeExecution domain model
  457. node_execution = WorkflowNodeExecution(
  458. id=str(uuid4()),
  459. workflow_id="", # This is a single-step execution, so no workflow ID
  460. index=1,
  461. node_id=node_id,
  462. node_type=node.type_,
  463. title=node.title,
  464. elapsed_time=time.perf_counter() - start_at,
  465. created_at=naive_utc_now(),
  466. finished_at=naive_utc_now(),
  467. )
  468. if run_succeeded and node_run_result:
  469. # Set inputs, process_data, and outputs as dictionaries (not JSON strings)
  470. inputs = WorkflowEntry.handle_special_values(node_run_result.inputs) if node_run_result.inputs else None
  471. process_data = (
  472. WorkflowEntry.handle_special_values(node_run_result.process_data)
  473. if node_run_result.process_data
  474. else None
  475. )
  476. outputs = node_run_result.outputs
  477. node_execution.inputs = inputs
  478. node_execution.process_data = process_data
  479. node_execution.outputs = outputs
  480. node_execution.metadata = node_run_result.metadata
  481. # Map status from WorkflowNodeExecutionStatus to NodeExecutionStatus
  482. if node_run_result.status == WorkflowNodeExecutionStatus.SUCCEEDED:
  483. node_execution.status = WorkflowNodeExecutionStatus.SUCCEEDED
  484. elif node_run_result.status == WorkflowNodeExecutionStatus.EXCEPTION:
  485. node_execution.status = WorkflowNodeExecutionStatus.EXCEPTION
  486. node_execution.error = node_run_result.error
  487. else:
  488. # Set failed status and error
  489. node_execution.status = WorkflowNodeExecutionStatus.FAILED
  490. node_execution.error = error
  491. return node_execution
  492. def convert_to_workflow(self, app_model: App, account: Account, args: dict) -> App:
  493. """
  494. Basic mode of chatbot app(expert mode) to workflow
  495. Completion App to Workflow App
  496. :param app_model: App instance
  497. :param account: Account instance
  498. :param args: dict
  499. :return:
  500. """
  501. # chatbot convert to workflow mode
  502. workflow_converter = WorkflowConverter()
  503. if app_model.mode not in {AppMode.CHAT.value, AppMode.COMPLETION.value}:
  504. raise ValueError(f"Current App mode: {app_model.mode} is not supported convert to workflow.")
  505. # convert to workflow
  506. new_app: App = workflow_converter.convert_to_workflow(
  507. app_model=app_model,
  508. account=account,
  509. name=args.get("name", "Default Name"),
  510. icon_type=args.get("icon_type", "emoji"),
  511. icon=args.get("icon", "🤖"),
  512. icon_background=args.get("icon_background", "#FFEAD5"),
  513. )
  514. return new_app
  515. def validate_features_structure(self, app_model: App, features: dict) -> dict:
  516. if app_model.mode == AppMode.ADVANCED_CHAT.value:
  517. return AdvancedChatAppConfigManager.config_validate(
  518. tenant_id=app_model.tenant_id, config=features, only_structure_validate=True
  519. )
  520. elif app_model.mode == AppMode.WORKFLOW.value:
  521. return WorkflowAppConfigManager.config_validate(
  522. tenant_id=app_model.tenant_id, config=features, only_structure_validate=True
  523. )
  524. else:
  525. raise ValueError(f"Invalid app mode: {app_model.mode}")
  526. def update_workflow(
  527. self, *, session: Session, workflow_id: str, tenant_id: str, account_id: str, data: dict
  528. ) -> Optional[Workflow]:
  529. """
  530. Update workflow attributes
  531. :param session: SQLAlchemy database session
  532. :param workflow_id: Workflow ID
  533. :param tenant_id: Tenant ID
  534. :param account_id: Account ID (for permission check)
  535. :param data: Dictionary containing fields to update
  536. :return: Updated workflow or None if not found
  537. """
  538. stmt = select(Workflow).where(Workflow.id == workflow_id, Workflow.tenant_id == tenant_id)
  539. workflow = session.scalar(stmt)
  540. if not workflow:
  541. return None
  542. allowed_fields = ["marked_name", "marked_comment"]
  543. for field, value in data.items():
  544. if field in allowed_fields:
  545. setattr(workflow, field, value)
  546. workflow.updated_by = account_id
  547. workflow.updated_at = naive_utc_now()
  548. return workflow
  549. def delete_workflow(self, *, session: Session, workflow_id: str, tenant_id: str) -> bool:
  550. """
  551. Delete a workflow
  552. :param session: SQLAlchemy database session
  553. :param workflow_id: Workflow ID
  554. :param tenant_id: Tenant ID
  555. :return: True if successful
  556. :raises: ValueError if workflow not found
  557. :raises: WorkflowInUseError if workflow is in use
  558. :raises: DraftWorkflowDeletionError if workflow is a draft version
  559. """
  560. stmt = select(Workflow).where(Workflow.id == workflow_id, Workflow.tenant_id == tenant_id)
  561. workflow = session.scalar(stmt)
  562. if not workflow:
  563. raise ValueError(f"Workflow with ID {workflow_id} not found")
  564. # Check if workflow is a draft version
  565. if workflow.version == Workflow.VERSION_DRAFT:
  566. raise DraftWorkflowDeletionError("Cannot delete draft workflow versions")
  567. # Check if this workflow is currently referenced by an app
  568. app_stmt = select(App).where(App.workflow_id == workflow_id)
  569. app = session.scalar(app_stmt)
  570. if app:
  571. # Cannot delete a workflow that's currently in use by an app
  572. raise WorkflowInUseError(f"Cannot delete workflow that is currently in use by app '{app.id}'")
  573. # Don't use workflow.tool_published as it's not accurate for specific workflow versions
  574. # Check if there's a tool provider using this specific workflow version
  575. tool_provider = (
  576. session.query(WorkflowToolProvider)
  577. .where(
  578. WorkflowToolProvider.tenant_id == workflow.tenant_id,
  579. WorkflowToolProvider.app_id == workflow.app_id,
  580. WorkflowToolProvider.version == workflow.version,
  581. )
  582. .first()
  583. )
  584. if tool_provider:
  585. # Cannot delete a workflow that's published as a tool
  586. raise WorkflowInUseError("Cannot delete workflow that is published as a tool")
  587. session.delete(workflow)
  588. return True
  589. def _setup_variable_pool(
  590. query: str,
  591. files: Sequence[File],
  592. user_id: str,
  593. user_inputs: Mapping[str, Any],
  594. workflow: Workflow,
  595. node_type: NodeType,
  596. conversation_id: str,
  597. conversation_variables: list[Variable],
  598. ):
  599. # Only inject system variables for START node type.
  600. if node_type == NodeType.START:
  601. system_variable = SystemVariable(
  602. user_id=user_id,
  603. app_id=workflow.app_id,
  604. workflow_id=workflow.id,
  605. files=files or [],
  606. workflow_execution_id=str(uuid.uuid4()),
  607. )
  608. # Only add chatflow-specific variables for non-workflow types
  609. if workflow.type != WorkflowType.WORKFLOW.value:
  610. system_variable.query = query
  611. system_variable.conversation_id = conversation_id
  612. system_variable.dialogue_count = 0
  613. else:
  614. system_variable = SystemVariable.empty()
  615. # init variable pool
  616. variable_pool = VariablePool(
  617. system_variables=system_variable,
  618. user_inputs=user_inputs,
  619. environment_variables=workflow.environment_variables,
  620. # Based on the definition of `VariableUnion`,
  621. # `list[Variable]` can be safely used as `list[VariableUnion]` since they are compatible.
  622. conversation_variables=cast(list[VariableUnion], conversation_variables), #
  623. )
  624. return variable_pool
  625. def _rebuild_file_for_user_inputs_in_start_node(
  626. tenant_id: str, start_node_data: StartNodeData, user_inputs: Mapping[str, Any]
  627. ) -> Mapping[str, Any]:
  628. inputs_copy = dict(user_inputs)
  629. for variable in start_node_data.variables:
  630. if variable.type not in (VariableEntityType.FILE, VariableEntityType.FILE_LIST):
  631. continue
  632. if variable.variable not in user_inputs:
  633. continue
  634. value = user_inputs[variable.variable]
  635. file = _rebuild_single_file(tenant_id=tenant_id, value=value, variable_entity_type=variable.type)
  636. inputs_copy[variable.variable] = file
  637. return inputs_copy
  638. def _rebuild_single_file(tenant_id: str, value: Any, variable_entity_type: VariableEntityType) -> File | Sequence[File]:
  639. if variable_entity_type == VariableEntityType.FILE:
  640. if not isinstance(value, dict):
  641. raise ValueError(f"expected dict for file object, got {type(value)}")
  642. return build_from_mapping(mapping=value, tenant_id=tenant_id)
  643. elif variable_entity_type == VariableEntityType.FILE_LIST:
  644. if not isinstance(value, list):
  645. raise ValueError(f"expected list for file list object, got {type(value)}")
  646. if len(value) == 0:
  647. return []
  648. if not isinstance(value[0], dict):
  649. raise ValueError(f"expected dict for first element in the file list, got {type(value)}")
  650. return build_from_mappings(mappings=value, tenant_id=tenant_id)
  651. else:
  652. raise Exception("unreachable")