workflow_service.py 13 KB

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