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

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