workflow.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import json
  2. from enum import Enum
  3. from typing import Optional, Union
  4. from extensions.ext_database import db
  5. from libs import helper
  6. from models import StringUUID
  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(StringUUID, server_default=db.text('uuid_generate_v4()'))
  79. tenant_id = db.Column(StringUUID, nullable=False)
  80. app_id = db.Column(StringUUID, 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(StringUUID, nullable=False)
  86. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  87. updated_by = db.Column(StringUUID)
  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. @property
  122. def unique_hash(self) -> str:
  123. """
  124. Get hash of workflow.
  125. :return: hash
  126. """
  127. entity = {
  128. 'graph': self.graph_dict,
  129. 'features': self.features_dict
  130. }
  131. return helper.generate_text_hash(json.dumps(entity, sort_keys=True))
  132. @property
  133. def tool_published(self) -> bool:
  134. from models.tools import WorkflowToolProvider
  135. return db.session.query(WorkflowToolProvider).filter(
  136. WorkflowToolProvider.app_id == self.app_id
  137. ).first() is not None
  138. class WorkflowRunTriggeredFrom(Enum):
  139. """
  140. Workflow Run Triggered From Enum
  141. """
  142. DEBUGGING = 'debugging'
  143. APP_RUN = 'app-run'
  144. @classmethod
  145. def value_of(cls, value: str) -> 'WorkflowRunTriggeredFrom':
  146. """
  147. Get value of given mode.
  148. :param value: mode value
  149. :return: mode
  150. """
  151. for mode in cls:
  152. if mode.value == value:
  153. return mode
  154. raise ValueError(f'invalid workflow run triggered from value {value}')
  155. class WorkflowRunStatus(Enum):
  156. """
  157. Workflow Run Status Enum
  158. """
  159. RUNNING = 'running'
  160. SUCCEEDED = 'succeeded'
  161. FAILED = 'failed'
  162. STOPPED = 'stopped'
  163. @classmethod
  164. def value_of(cls, value: str) -> 'WorkflowRunStatus':
  165. """
  166. Get value of given mode.
  167. :param value: mode value
  168. :return: mode
  169. """
  170. for mode in cls:
  171. if mode.value == value:
  172. return mode
  173. raise ValueError(f'invalid workflow run status value {value}')
  174. class WorkflowRun(db.Model):
  175. """
  176. Workflow Run
  177. Attributes:
  178. - id (uuid) Run ID
  179. - tenant_id (uuid) Workspace ID
  180. - app_id (uuid) App ID
  181. - sequence_number (int) Auto-increment sequence number, incremented within the App, starting from 1
  182. - workflow_id (uuid) Workflow ID
  183. - type (string) Workflow type
  184. - triggered_from (string) Trigger source
  185. `debugging` for canvas debugging
  186. `app-run` for (published) app execution
  187. - version (string) Version
  188. - graph (text) Workflow canvas configuration (JSON)
  189. - inputs (text) Input parameters
  190. - status (string) Execution status, `running` / `succeeded` / `failed` / `stopped`
  191. - outputs (text) `optional` Output content
  192. - error (string) `optional` Error reason
  193. - elapsed_time (float) `optional` Time consumption (s)
  194. - total_tokens (int) `optional` Total tokens used
  195. - total_steps (int) Total steps (redundant), default 0
  196. - created_by_role (string) Creator role
  197. - `account` Console account
  198. - `end_user` End user
  199. - created_by (uuid) Runner ID
  200. - created_at (timestamp) Run time
  201. - finished_at (timestamp) End time
  202. """
  203. __tablename__ = 'workflow_runs'
  204. __table_args__ = (
  205. db.PrimaryKeyConstraint('id', name='workflow_run_pkey'),
  206. db.Index('workflow_run_triggerd_from_idx', 'tenant_id', 'app_id', 'triggered_from'),
  207. )
  208. id = db.Column(StringUUID, server_default=db.text('uuid_generate_v4()'))
  209. tenant_id = db.Column(StringUUID, nullable=False)
  210. app_id = db.Column(StringUUID, nullable=False)
  211. sequence_number = db.Column(db.Integer, nullable=False)
  212. workflow_id = db.Column(StringUUID, nullable=False)
  213. type = db.Column(db.String(255), nullable=False)
  214. triggered_from = db.Column(db.String(255), nullable=False)
  215. version = db.Column(db.String(255), nullable=False)
  216. graph = db.Column(db.Text)
  217. inputs = db.Column(db.Text)
  218. status = db.Column(db.String(255), nullable=False)
  219. outputs = db.Column(db.Text)
  220. error = db.Column(db.Text)
  221. elapsed_time = db.Column(db.Float, nullable=False, server_default=db.text('0'))
  222. total_tokens = db.Column(db.Integer, nullable=False, server_default=db.text('0'))
  223. total_steps = db.Column(db.Integer, server_default=db.text('0'))
  224. created_by_role = db.Column(db.String(255), nullable=False)
  225. created_by = db.Column(StringUUID, nullable=False)
  226. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  227. finished_at = db.Column(db.DateTime)
  228. @property
  229. def created_by_account(self):
  230. created_by_role = CreatedByRole.value_of(self.created_by_role)
  231. return Account.query.get(self.created_by) \
  232. if created_by_role == CreatedByRole.ACCOUNT else None
  233. @property
  234. def created_by_end_user(self):
  235. from models.model import EndUser
  236. created_by_role = CreatedByRole.value_of(self.created_by_role)
  237. return EndUser.query.get(self.created_by) \
  238. if created_by_role == CreatedByRole.END_USER else None
  239. @property
  240. def graph_dict(self):
  241. return json.loads(self.graph) if self.graph else None
  242. @property
  243. def inputs_dict(self):
  244. return json.loads(self.inputs) if self.inputs else None
  245. @property
  246. def outputs_dict(self):
  247. return json.loads(self.outputs) if self.outputs else None
  248. @property
  249. def message(self) -> Optional['Message']:
  250. from models.model import Message
  251. return db.session.query(Message).filter(
  252. Message.app_id == self.app_id,
  253. Message.workflow_run_id == self.id
  254. ).first()
  255. @property
  256. def workflow(self):
  257. return db.session.query(Workflow).filter(Workflow.id == self.workflow_id).first()
  258. class WorkflowNodeExecutionTriggeredFrom(Enum):
  259. """
  260. Workflow Node Execution Triggered From Enum
  261. """
  262. SINGLE_STEP = 'single-step'
  263. WORKFLOW_RUN = 'workflow-run'
  264. @classmethod
  265. def value_of(cls, value: str) -> 'WorkflowNodeExecutionTriggeredFrom':
  266. """
  267. Get value of given mode.
  268. :param value: mode value
  269. :return: mode
  270. """
  271. for mode in cls:
  272. if mode.value == value:
  273. return mode
  274. raise ValueError(f'invalid workflow node execution triggered from value {value}')
  275. class WorkflowNodeExecutionStatus(Enum):
  276. """
  277. Workflow Node Execution Status Enum
  278. """
  279. RUNNING = 'running'
  280. SUCCEEDED = 'succeeded'
  281. FAILED = 'failed'
  282. @classmethod
  283. def value_of(cls, value: str) -> 'WorkflowNodeExecutionStatus':
  284. """
  285. Get value of given mode.
  286. :param value: mode value
  287. :return: mode
  288. """
  289. for mode in cls:
  290. if mode.value == value:
  291. return mode
  292. raise ValueError(f'invalid workflow node execution status value {value}')
  293. class WorkflowNodeExecution(db.Model):
  294. """
  295. Workflow Node Execution
  296. - id (uuid) Execution ID
  297. - tenant_id (uuid) Workspace ID
  298. - app_id (uuid) App ID
  299. - workflow_id (uuid) Workflow ID
  300. - triggered_from (string) Trigger source
  301. `single-step` for single-step debugging
  302. `workflow-run` for workflow execution (debugging / user execution)
  303. - workflow_run_id (uuid) `optional` Workflow run ID
  304. Null for single-step debugging.
  305. - index (int) Execution sequence number, used for displaying Tracing Node order
  306. - predecessor_node_id (string) `optional` Predecessor node ID, used for displaying execution path
  307. - node_id (string) Node ID
  308. - node_type (string) Node type, such as `start`
  309. - title (string) Node title
  310. - inputs (json) All predecessor node variable content used in the node
  311. - process_data (json) Node process data
  312. - outputs (json) `optional` Node output variables
  313. - status (string) Execution status, `running` / `succeeded` / `failed`
  314. - error (string) `optional` Error reason
  315. - elapsed_time (float) `optional` Time consumption (s)
  316. - execution_metadata (text) Metadata
  317. - total_tokens (int) `optional` Total tokens used
  318. - total_price (decimal) `optional` Total cost
  319. - currency (string) `optional` Currency, such as USD / RMB
  320. - created_at (timestamp) Run time
  321. - created_by_role (string) Creator role
  322. - `account` Console account
  323. - `end_user` End user
  324. - created_by (uuid) Runner ID
  325. - finished_at (timestamp) End time
  326. """
  327. __tablename__ = 'workflow_node_executions'
  328. __table_args__ = (
  329. db.PrimaryKeyConstraint('id', name='workflow_node_execution_pkey'),
  330. db.Index('workflow_node_execution_workflow_run_idx', 'tenant_id', 'app_id', 'workflow_id',
  331. 'triggered_from', 'workflow_run_id'),
  332. db.Index('workflow_node_execution_node_run_idx', 'tenant_id', 'app_id', 'workflow_id',
  333. 'triggered_from', 'node_id'),
  334. )
  335. id = db.Column(StringUUID, server_default=db.text('uuid_generate_v4()'))
  336. tenant_id = db.Column(StringUUID, nullable=False)
  337. app_id = db.Column(StringUUID, nullable=False)
  338. workflow_id = db.Column(StringUUID, nullable=False)
  339. triggered_from = db.Column(db.String(255), nullable=False)
  340. workflow_run_id = db.Column(StringUUID)
  341. index = db.Column(db.Integer, nullable=False)
  342. predecessor_node_id = db.Column(db.String(255))
  343. node_id = db.Column(db.String(255), nullable=False)
  344. node_type = db.Column(db.String(255), nullable=False)
  345. title = db.Column(db.String(255), nullable=False)
  346. inputs = db.Column(db.Text)
  347. process_data = db.Column(db.Text)
  348. outputs = db.Column(db.Text)
  349. status = db.Column(db.String(255), nullable=False)
  350. error = db.Column(db.Text)
  351. elapsed_time = db.Column(db.Float, nullable=False, server_default=db.text('0'))
  352. execution_metadata = db.Column(db.Text)
  353. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  354. created_by_role = db.Column(db.String(255), nullable=False)
  355. created_by = db.Column(StringUUID, nullable=False)
  356. finished_at = db.Column(db.DateTime)
  357. @property
  358. def created_by_account(self):
  359. created_by_role = CreatedByRole.value_of(self.created_by_role)
  360. return Account.query.get(self.created_by) \
  361. if created_by_role == CreatedByRole.ACCOUNT else None
  362. @property
  363. def created_by_end_user(self):
  364. from models.model import EndUser
  365. created_by_role = CreatedByRole.value_of(self.created_by_role)
  366. return EndUser.query.get(self.created_by) \
  367. if created_by_role == CreatedByRole.END_USER else None
  368. @property
  369. def inputs_dict(self):
  370. return json.loads(self.inputs) if self.inputs else None
  371. @property
  372. def outputs_dict(self):
  373. return json.loads(self.outputs) if self.outputs else None
  374. @property
  375. def process_data_dict(self):
  376. return json.loads(self.process_data) if self.process_data else None
  377. @property
  378. def execution_metadata_dict(self):
  379. return json.loads(self.execution_metadata) if self.execution_metadata else None
  380. @property
  381. def extras(self):
  382. from core.tools.tool_manager import ToolManager
  383. extras = {}
  384. if self.execution_metadata_dict:
  385. from core.workflow.entities.node_entities import NodeType
  386. if self.node_type == NodeType.TOOL.value and 'tool_info' in self.execution_metadata_dict:
  387. tool_info = self.execution_metadata_dict['tool_info']
  388. extras['icon'] = ToolManager.get_tool_icon(
  389. tenant_id=self.tenant_id,
  390. provider_type=tool_info['provider_type'],
  391. provider_id=tool_info['provider_id']
  392. )
  393. return extras
  394. class WorkflowAppLogCreatedFrom(Enum):
  395. """
  396. Workflow App Log Created From Enum
  397. """
  398. SERVICE_API = 'service-api'
  399. WEB_APP = 'web-app'
  400. INSTALLED_APP = 'installed-app'
  401. @classmethod
  402. def value_of(cls, value: str) -> 'WorkflowAppLogCreatedFrom':
  403. """
  404. Get value of given mode.
  405. :param value: mode value
  406. :return: mode
  407. """
  408. for mode in cls:
  409. if mode.value == value:
  410. return mode
  411. raise ValueError(f'invalid workflow app log created from value {value}')
  412. class WorkflowAppLog(db.Model):
  413. """
  414. Workflow App execution log, excluding workflow debugging records.
  415. Attributes:
  416. - id (uuid) run ID
  417. - tenant_id (uuid) Workspace ID
  418. - app_id (uuid) App ID
  419. - workflow_id (uuid) Associated Workflow ID
  420. - workflow_run_id (uuid) Associated Workflow Run ID
  421. - created_from (string) Creation source
  422. `service-api` App Execution OpenAPI
  423. `web-app` WebApp
  424. `installed-app` Installed App
  425. - created_by_role (string) Creator role
  426. - `account` Console account
  427. - `end_user` End user
  428. - created_by (uuid) Creator ID, depends on the user table according to created_by_role
  429. - created_at (timestamp) Creation time
  430. """
  431. __tablename__ = 'workflow_app_logs'
  432. __table_args__ = (
  433. db.PrimaryKeyConstraint('id', name='workflow_app_log_pkey'),
  434. db.Index('workflow_app_log_app_idx', 'tenant_id', 'app_id'),
  435. )
  436. id = db.Column(StringUUID, server_default=db.text('uuid_generate_v4()'))
  437. tenant_id = db.Column(StringUUID, nullable=False)
  438. app_id = db.Column(StringUUID, nullable=False)
  439. workflow_id = db.Column(StringUUID, nullable=False)
  440. workflow_run_id = db.Column(StringUUID, nullable=False)
  441. created_from = db.Column(db.String(255), nullable=False)
  442. created_by_role = db.Column(db.String(255), nullable=False)
  443. created_by = db.Column(StringUUID, nullable=False)
  444. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  445. @property
  446. def workflow_run(self):
  447. return WorkflowRun.query.get(self.workflow_run_id)
  448. @property
  449. def created_by_account(self):
  450. created_by_role = CreatedByRole.value_of(self.created_by_role)
  451. return Account.query.get(self.created_by) \
  452. if created_by_role == CreatedByRole.ACCOUNT else None
  453. @property
  454. def created_by_end_user(self):
  455. from models.model import EndUser
  456. created_by_role = CreatedByRole.value_of(self.created_by_role)
  457. return EndUser.query.get(self.created_by) \
  458. if created_by_role == CreatedByRole.END_USER else None