workflow.py 20 KB

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