workflow_service.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import json
  2. import time
  3. from collections.abc import Callable, Generator, Sequence
  4. from datetime import datetime, timezone
  5. from typing import Any, Optional
  6. from core.app.apps.advanced_chat.app_config_manager import AdvancedChatAppConfigManager
  7. from core.app.apps.workflow.app_config_manager import WorkflowAppConfigManager
  8. from core.app.segments import Variable
  9. from core.model_runtime.utils.encoders import jsonable_encoder
  10. from core.workflow.entities.node_entities import NodeRunResult, NodeType
  11. from core.workflow.errors import WorkflowNodeRunFailedError
  12. from core.workflow.graph_engine.entities.event import InNodeEvent
  13. from core.workflow.nodes.base_node import BaseNode
  14. from core.workflow.nodes.event import RunCompletedEvent, RunEvent
  15. from core.workflow.nodes.node_mapping import node_classes
  16. from core.workflow.workflow_entry import WorkflowEntry
  17. from events.app_event import app_draft_workflow_was_synced, app_published_workflow_was_updated
  18. from extensions.ext_database import db
  19. from models.account import Account
  20. from models.model import App, AppMode
  21. from models.workflow import (
  22. CreatedByRole,
  23. Workflow,
  24. WorkflowNodeExecution,
  25. WorkflowNodeExecutionStatus,
  26. WorkflowNodeExecutionTriggeredFrom,
  27. WorkflowType,
  28. )
  29. from services.errors.app import WorkflowHashNotEqualError
  30. from services.workflow.workflow_converter import WorkflowConverter
  31. class WorkflowService:
  32. """
  33. Workflow Service
  34. """
  35. def get_draft_workflow(self, app_model: App) -> Optional[Workflow]:
  36. """
  37. Get draft workflow
  38. """
  39. # fetch draft workflow by app_model
  40. workflow = (
  41. db.session.query(Workflow)
  42. .filter(
  43. Workflow.tenant_id == app_model.tenant_id, Workflow.app_id == app_model.id, Workflow.version == "draft"
  44. )
  45. .first()
  46. )
  47. # return draft workflow
  48. return workflow
  49. def get_published_workflow(self, app_model: App) -> Optional[Workflow]:
  50. """
  51. Get published workflow
  52. """
  53. if not app_model.workflow_id:
  54. return None
  55. # fetch published workflow by workflow_id
  56. workflow = (
  57. db.session.query(Workflow)
  58. .filter(
  59. Workflow.tenant_id == app_model.tenant_id,
  60. Workflow.app_id == app_model.id,
  61. Workflow.id == app_model.workflow_id,
  62. )
  63. .first()
  64. )
  65. return workflow
  66. def sync_draft_workflow(
  67. self,
  68. *,
  69. app_model: App,
  70. graph: dict,
  71. features: dict,
  72. unique_hash: Optional[str],
  73. account: Account,
  74. environment_variables: Sequence[Variable],
  75. conversation_variables: Sequence[Variable],
  76. ) -> Workflow:
  77. """
  78. Sync draft workflow
  79. :raises WorkflowHashNotEqualError
  80. """
  81. # fetch draft workflow by app_model
  82. workflow = self.get_draft_workflow(app_model=app_model)
  83. if workflow and workflow.unique_hash != unique_hash:
  84. raise WorkflowHashNotEqualError()
  85. # validate features structure
  86. self.validate_features_structure(app_model=app_model, features=features)
  87. # create draft workflow if not found
  88. if not workflow:
  89. workflow = Workflow(
  90. tenant_id=app_model.tenant_id,
  91. app_id=app_model.id,
  92. type=WorkflowType.from_app_mode(app_model.mode).value,
  93. version="draft",
  94. graph=json.dumps(graph),
  95. features=json.dumps(features),
  96. created_by=account.id,
  97. environment_variables=environment_variables,
  98. conversation_variables=conversation_variables,
  99. )
  100. db.session.add(workflow)
  101. # update draft workflow if found
  102. else:
  103. workflow.graph = json.dumps(graph)
  104. workflow.features = json.dumps(features)
  105. workflow.updated_by = account.id
  106. workflow.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  107. workflow.environment_variables = environment_variables
  108. workflow.conversation_variables = conversation_variables
  109. # commit db session changes
  110. db.session.commit()
  111. # trigger app workflow events
  112. app_draft_workflow_was_synced.send(app_model, synced_draft_workflow=workflow)
  113. # return draft workflow
  114. return workflow
  115. def publish_workflow(self, app_model: App, account: Account, draft_workflow: Optional[Workflow] = None) -> Workflow:
  116. """
  117. Publish workflow from draft
  118. :param app_model: App instance
  119. :param account: Account instance
  120. :param draft_workflow: Workflow instance
  121. """
  122. if not draft_workflow:
  123. # fetch draft workflow by app_model
  124. draft_workflow = self.get_draft_workflow(app_model=app_model)
  125. if not draft_workflow:
  126. raise ValueError("No valid workflow found.")
  127. # create new workflow
  128. workflow = Workflow(
  129. tenant_id=app_model.tenant_id,
  130. app_id=app_model.id,
  131. type=draft_workflow.type,
  132. version=str(datetime.now(timezone.utc).replace(tzinfo=None)),
  133. graph=draft_workflow.graph,
  134. features=draft_workflow.features,
  135. created_by=account.id,
  136. environment_variables=draft_workflow.environment_variables,
  137. conversation_variables=draft_workflow.conversation_variables,
  138. )
  139. # commit db session changes
  140. db.session.add(workflow)
  141. db.session.flush()
  142. db.session.commit()
  143. app_model.workflow_id = workflow.id
  144. db.session.commit()
  145. # trigger app workflow events
  146. app_published_workflow_was_updated.send(app_model, published_workflow=workflow)
  147. # return new workflow
  148. return workflow
  149. def get_default_block_configs(self) -> list[dict]:
  150. """
  151. Get default block configs
  152. """
  153. # return default block config
  154. default_block_configs = []
  155. for node_type, node_class in node_classes.items():
  156. default_config = node_class.get_default_config()
  157. if default_config:
  158. default_block_configs.append(default_config)
  159. return default_block_configs
  160. def get_default_block_config(self, node_type: str, filters: Optional[dict] = None) -> Optional[dict]:
  161. """
  162. Get default config of node.
  163. :param node_type: node type
  164. :param filters: filter by node config parameters.
  165. :return:
  166. """
  167. node_type_enum: NodeType = NodeType.value_of(node_type)
  168. # return default block config
  169. node_class = node_classes.get(node_type_enum)
  170. if not node_class:
  171. return None
  172. default_config = node_class.get_default_config(filters=filters)
  173. if not default_config:
  174. return None
  175. return default_config
  176. def run_draft_workflow_node(
  177. self, app_model: App, node_id: str, user_inputs: dict, account: Account
  178. ) -> WorkflowNodeExecution:
  179. """
  180. Run draft workflow node
  181. """
  182. # fetch draft workflow by app_model
  183. draft_workflow = self.get_draft_workflow(app_model=app_model)
  184. if not draft_workflow:
  185. raise ValueError("Workflow not initialized")
  186. # run draft workflow node
  187. start_at = time.perf_counter()
  188. workflow_node_execution = self._handle_node_run_result(
  189. getter=lambda: WorkflowEntry.single_step_run(
  190. workflow=draft_workflow,
  191. node_id=node_id,
  192. user_inputs=user_inputs,
  193. user_id=account.id,
  194. ),
  195. start_at=start_at,
  196. tenant_id=app_model.tenant_id,
  197. node_id=node_id,
  198. )
  199. workflow_node_execution.app_id = app_model.id
  200. workflow_node_execution.created_by = account.id
  201. workflow_node_execution.workflow_id = draft_workflow.id
  202. db.session.add(workflow_node_execution)
  203. db.session.commit()
  204. return workflow_node_execution
  205. def run_free_workflow_node(
  206. self, node_data: dict, tenant_id: str, user_id: str, node_id: str, user_inputs: dict[str, Any]
  207. ) -> WorkflowNodeExecution:
  208. """
  209. Run draft workflow node
  210. """
  211. # run draft workflow node
  212. start_at = time.perf_counter()
  213. workflow_node_execution = self._handle_node_run_result(
  214. getter=lambda: WorkflowEntry.run_free_node(
  215. node_id=node_id,
  216. node_data=node_data,
  217. tenant_id=tenant_id,
  218. user_id=user_id,
  219. user_inputs=user_inputs,
  220. ),
  221. start_at=start_at,
  222. tenant_id=tenant_id,
  223. node_id=node_id,
  224. )
  225. return workflow_node_execution
  226. def _handle_node_run_result(
  227. self,
  228. getter: Callable[[], tuple[BaseNode, Generator[RunEvent | InNodeEvent, None, None]]],
  229. start_at: float,
  230. tenant_id: str,
  231. node_id: str,
  232. ):
  233. """
  234. Handle node run result
  235. :param getter: Callable[[], tuple[BaseNode, Generator[RunEvent | InNodeEvent, None, None]]]
  236. :param start_at: float
  237. :param tenant_id: str
  238. :param node_id: str
  239. """
  240. try:
  241. node_instance, generator = getter()
  242. node_run_result: NodeRunResult | None = None
  243. for event in generator:
  244. if isinstance(event, RunCompletedEvent):
  245. node_run_result = event.run_result
  246. # sign output files
  247. node_run_result.outputs = WorkflowEntry.handle_special_values(node_run_result.outputs)
  248. break
  249. if not node_run_result:
  250. raise ValueError("Node run failed with no run result")
  251. run_succeeded = True if node_run_result.status == WorkflowNodeExecutionStatus.SUCCEEDED else False
  252. error = node_run_result.error if not run_succeeded else None
  253. except WorkflowNodeRunFailedError as e:
  254. node_instance = e.node_instance
  255. run_succeeded = False
  256. node_run_result = None
  257. error = e.error
  258. workflow_node_execution = WorkflowNodeExecution()
  259. workflow_node_execution.tenant_id = tenant_id
  260. workflow_node_execution.triggered_from = WorkflowNodeExecutionTriggeredFrom.SINGLE_STEP.value
  261. workflow_node_execution.index = 1
  262. workflow_node_execution.node_id = node_id
  263. workflow_node_execution.node_type = node_instance.node_type.value
  264. workflow_node_execution.title = node_instance.node_data.title
  265. workflow_node_execution.elapsed_time = time.perf_counter() - start_at
  266. workflow_node_execution.created_by_role = CreatedByRole.ACCOUNT.value
  267. workflow_node_execution.created_at = datetime.now(timezone.utc).replace(tzinfo=None)
  268. workflow_node_execution.finished_at = datetime.now(timezone.utc).replace(tzinfo=None)
  269. if run_succeeded and node_run_result:
  270. # create workflow node execution
  271. workflow_node_execution.inputs = json.dumps(node_run_result.inputs) if node_run_result.inputs else None
  272. workflow_node_execution.process_data = (
  273. json.dumps(node_run_result.process_data) if node_run_result.process_data else None
  274. )
  275. workflow_node_execution.outputs = (
  276. json.dumps(jsonable_encoder(node_run_result.outputs)) if node_run_result.outputs else None
  277. )
  278. workflow_node_execution.execution_metadata = (
  279. json.dumps(jsonable_encoder(node_run_result.metadata)) if node_run_result.metadata else None
  280. )
  281. workflow_node_execution.status = WorkflowNodeExecutionStatus.SUCCEEDED.value
  282. else:
  283. # create workflow node execution
  284. workflow_node_execution.status = WorkflowNodeExecutionStatus.FAILED.value
  285. workflow_node_execution.error = error
  286. return workflow_node_execution
  287. def convert_to_workflow(self, app_model: App, account: Account, args: dict) -> App:
  288. """
  289. Basic mode of chatbot app(expert mode) to workflow
  290. Completion App to Workflow App
  291. :param app_model: App instance
  292. :param account: Account instance
  293. :param args: dict
  294. :return:
  295. """
  296. # chatbot convert to workflow mode
  297. workflow_converter = WorkflowConverter()
  298. if app_model.mode not in {AppMode.CHAT.value, AppMode.COMPLETION.value}:
  299. raise ValueError(f"Current App mode: {app_model.mode} is not supported convert to workflow.")
  300. # convert to workflow
  301. new_app = workflow_converter.convert_to_workflow(
  302. app_model=app_model,
  303. account=account,
  304. name=args.get("name", ""),
  305. icon_type=args.get("icon_type", ""),
  306. icon=args.get("icon", ""),
  307. icon_background=args.get("icon_background", ""),
  308. )
  309. return new_app
  310. def validate_features_structure(self, app_model: App, features: dict) -> dict:
  311. if app_model.mode == AppMode.ADVANCED_CHAT.value:
  312. return AdvancedChatAppConfigManager.config_validate(
  313. tenant_id=app_model.tenant_id, config=features, only_structure_validate=True
  314. )
  315. elif app_model.mode == AppMode.WORKFLOW.value:
  316. return WorkflowAppConfigManager.config_validate(
  317. tenant_id=app_model.tenant_id, config=features, only_structure_validate=True
  318. )
  319. else:
  320. raise ValueError(f"Invalid app mode: {app_model.mode}")