workflow.py 18 KB

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