workflow.py 17 KB

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