workflow.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. db.Index('workflow_run_tenant_app_sequence_idx', 'tenant_id', 'app_id', 'sequence_number'),
  208. )
  209. id = db.Column(StringUUID, server_default=db.text('uuid_generate_v4()'))
  210. tenant_id = db.Column(StringUUID, nullable=False)
  211. app_id = db.Column(StringUUID, nullable=False)
  212. sequence_number = db.Column(db.Integer, nullable=False)
  213. workflow_id = db.Column(StringUUID, nullable=False)
  214. type = db.Column(db.String(255), nullable=False)
  215. triggered_from = db.Column(db.String(255), nullable=False)
  216. version = db.Column(db.String(255), nullable=False)
  217. graph = db.Column(db.Text)
  218. inputs = db.Column(db.Text)
  219. status = db.Column(db.String(255), nullable=False)
  220. outputs = db.Column(db.Text)
  221. error = db.Column(db.Text)
  222. elapsed_time = db.Column(db.Float, nullable=False, server_default=db.text('0'))
  223. total_tokens = db.Column(db.Integer, nullable=False, server_default=db.text('0'))
  224. total_steps = db.Column(db.Integer, server_default=db.text('0'))
  225. created_by_role = db.Column(db.String(255), nullable=False)
  226. created_by = db.Column(StringUUID, nullable=False)
  227. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  228. finished_at = db.Column(db.DateTime)
  229. @property
  230. def created_by_account(self):
  231. created_by_role = CreatedByRole.value_of(self.created_by_role)
  232. return Account.query.get(self.created_by) \
  233. if created_by_role == CreatedByRole.ACCOUNT else None
  234. @property
  235. def created_by_end_user(self):
  236. from models.model import EndUser
  237. created_by_role = CreatedByRole.value_of(self.created_by_role)
  238. return EndUser.query.get(self.created_by) \
  239. if created_by_role == CreatedByRole.END_USER else None
  240. @property
  241. def graph_dict(self):
  242. return json.loads(self.graph) if self.graph else None
  243. @property
  244. def inputs_dict(self):
  245. return json.loads(self.inputs) if self.inputs else None
  246. @property
  247. def outputs_dict(self):
  248. return json.loads(self.outputs) if self.outputs else None
  249. @property
  250. def message(self) -> Optional['Message']:
  251. from models.model import Message
  252. return db.session.query(Message).filter(
  253. Message.app_id == self.app_id,
  254. Message.workflow_run_id == self.id
  255. ).first()
  256. @property
  257. def workflow(self):
  258. return db.session.query(Workflow).filter(Workflow.id == self.workflow_id).first()
  259. class WorkflowNodeExecutionTriggeredFrom(Enum):
  260. """
  261. Workflow Node Execution Triggered From Enum
  262. """
  263. SINGLE_STEP = 'single-step'
  264. WORKFLOW_RUN = 'workflow-run'
  265. @classmethod
  266. def value_of(cls, value: str) -> 'WorkflowNodeExecutionTriggeredFrom':
  267. """
  268. Get value of given mode.
  269. :param value: mode value
  270. :return: mode
  271. """
  272. for mode in cls:
  273. if mode.value == value:
  274. return mode
  275. raise ValueError(f'invalid workflow node execution triggered from value {value}')
  276. class WorkflowNodeExecutionStatus(Enum):
  277. """
  278. Workflow Node Execution Status Enum
  279. """
  280. RUNNING = 'running'
  281. SUCCEEDED = 'succeeded'
  282. FAILED = 'failed'
  283. @classmethod
  284. def value_of(cls, value: str) -> 'WorkflowNodeExecutionStatus':
  285. """
  286. Get value of given mode.
  287. :param value: mode value
  288. :return: mode
  289. """
  290. for mode in cls:
  291. if mode.value == value:
  292. return mode
  293. raise ValueError(f'invalid workflow node execution status value {value}')
  294. class WorkflowNodeExecution(db.Model):
  295. """
  296. Workflow Node Execution
  297. - id (uuid) Execution ID
  298. - tenant_id (uuid) Workspace ID
  299. - app_id (uuid) App ID
  300. - workflow_id (uuid) Workflow ID
  301. - triggered_from (string) Trigger source
  302. `single-step` for single-step debugging
  303. `workflow-run` for workflow execution (debugging / user execution)
  304. - workflow_run_id (uuid) `optional` Workflow run ID
  305. Null for single-step debugging.
  306. - index (int) Execution sequence number, used for displaying Tracing Node order
  307. - predecessor_node_id (string) `optional` Predecessor node ID, used for displaying execution path
  308. - node_id (string) Node ID
  309. - node_type (string) Node type, such as `start`
  310. - title (string) Node title
  311. - inputs (json) All predecessor node variable content used in the node
  312. - process_data (json) Node process data
  313. - outputs (json) `optional` Node output variables
  314. - status (string) Execution status, `running` / `succeeded` / `failed`
  315. - error (string) `optional` Error reason
  316. - elapsed_time (float) `optional` Time consumption (s)
  317. - execution_metadata (text) Metadata
  318. - total_tokens (int) `optional` Total tokens used
  319. - total_price (decimal) `optional` Total cost
  320. - currency (string) `optional` Currency, such as USD / RMB
  321. - created_at (timestamp) Run time
  322. - created_by_role (string) Creator role
  323. - `account` Console account
  324. - `end_user` End user
  325. - created_by (uuid) Runner ID
  326. - finished_at (timestamp) End time
  327. """
  328. __tablename__ = 'workflow_node_executions'
  329. __table_args__ = (
  330. db.PrimaryKeyConstraint('id', name='workflow_node_execution_pkey'),
  331. db.Index('workflow_node_execution_workflow_run_idx', 'tenant_id', 'app_id', 'workflow_id',
  332. 'triggered_from', 'workflow_run_id'),
  333. db.Index('workflow_node_execution_node_run_idx', 'tenant_id', 'app_id', 'workflow_id',
  334. 'triggered_from', 'node_id'),
  335. )
  336. id = db.Column(StringUUID, server_default=db.text('uuid_generate_v4()'))
  337. tenant_id = db.Column(StringUUID, nullable=False)
  338. app_id = db.Column(StringUUID, nullable=False)
  339. workflow_id = db.Column(StringUUID, nullable=False)
  340. triggered_from = db.Column(db.String(255), nullable=False)
  341. workflow_run_id = db.Column(StringUUID)
  342. index = db.Column(db.Integer, nullable=False)
  343. predecessor_node_id = db.Column(db.String(255))
  344. node_id = db.Column(db.String(255), nullable=False)
  345. node_type = db.Column(db.String(255), nullable=False)
  346. title = db.Column(db.String(255), nullable=False)
  347. inputs = db.Column(db.Text)
  348. process_data = db.Column(db.Text)
  349. outputs = db.Column(db.Text)
  350. status = db.Column(db.String(255), nullable=False)
  351. error = db.Column(db.Text)
  352. elapsed_time = db.Column(db.Float, nullable=False, server_default=db.text('0'))
  353. execution_metadata = db.Column(db.Text)
  354. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  355. created_by_role = db.Column(db.String(255), nullable=False)
  356. created_by = db.Column(StringUUID, nullable=False)
  357. finished_at = db.Column(db.DateTime)
  358. @property
  359. def created_by_account(self):
  360. created_by_role = CreatedByRole.value_of(self.created_by_role)
  361. return Account.query.get(self.created_by) \
  362. if created_by_role == CreatedByRole.ACCOUNT else None
  363. @property
  364. def created_by_end_user(self):
  365. from models.model import EndUser
  366. created_by_role = CreatedByRole.value_of(self.created_by_role)
  367. return EndUser.query.get(self.created_by) \
  368. if created_by_role == CreatedByRole.END_USER else None
  369. @property
  370. def inputs_dict(self):
  371. return json.loads(self.inputs) if self.inputs else None
  372. @property
  373. def outputs_dict(self):
  374. return json.loads(self.outputs) if self.outputs else None
  375. @property
  376. def process_data_dict(self):
  377. return json.loads(self.process_data) if self.process_data else None
  378. @property
  379. def execution_metadata_dict(self):
  380. return json.loads(self.execution_metadata) if self.execution_metadata else None
  381. @property
  382. def extras(self):
  383. from core.tools.tool_manager import ToolManager
  384. extras = {}
  385. if self.execution_metadata_dict:
  386. from core.workflow.entities.node_entities import NodeType
  387. if self.node_type == NodeType.TOOL.value and 'tool_info' in self.execution_metadata_dict:
  388. tool_info = self.execution_metadata_dict['tool_info']
  389. extras['icon'] = ToolManager.get_tool_icon(
  390. tenant_id=self.tenant_id,
  391. provider_type=tool_info['provider_type'],
  392. provider_id=tool_info['provider_id']
  393. )
  394. return extras
  395. class WorkflowAppLogCreatedFrom(Enum):
  396. """
  397. Workflow App Log Created From Enum
  398. """
  399. SERVICE_API = 'service-api'
  400. WEB_APP = 'web-app'
  401. INSTALLED_APP = 'installed-app'
  402. @classmethod
  403. def value_of(cls, value: str) -> 'WorkflowAppLogCreatedFrom':
  404. """
  405. Get value of given mode.
  406. :param value: mode value
  407. :return: mode
  408. """
  409. for mode in cls:
  410. if mode.value == value:
  411. return mode
  412. raise ValueError(f'invalid workflow app log created from value {value}')
  413. class WorkflowAppLog(db.Model):
  414. """
  415. Workflow App execution log, excluding workflow debugging records.
  416. Attributes:
  417. - id (uuid) run ID
  418. - tenant_id (uuid) Workspace ID
  419. - app_id (uuid) App ID
  420. - workflow_id (uuid) Associated Workflow ID
  421. - workflow_run_id (uuid) Associated Workflow Run ID
  422. - created_from (string) Creation source
  423. `service-api` App Execution OpenAPI
  424. `web-app` WebApp
  425. `installed-app` Installed App
  426. - created_by_role (string) Creator role
  427. - `account` Console account
  428. - `end_user` End user
  429. - created_by (uuid) Creator ID, depends on the user table according to created_by_role
  430. - created_at (timestamp) Creation time
  431. """
  432. __tablename__ = 'workflow_app_logs'
  433. __table_args__ = (
  434. db.PrimaryKeyConstraint('id', name='workflow_app_log_pkey'),
  435. db.Index('workflow_app_log_app_idx', 'tenant_id', 'app_id'),
  436. )
  437. id = db.Column(StringUUID, server_default=db.text('uuid_generate_v4()'))
  438. tenant_id = db.Column(StringUUID, nullable=False)
  439. app_id = db.Column(StringUUID, nullable=False)
  440. workflow_id = db.Column(StringUUID, nullable=False)
  441. workflow_run_id = db.Column(StringUUID, nullable=False)
  442. created_from = db.Column(db.String(255), nullable=False)
  443. created_by_role = db.Column(db.String(255), nullable=False)
  444. created_by = db.Column(StringUUID, nullable=False)
  445. created_at = db.Column(db.DateTime, nullable=False, server_default=db.text('CURRENT_TIMESTAMP(0)'))
  446. @property
  447. def workflow_run(self):
  448. return WorkflowRun.query.get(self.workflow_run_id)
  449. @property
  450. def created_by_account(self):
  451. created_by_role = CreatedByRole.value_of(self.created_by_role)
  452. return Account.query.get(self.created_by) \
  453. if created_by_role == CreatedByRole.ACCOUNT else None
  454. @property
  455. def created_by_end_user(self):
  456. from models.model import EndUser
  457. created_by_role = CreatedByRole.value_of(self.created_by_role)
  458. return EndUser.query.get(self.created_by) \
  459. if created_by_role == CreatedByRole.END_USER else None