workflow.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import json
  2. from enum import Enum
  3. from typing import Optional, Union
  4. from sqlalchemy.dialects.postgresql import UUID
  5. from core.tools.tool_manager import ToolManager
  6. from extensions.ext_database import db
  7. from models.account import Account
  8. class CreatedByRole(Enum):
  9. """
  10. Created By Role Enum
  11. """
  12. ACCOUNT = 'account'
  13. END_USER = 'end_user'
  14. @classmethod
  15. def value_of(cls, value: str) -> 'CreatedByRole':
  16. """
  17. Get value of given mode.
  18. :param value: mode value
  19. :return: mode
  20. """
  21. for mode in cls:
  22. if mode.value == value:
  23. return mode
  24. raise ValueError(f'invalid created by role value {value}')
  25. class WorkflowType(Enum):
  26. """
  27. Workflow Type Enum
  28. """
  29. WORKFLOW = 'workflow'
  30. CHAT = 'chat'
  31. @classmethod
  32. def value_of(cls, value: str) -> 'WorkflowType':
  33. """
  34. Get value of given mode.
  35. :param value: mode value
  36. :return: mode
  37. """
  38. for mode in cls:
  39. if mode.value == value:
  40. return mode
  41. raise ValueError(f'invalid workflow type value {value}')
  42. @classmethod
  43. def from_app_mode(cls, app_mode: Union[str, 'AppMode']) -> 'WorkflowType':
  44. """
  45. Get workflow type from app mode.
  46. :param app_mode: app mode
  47. :return: workflow type
  48. """
  49. from models.model import AppMode
  50. app_mode = app_mode if isinstance(app_mode, AppMode) else AppMode.value_of(app_mode)
  51. return cls.WORKFLOW if app_mode == AppMode.WORKFLOW else cls.CHAT
  52. class Workflow(db.Model):
  53. """
  54. Workflow, for `Workflow App` and `Chat App workflow mode`.
  55. Attributes:
  56. - id (uuid) Workflow ID, pk
  57. - tenant_id (uuid) Workspace ID
  58. - app_id (uuid) App ID
  59. - type (string) Workflow type
  60. `workflow` for `Workflow App`
  61. `chat` for `Chat App workflow mode`
  62. - version (string) Version
  63. `draft` for draft version (only one for each app), other for version number (redundant)
  64. - graph (text) Workflow canvas configuration (JSON)
  65. The entire canvas configuration JSON, including Node, Edge, and other configurations
  66. - nodes (array[object]) Node list, see Node Schema
  67. - edges (array[object]) Edge list, see Edge Schema
  68. - created_by (uuid) Creator ID
  69. - created_at (timestamp) Creation time
  70. - updated_by (uuid) `optional` Last updater ID
  71. - updated_at (timestamp) `optional` Last update time
  72. """
  73. __tablename__ = 'workflows'
  74. __table_args__ = (
  75. db.PrimaryKeyConstraint('id', name='workflow_pkey'),
  76. db.Index('workflow_version_idx', 'tenant_id', 'app_id', 'version'),
  77. )
  78. id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
  79. tenant_id = db.Column(UUID, nullable=False)
  80. app_id = db.Column(UUID, nullable=False)
  81. type = db.Column(db.String(255), nullable=False)
  82. version = db.Column(db.String(255), nullable=False)
  83. graph = db.Column(db.Text)
  84. features = db.Column(db.Text)
  85. created_by = db.Column(UUID, nullable=False)
  86. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  87. updated_by = db.Column(UUID)
  88. updated_at = db.Column(db.DateTime)
  89. @property
  90. def created_by_account(self):
  91. return Account.query.get(self.created_by)
  92. @property
  93. def updated_by_account(self):
  94. return Account.query.get(self.updated_by) if self.updated_by else None
  95. @property
  96. def graph_dict(self):
  97. return json.loads(self.graph) if self.graph else None
  98. @property
  99. def features_dict(self):
  100. return json.loads(self.features) if self.features else {}
  101. def user_input_form(self, to_old_structure: bool = False) -> list:
  102. # get start node from graph
  103. if not self.graph:
  104. return []
  105. graph_dict = self.graph_dict
  106. if 'nodes' not in graph_dict:
  107. return []
  108. start_node = next((node for node in graph_dict['nodes'] if node['data']['type'] == 'start'), None)
  109. if not start_node:
  110. return []
  111. # get user_input_form from start node
  112. variables = start_node.get('data', {}).get('variables', [])
  113. if to_old_structure:
  114. old_structure_variables = []
  115. for variable in variables:
  116. old_structure_variables.append({
  117. variable['type']: variable
  118. })
  119. return old_structure_variables
  120. return variables
  121. class WorkflowRunTriggeredFrom(Enum):
  122. """
  123. Workflow Run Triggered From Enum
  124. """
  125. DEBUGGING = 'debugging'
  126. APP_RUN = 'app-run'
  127. @classmethod
  128. def value_of(cls, value: str) -> 'WorkflowRunTriggeredFrom':
  129. """
  130. Get value of given mode.
  131. :param value: mode value
  132. :return: mode
  133. """
  134. for mode in cls:
  135. if mode.value == value:
  136. return mode
  137. raise ValueError(f'invalid workflow run triggered from value {value}')
  138. class WorkflowRunStatus(Enum):
  139. """
  140. Workflow Run Status Enum
  141. """
  142. RUNNING = 'running'
  143. SUCCEEDED = 'succeeded'
  144. FAILED = 'failed'
  145. STOPPED = 'stopped'
  146. @classmethod
  147. def value_of(cls, value: str) -> 'WorkflowRunStatus':
  148. """
  149. Get value of given mode.
  150. :param value: mode value
  151. :return: mode
  152. """
  153. for mode in cls:
  154. if mode.value == value:
  155. return mode
  156. raise ValueError(f'invalid workflow run status value {value}')
  157. class WorkflowRun(db.Model):
  158. """
  159. Workflow Run
  160. Attributes:
  161. - id (uuid) Run ID
  162. - tenant_id (uuid) Workspace ID
  163. - app_id (uuid) App ID
  164. - sequence_number (int) Auto-increment sequence number, incremented within the App, starting from 1
  165. - workflow_id (uuid) Workflow ID
  166. - type (string) Workflow type
  167. - triggered_from (string) Trigger source
  168. `debugging` for canvas debugging
  169. `app-run` for (published) app execution
  170. - version (string) Version
  171. - graph (text) Workflow canvas configuration (JSON)
  172. - inputs (text) Input parameters
  173. - status (string) Execution status, `running` / `succeeded` / `failed` / `stopped`
  174. - outputs (text) `optional` Output content
  175. - error (string) `optional` Error reason
  176. - elapsed_time (float) `optional` Time consumption (s)
  177. - total_tokens (int) `optional` Total tokens used
  178. - total_steps (int) Total steps (redundant), default 0
  179. - created_by_role (string) Creator role
  180. - `account` Console account
  181. - `end_user` End user
  182. - created_by (uuid) Runner ID
  183. - created_at (timestamp) Run time
  184. - finished_at (timestamp) End time
  185. """
  186. __tablename__ = 'workflow_runs'
  187. __table_args__ = (
  188. db.PrimaryKeyConstraint('id', name='workflow_run_pkey'),
  189. db.Index('workflow_run_triggerd_from_idx', 'tenant_id', 'app_id', 'triggered_from'),
  190. )
  191. id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
  192. tenant_id = db.Column(UUID, nullable=False)
  193. app_id = db.Column(UUID, nullable=False)
  194. sequence_number = db.Column(db.Integer, nullable=False)
  195. workflow_id = db.Column(UUID, nullable=False)
  196. type = db.Column(db.String(255), nullable=False)
  197. triggered_from = db.Column(db.String(255), nullable=False)
  198. version = db.Column(db.String(255), nullable=False)
  199. graph = db.Column(db.Text)
  200. inputs = db.Column(db.Text)
  201. status = db.Column(db.String(255), nullable=False)
  202. outputs = db.Column(db.Text)
  203. error = db.Column(db.Text)
  204. elapsed_time = db.Column(db.Float, nullable=False, server_default=db.text('0'))
  205. total_tokens = db.Column(db.Integer, nullable=False, server_default=db.text('0'))
  206. total_steps = db.Column(db.Integer, server_default=db.text('0'))
  207. created_by_role = db.Column(db.String(255), nullable=False)
  208. created_by = db.Column(UUID, nullable=False)
  209. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  210. finished_at = db.Column(db.DateTime)
  211. @property
  212. def created_by_account(self):
  213. created_by_role = CreatedByRole.value_of(self.created_by_role)
  214. return Account.query.get(self.created_by) \
  215. if created_by_role == CreatedByRole.ACCOUNT else None
  216. @property
  217. def created_by_end_user(self):
  218. from models.model import EndUser
  219. created_by_role = CreatedByRole.value_of(self.created_by_role)
  220. return EndUser.query.get(self.created_by) \
  221. if created_by_role == CreatedByRole.END_USER else None
  222. @property
  223. def graph_dict(self):
  224. return json.loads(self.graph) if self.graph else None
  225. @property
  226. def inputs_dict(self):
  227. return json.loads(self.inputs) if self.inputs else None
  228. @property
  229. def outputs_dict(self):
  230. return json.loads(self.outputs) if self.outputs else None
  231. @property
  232. def message(self) -> Optional['Message']:
  233. from models.model import Message
  234. return db.session.query(Message).filter(
  235. Message.app_id == self.app_id,
  236. Message.workflow_run_id == self.id
  237. ).first()
  238. class WorkflowNodeExecutionTriggeredFrom(Enum):
  239. """
  240. Workflow Node Execution Triggered From Enum
  241. """
  242. SINGLE_STEP = 'single-step'
  243. WORKFLOW_RUN = 'workflow-run'
  244. @classmethod
  245. def value_of(cls, value: str) -> 'WorkflowNodeExecutionTriggeredFrom':
  246. """
  247. Get value of given mode.
  248. :param value: mode value
  249. :return: mode
  250. """
  251. for mode in cls:
  252. if mode.value == value:
  253. return mode
  254. raise ValueError(f'invalid workflow node execution triggered from value {value}')
  255. class WorkflowNodeExecutionStatus(Enum):
  256. """
  257. Workflow Node Execution Status Enum
  258. """
  259. RUNNING = 'running'
  260. SUCCEEDED = 'succeeded'
  261. FAILED = 'failed'
  262. @classmethod
  263. def value_of(cls, value: str) -> 'WorkflowNodeExecutionStatus':
  264. """
  265. Get value of given mode.
  266. :param value: mode value
  267. :return: mode
  268. """
  269. for mode in cls:
  270. if mode.value == value:
  271. return mode
  272. raise ValueError(f'invalid workflow node execution status value {value}')
  273. class WorkflowNodeExecution(db.Model):
  274. """
  275. Workflow Node Execution
  276. - id (uuid) Execution ID
  277. - tenant_id (uuid) Workspace ID
  278. - app_id (uuid) App ID
  279. - workflow_id (uuid) Workflow ID
  280. - triggered_from (string) Trigger source
  281. `single-step` for single-step debugging
  282. `workflow-run` for workflow execution (debugging / user execution)
  283. - workflow_run_id (uuid) `optional` Workflow run ID
  284. Null for single-step debugging.
  285. - index (int) Execution sequence number, used for displaying Tracing Node order
  286. - predecessor_node_id (string) `optional` Predecessor node ID, used for displaying execution path
  287. - node_id (string) Node ID
  288. - node_type (string) Node type, such as `start`
  289. - title (string) Node title
  290. - inputs (json) All predecessor node variable content used in the node
  291. - process_data (json) Node process data
  292. - outputs (json) `optional` Node output variables
  293. - status (string) Execution status, `running` / `succeeded` / `failed`
  294. - error (string) `optional` Error reason
  295. - elapsed_time (float) `optional` Time consumption (s)
  296. - execution_metadata (text) Metadata
  297. - total_tokens (int) `optional` Total tokens used
  298. - total_price (decimal) `optional` Total cost
  299. - currency (string) `optional` Currency, such as USD / RMB
  300. - created_at (timestamp) Run time
  301. - created_by_role (string) Creator role
  302. - `account` Console account
  303. - `end_user` End user
  304. - created_by (uuid) Runner ID
  305. - finished_at (timestamp) End time
  306. """
  307. __tablename__ = 'workflow_node_executions'
  308. __table_args__ = (
  309. db.PrimaryKeyConstraint('id', name='workflow_node_execution_pkey'),
  310. db.Index('workflow_node_execution_workflow_run_idx', 'tenant_id', 'app_id', 'workflow_id',
  311. 'triggered_from', 'workflow_run_id'),
  312. db.Index('workflow_node_execution_node_run_idx', 'tenant_id', 'app_id', 'workflow_id',
  313. 'triggered_from', 'node_id'),
  314. )
  315. id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
  316. tenant_id = db.Column(UUID, nullable=False)
  317. app_id = db.Column(UUID, nullable=False)
  318. workflow_id = db.Column(UUID, nullable=False)
  319. triggered_from = db.Column(db.String(255), nullable=False)
  320. workflow_run_id = db.Column(UUID)
  321. index = db.Column(db.Integer, nullable=False)
  322. predecessor_node_id = db.Column(db.String(255))
  323. node_id = db.Column(db.String(255), nullable=False)
  324. node_type = db.Column(db.String(255), nullable=False)
  325. title = db.Column(db.String(255), nullable=False)
  326. inputs = db.Column(db.Text)
  327. process_data = db.Column(db.Text)
  328. outputs = db.Column(db.Text)
  329. status = db.Column(db.String(255), nullable=False)
  330. error = db.Column(db.Text)
  331. elapsed_time = db.Column(db.Float, nullable=False, server_default=db.text('0'))
  332. execution_metadata = db.Column(db.Text)
  333. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  334. created_by_role = db.Column(db.String(255), nullable=False)
  335. created_by = db.Column(UUID, nullable=False)
  336. finished_at = db.Column(db.DateTime)
  337. @property
  338. def created_by_account(self):
  339. created_by_role = CreatedByRole.value_of(self.created_by_role)
  340. return Account.query.get(self.created_by) \
  341. if created_by_role == CreatedByRole.ACCOUNT else None
  342. @property
  343. def created_by_end_user(self):
  344. from models.model import EndUser
  345. created_by_role = CreatedByRole.value_of(self.created_by_role)
  346. return EndUser.query.get(self.created_by) \
  347. if created_by_role == CreatedByRole.END_USER else None
  348. @property
  349. def inputs_dict(self):
  350. return json.loads(self.inputs) if self.inputs else None
  351. @property
  352. def outputs_dict(self):
  353. return json.loads(self.outputs) if self.outputs else None
  354. @property
  355. def process_data_dict(self):
  356. return json.loads(self.process_data) if self.process_data else None
  357. @property
  358. def execution_metadata_dict(self):
  359. return json.loads(self.execution_metadata) if self.execution_metadata else None
  360. @property
  361. def extras(self):
  362. extras = {}
  363. if self.execution_metadata_dict:
  364. from core.workflow.entities.node_entities import NodeType
  365. if self.node_type == NodeType.TOOL.value and 'tool_info' in self.execution_metadata_dict:
  366. tool_info = self.execution_metadata_dict['tool_info']
  367. extras['icon'] = ToolManager.get_tool_icon(
  368. tenant_id=self.tenant_id,
  369. provider_type=tool_info['provider_type'],
  370. provider_id=tool_info['provider_id']
  371. )
  372. return extras
  373. class WorkflowAppLogCreatedFrom(Enum):
  374. """
  375. Workflow App Log Created From Enum
  376. """
  377. SERVICE_API = 'service-api'
  378. WEB_APP = 'web-app'
  379. INSTALLED_APP = 'installed-app'
  380. @classmethod
  381. def value_of(cls, value: str) -> 'WorkflowAppLogCreatedFrom':
  382. """
  383. Get value of given mode.
  384. :param value: mode value
  385. :return: mode
  386. """
  387. for mode in cls:
  388. if mode.value == value:
  389. return mode
  390. raise ValueError(f'invalid workflow app log created from value {value}')
  391. class WorkflowAppLog(db.Model):
  392. """
  393. Workflow App execution log, excluding workflow debugging records.
  394. Attributes:
  395. - id (uuid) run ID
  396. - tenant_id (uuid) Workspace ID
  397. - app_id (uuid) App ID
  398. - workflow_id (uuid) Associated Workflow ID
  399. - workflow_run_id (uuid) Associated Workflow Run ID
  400. - created_from (string) Creation source
  401. `service-api` App Execution OpenAPI
  402. `web-app` WebApp
  403. `installed-app` Installed App
  404. - created_by_role (string) Creator role
  405. - `account` Console account
  406. - `end_user` End user
  407. - created_by (uuid) Creator ID, depends on the user table according to created_by_role
  408. - created_at (timestamp) Creation time
  409. """
  410. __tablename__ = 'workflow_app_logs'
  411. __table_args__ = (
  412. db.PrimaryKeyConstraint('id', name='workflow_app_log_pkey'),
  413. db.Index('workflow_app_log_app_idx', 'tenant_id', 'app_id'),
  414. )
  415. id = db.Column(UUID, server_default=db.text('uuid_generate_v4()'))
  416. tenant_id = db.Column(UUID, nullable=False)
  417. app_id = db.Column(UUID, nullable=False)
  418. workflow_id = db.Column(UUID, nullable=False)
  419. workflow_run_id = db.Column(UUID, nullable=False)
  420. created_from = db.Column(db.String(255), nullable=False)
  421. created_by_role = db.Column(db.String(255), nullable=False)
  422. created_by = db.Column(UUID, nullable=False)
  423. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  424. @property
  425. def workflow_run(self):
  426. return WorkflowRun.query.get(self.workflow_run_id)
  427. @property
  428. def created_by_account(self):
  429. created_by_role = CreatedByRole.value_of(self.created_by_role)
  430. return Account.query.get(self.created_by) \
  431. if created_by_role == CreatedByRole.ACCOUNT else None
  432. @property
  433. def created_by_end_user(self):
  434. from models.model import EndUser
  435. created_by_role = CreatedByRole.value_of(self.created_by_role)
  436. return EndUser.query.get(self.created_by) \
  437. if created_by_role == CreatedByRole.END_USER else None