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