workflow_service.py 12 KB

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