You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

workflow.py 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. import json
  2. import logging
  3. from collections.abc import Mapping, Sequence
  4. from datetime import UTC, datetime
  5. from enum import Enum, StrEnum
  6. from typing import TYPE_CHECKING, Any, Optional, Union
  7. from uuid import uuid4
  8. from flask_login import current_user
  9. from sqlalchemy import orm
  10. from core.file.constants import maybe_file_object
  11. from core.file.models import File
  12. from core.variables import utils as variable_utils
  13. from core.variables.variables import FloatVariable, IntegerVariable, StringVariable
  14. from core.workflow.constants import CONVERSATION_VARIABLE_NODE_ID, SYSTEM_VARIABLE_NODE_ID
  15. from core.workflow.nodes.enums import NodeType
  16. from factories.variable_factory import TypeMismatchError, build_segment_with_type
  17. from libs.helper import extract_tenant_id
  18. from ._workflow_exc import NodeNotFoundError, WorkflowDataError
  19. if TYPE_CHECKING:
  20. from models.model import AppMode
  21. import sqlalchemy as sa
  22. from sqlalchemy import Index, PrimaryKeyConstraint, UniqueConstraint, func
  23. from sqlalchemy.orm import Mapped, declared_attr, mapped_column
  24. from constants import DEFAULT_FILE_NUMBER_LIMITS, HIDDEN_VALUE
  25. from core.helper import encrypter
  26. from core.variables import SecretVariable, Segment, SegmentType, Variable
  27. from factories import variable_factory
  28. from libs import helper
  29. from .account import Account
  30. from .base import Base
  31. from .engine import db
  32. from .enums import CreatorUserRole, DraftVariableType
  33. from .types import EnumText, StringUUID
  34. _logger = logging.getLogger(__name__)
  35. if TYPE_CHECKING:
  36. from models.model import AppMode
  37. class WorkflowType(Enum):
  38. """
  39. Workflow Type Enum
  40. """
  41. WORKFLOW = "workflow"
  42. CHAT = "chat"
  43. @classmethod
  44. def value_of(cls, value: str) -> "WorkflowType":
  45. """
  46. Get value of given mode.
  47. :param value: mode value
  48. :return: mode
  49. """
  50. for mode in cls:
  51. if mode.value == value:
  52. return mode
  53. raise ValueError(f"invalid workflow type value {value}")
  54. @classmethod
  55. def from_app_mode(cls, app_mode: Union[str, "AppMode"]) -> "WorkflowType":
  56. """
  57. Get workflow type from app mode.
  58. :param app_mode: app mode
  59. :return: workflow type
  60. """
  61. from models.model import AppMode
  62. app_mode = app_mode if isinstance(app_mode, AppMode) else AppMode.value_of(app_mode)
  63. return cls.WORKFLOW if app_mode == AppMode.WORKFLOW else cls.CHAT
  64. class _InvalidGraphDefinitionError(Exception):
  65. pass
  66. class Workflow(Base):
  67. """
  68. Workflow, for `Workflow App` and `Chat App workflow mode`.
  69. Attributes:
  70. - id (uuid) Workflow ID, pk
  71. - tenant_id (uuid) Workspace ID
  72. - app_id (uuid) App ID
  73. - type (string) Workflow type
  74. `workflow` for `Workflow App`
  75. `chat` for `Chat App workflow mode`
  76. - version (string) Version
  77. `draft` for draft version (only one for each app), other for version number (redundant)
  78. - graph (text) Workflow canvas configuration (JSON)
  79. The entire canvas configuration JSON, including Node, Edge, and other configurations
  80. - nodes (array[object]) Node list, see Node Schema
  81. - edges (array[object]) Edge list, see Edge Schema
  82. - created_by (uuid) Creator ID
  83. - created_at (timestamp) Creation time
  84. - updated_by (uuid) `optional` Last updater ID
  85. - updated_at (timestamp) `optional` Last update time
  86. """
  87. __tablename__ = "workflows"
  88. __table_args__ = (
  89. db.PrimaryKeyConstraint("id", name="workflow_pkey"),
  90. db.Index("workflow_version_idx", "tenant_id", "app_id", "version"),
  91. )
  92. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  93. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  94. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  95. type: Mapped[str] = mapped_column(db.String(255), nullable=False)
  96. version: Mapped[str] = mapped_column(db.String(255), nullable=False)
  97. marked_name: Mapped[str] = mapped_column(default="", server_default="")
  98. marked_comment: Mapped[str] = mapped_column(default="", server_default="")
  99. graph: Mapped[str] = mapped_column(sa.Text)
  100. _features: Mapped[str] = mapped_column("features", sa.TEXT)
  101. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  102. created_at: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  103. updated_by: Mapped[Optional[str]] = mapped_column(StringUUID)
  104. updated_at: Mapped[datetime] = mapped_column(
  105. db.DateTime,
  106. nullable=False,
  107. default=datetime.now(UTC).replace(tzinfo=None),
  108. server_onupdate=func.current_timestamp(),
  109. )
  110. _environment_variables: Mapped[str] = mapped_column(
  111. "environment_variables", db.Text, nullable=False, server_default="{}"
  112. )
  113. _conversation_variables: Mapped[str] = mapped_column(
  114. "conversation_variables", db.Text, nullable=False, server_default="{}"
  115. )
  116. VERSION_DRAFT = "draft"
  117. @classmethod
  118. def new(
  119. cls,
  120. *,
  121. tenant_id: str,
  122. app_id: str,
  123. type: str,
  124. version: str,
  125. graph: str,
  126. features: str,
  127. created_by: str,
  128. environment_variables: Sequence[Variable],
  129. conversation_variables: Sequence[Variable],
  130. marked_name: str = "",
  131. marked_comment: str = "",
  132. ) -> "Workflow":
  133. workflow = Workflow()
  134. workflow.id = str(uuid4())
  135. workflow.tenant_id = tenant_id
  136. workflow.app_id = app_id
  137. workflow.type = type
  138. workflow.version = version
  139. workflow.graph = graph
  140. workflow.features = features
  141. workflow.created_by = created_by
  142. workflow.environment_variables = environment_variables or []
  143. workflow.conversation_variables = conversation_variables or []
  144. workflow.marked_name = marked_name
  145. workflow.marked_comment = marked_comment
  146. workflow.created_at = datetime.now(UTC).replace(tzinfo=None)
  147. workflow.updated_at = workflow.created_at
  148. return workflow
  149. @property
  150. def created_by_account(self):
  151. return db.session.get(Account, self.created_by)
  152. @property
  153. def updated_by_account(self):
  154. return db.session.get(Account, self.updated_by) if self.updated_by else None
  155. @property
  156. def graph_dict(self) -> Mapping[str, Any]:
  157. # TODO(QuantumGhost): Consider caching `graph_dict` to avoid repeated JSON decoding.
  158. #
  159. # Using `functools.cached_property` could help, but some code in the codebase may
  160. # modify the returned dict, which can cause issues elsewhere.
  161. #
  162. # For example, changing this property to a cached property led to errors like the
  163. # following when single stepping an `Iteration` node:
  164. #
  165. # Root node id 1748401971780start not found in the graph
  166. #
  167. # There is currently no standard way to make a dict deeply immutable in Python,
  168. # and tracking modifications to the returned dict is difficult. For now, we leave
  169. # the code as-is to avoid these issues.
  170. #
  171. # Currently, the following functions / methods would mutate the returned dict:
  172. #
  173. # - `_get_graph_and_variable_pool_of_single_iteration`.
  174. # - `_get_graph_and_variable_pool_of_single_loop`.
  175. return json.loads(self.graph) if self.graph else {}
  176. def get_node_config_by_id(self, node_id: str) -> Mapping[str, Any]:
  177. """Extract a node configuration from the workflow graph by node ID.
  178. A node configuration is a dictionary containing the node's properties, including
  179. the node's id, title, and its data as a dict.
  180. """
  181. workflow_graph = self.graph_dict
  182. if not workflow_graph:
  183. raise WorkflowDataError(f"workflow graph not found, workflow_id={self.id}")
  184. nodes = workflow_graph.get("nodes")
  185. if not nodes:
  186. raise WorkflowDataError("nodes not found in workflow graph")
  187. try:
  188. node_config = next(filter(lambda node: node["id"] == node_id, nodes))
  189. except StopIteration:
  190. raise NodeNotFoundError(node_id)
  191. assert isinstance(node_config, dict)
  192. return node_config
  193. @staticmethod
  194. def get_node_type_from_node_config(node_config: Mapping[str, Any]) -> NodeType:
  195. """Extract type of a node from the node configuration returned by `get_node_config_by_id`."""
  196. node_config_data = node_config.get("data", {})
  197. # Get node class
  198. node_type = NodeType(node_config_data.get("type"))
  199. return node_type
  200. @staticmethod
  201. def get_enclosing_node_type_and_id(node_config: Mapping[str, Any]) -> tuple[NodeType, str] | None:
  202. in_loop = node_config.get("isInLoop", False)
  203. in_iteration = node_config.get("isInIteration", False)
  204. if in_loop:
  205. loop_id = node_config.get("loop_id")
  206. if loop_id is None:
  207. raise _InvalidGraphDefinitionError("invalid graph")
  208. return NodeType.LOOP, loop_id
  209. elif in_iteration:
  210. iteration_id = node_config.get("iteration_id")
  211. if iteration_id is None:
  212. raise _InvalidGraphDefinitionError("invalid graph")
  213. return NodeType.ITERATION, iteration_id
  214. else:
  215. return None
  216. @property
  217. def features(self) -> str:
  218. """
  219. Convert old features structure to new features structure.
  220. """
  221. if not self._features:
  222. return self._features
  223. features = json.loads(self._features)
  224. if features.get("file_upload", {}).get("image", {}).get("enabled", False):
  225. image_enabled = True
  226. image_number_limits = int(features["file_upload"]["image"].get("number_limits", DEFAULT_FILE_NUMBER_LIMITS))
  227. image_transfer_methods = features["file_upload"]["image"].get(
  228. "transfer_methods", ["remote_url", "local_file"]
  229. )
  230. features["file_upload"]["enabled"] = image_enabled
  231. features["file_upload"]["number_limits"] = image_number_limits
  232. features["file_upload"]["allowed_file_upload_methods"] = image_transfer_methods
  233. features["file_upload"]["allowed_file_types"] = features["file_upload"].get("allowed_file_types", ["image"])
  234. features["file_upload"]["allowed_file_extensions"] = features["file_upload"].get(
  235. "allowed_file_extensions", []
  236. )
  237. del features["file_upload"]["image"]
  238. self._features = json.dumps(features)
  239. return self._features
  240. @features.setter
  241. def features(self, value: str) -> None:
  242. self._features = value
  243. @property
  244. def features_dict(self) -> dict[str, Any]:
  245. return json.loads(self.features) if self.features else {}
  246. def user_input_form(self, to_old_structure: bool = False) -> list:
  247. # get start node from graph
  248. if not self.graph:
  249. return []
  250. graph_dict = self.graph_dict
  251. if "nodes" not in graph_dict:
  252. return []
  253. start_node = next((node for node in graph_dict["nodes"] if node["data"]["type"] == "start"), None)
  254. if not start_node:
  255. return []
  256. # get user_input_form from start node
  257. variables: list[Any] = start_node.get("data", {}).get("variables", [])
  258. if to_old_structure:
  259. old_structure_variables = []
  260. for variable in variables:
  261. old_structure_variables.append({variable["type"]: variable})
  262. return old_structure_variables
  263. return variables
  264. @property
  265. def unique_hash(self) -> str:
  266. """
  267. Get hash of workflow.
  268. :return: hash
  269. """
  270. entity = {"graph": self.graph_dict, "features": self.features_dict}
  271. return helper.generate_text_hash(json.dumps(entity, sort_keys=True))
  272. @property
  273. def tool_published(self) -> bool:
  274. """
  275. DEPRECATED: This property is not accurate for determining if a workflow is published as a tool.
  276. It only checks if there's a WorkflowToolProvider for the app, not if this specific workflow version
  277. is the one being used by the tool.
  278. For accurate checking, use a direct query with tenant_id, app_id, and version.
  279. """
  280. from models.tools import WorkflowToolProvider
  281. return (
  282. db.session.query(WorkflowToolProvider)
  283. .filter(WorkflowToolProvider.tenant_id == self.tenant_id, WorkflowToolProvider.app_id == self.app_id)
  284. .count()
  285. > 0
  286. )
  287. @property
  288. def environment_variables(self) -> Sequence[StringVariable | IntegerVariable | FloatVariable | SecretVariable]:
  289. # TODO: find some way to init `self._environment_variables` when instance created.
  290. if self._environment_variables is None:
  291. self._environment_variables = "{}"
  292. # Get tenant_id from current_user (Account or EndUser)
  293. tenant_id = extract_tenant_id(current_user)
  294. if not tenant_id:
  295. return []
  296. environment_variables_dict: dict[str, Any] = json.loads(self._environment_variables)
  297. results = [
  298. variable_factory.build_environment_variable_from_mapping(v) for v in environment_variables_dict.values()
  299. ]
  300. # decrypt secret variables value
  301. def decrypt_func(var):
  302. if isinstance(var, SecretVariable):
  303. return var.model_copy(update={"value": encrypter.decrypt_token(tenant_id=tenant_id, token=var.value)})
  304. elif isinstance(var, (StringVariable, IntegerVariable, FloatVariable)):
  305. return var
  306. else:
  307. raise AssertionError("this statement should be unreachable.")
  308. decrypted_results: list[SecretVariable | StringVariable | IntegerVariable | FloatVariable] = list(
  309. map(decrypt_func, results)
  310. )
  311. return decrypted_results
  312. @environment_variables.setter
  313. def environment_variables(self, value: Sequence[Variable]):
  314. if not value:
  315. self._environment_variables = "{}"
  316. return
  317. # Get tenant_id from current_user (Account or EndUser)
  318. tenant_id = extract_tenant_id(current_user)
  319. if not tenant_id:
  320. self._environment_variables = "{}"
  321. return
  322. value = list(value)
  323. if any(var for var in value if not var.id):
  324. raise ValueError("environment variable require a unique id")
  325. # Compare inputs and origin variables,
  326. # if the value is HIDDEN_VALUE, use the origin variable value (only update `name`).
  327. origin_variables_dictionary = {var.id: var for var in self.environment_variables}
  328. for i, variable in enumerate(value):
  329. if variable.id in origin_variables_dictionary and variable.value == HIDDEN_VALUE:
  330. value[i] = origin_variables_dictionary[variable.id].model_copy(update={"name": variable.name})
  331. # encrypt secret variables value
  332. def encrypt_func(var):
  333. if isinstance(var, SecretVariable):
  334. return var.model_copy(update={"value": encrypter.encrypt_token(tenant_id=tenant_id, token=var.value)})
  335. else:
  336. return var
  337. encrypted_vars = list(map(encrypt_func, value))
  338. environment_variables_json = json.dumps(
  339. {var.name: var.model_dump() for var in encrypted_vars},
  340. ensure_ascii=False,
  341. )
  342. self._environment_variables = environment_variables_json
  343. def to_dict(self, *, include_secret: bool = False) -> Mapping[str, Any]:
  344. environment_variables = list(self.environment_variables)
  345. environment_variables = [
  346. v if not isinstance(v, SecretVariable) or include_secret else v.model_copy(update={"value": ""})
  347. for v in environment_variables
  348. ]
  349. result = {
  350. "graph": self.graph_dict,
  351. "features": self.features_dict,
  352. "environment_variables": [var.model_dump(mode="json") for var in environment_variables],
  353. "conversation_variables": [var.model_dump(mode="json") for var in self.conversation_variables],
  354. }
  355. return result
  356. @property
  357. def conversation_variables(self) -> Sequence[Variable]:
  358. # TODO: find some way to init `self._conversation_variables` when instance created.
  359. if self._conversation_variables is None:
  360. self._conversation_variables = "{}"
  361. variables_dict: dict[str, Any] = json.loads(self._conversation_variables)
  362. results = [variable_factory.build_conversation_variable_from_mapping(v) for v in variables_dict.values()]
  363. return results
  364. @conversation_variables.setter
  365. def conversation_variables(self, value: Sequence[Variable]) -> None:
  366. self._conversation_variables = json.dumps(
  367. {var.name: var.model_dump() for var in value},
  368. ensure_ascii=False,
  369. )
  370. @staticmethod
  371. def version_from_datetime(d: datetime) -> str:
  372. return str(d)
  373. class WorkflowRun(Base):
  374. """
  375. Workflow Run
  376. Attributes:
  377. - id (uuid) Run ID
  378. - tenant_id (uuid) Workspace ID
  379. - app_id (uuid) App ID
  380. - workflow_id (uuid) Workflow ID
  381. - type (string) Workflow type
  382. - triggered_from (string) Trigger source
  383. `debugging` for canvas debugging
  384. `app-run` for (published) app execution
  385. - version (string) Version
  386. - graph (text) Workflow canvas configuration (JSON)
  387. - inputs (text) Input parameters
  388. - status (string) Execution status, `running` / `succeeded` / `failed` / `stopped`
  389. - outputs (text) `optional` Output content
  390. - error (string) `optional` Error reason
  391. - elapsed_time (float) `optional` Time consumption (s)
  392. - total_tokens (int) `optional` Total tokens used
  393. - total_steps (int) Total steps (redundant), default 0
  394. - created_by_role (string) Creator role
  395. - `account` Console account
  396. - `end_user` End user
  397. - created_by (uuid) Runner ID
  398. - created_at (timestamp) Run time
  399. - finished_at (timestamp) End time
  400. """
  401. __tablename__ = "workflow_runs"
  402. __table_args__ = (
  403. db.PrimaryKeyConstraint("id", name="workflow_run_pkey"),
  404. db.Index("workflow_run_triggerd_from_idx", "tenant_id", "app_id", "triggered_from"),
  405. )
  406. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  407. tenant_id: Mapped[str] = mapped_column(StringUUID)
  408. app_id: Mapped[str] = mapped_column(StringUUID)
  409. workflow_id: Mapped[str] = mapped_column(StringUUID)
  410. type: Mapped[str] = mapped_column(db.String(255))
  411. triggered_from: Mapped[str] = mapped_column(db.String(255))
  412. version: Mapped[str] = mapped_column(db.String(255))
  413. graph: Mapped[Optional[str]] = mapped_column(db.Text)
  414. inputs: Mapped[Optional[str]] = mapped_column(db.Text)
  415. status: Mapped[str] = mapped_column(db.String(255)) # running, succeeded, failed, stopped, partial-succeeded
  416. outputs: Mapped[Optional[str]] = mapped_column(sa.Text, default="{}")
  417. error: Mapped[Optional[str]] = mapped_column(db.Text)
  418. elapsed_time: Mapped[float] = mapped_column(db.Float, nullable=False, server_default=sa.text("0"))
  419. total_tokens: Mapped[int] = mapped_column(sa.BigInteger, server_default=sa.text("0"))
  420. total_steps: Mapped[int] = mapped_column(db.Integer, server_default=db.text("0"), nullable=True)
  421. created_by_role: Mapped[str] = mapped_column(db.String(255)) # account, end_user
  422. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  423. created_at: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  424. finished_at: Mapped[Optional[datetime]] = mapped_column(db.DateTime)
  425. exceptions_count: Mapped[int] = mapped_column(db.Integer, server_default=db.text("0"), nullable=True)
  426. @property
  427. def created_by_account(self):
  428. created_by_role = CreatorUserRole(self.created_by_role)
  429. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  430. @property
  431. def created_by_end_user(self):
  432. from models.model import EndUser
  433. created_by_role = CreatorUserRole(self.created_by_role)
  434. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  435. @property
  436. def graph_dict(self) -> Mapping[str, Any]:
  437. return json.loads(self.graph) if self.graph else {}
  438. @property
  439. def inputs_dict(self) -> Mapping[str, Any]:
  440. return json.loads(self.inputs) if self.inputs else {}
  441. @property
  442. def outputs_dict(self) -> Mapping[str, Any]:
  443. return json.loads(self.outputs) if self.outputs else {}
  444. @property
  445. def message(self):
  446. from models.model import Message
  447. return (
  448. db.session.query(Message).filter(Message.app_id == self.app_id, Message.workflow_run_id == self.id).first()
  449. )
  450. @property
  451. def workflow(self):
  452. return db.session.query(Workflow).filter(Workflow.id == self.workflow_id).first()
  453. def to_dict(self):
  454. return {
  455. "id": self.id,
  456. "tenant_id": self.tenant_id,
  457. "app_id": self.app_id,
  458. "workflow_id": self.workflow_id,
  459. "type": self.type,
  460. "triggered_from": self.triggered_from,
  461. "version": self.version,
  462. "graph": self.graph_dict,
  463. "inputs": self.inputs_dict,
  464. "status": self.status,
  465. "outputs": self.outputs_dict,
  466. "error": self.error,
  467. "elapsed_time": self.elapsed_time,
  468. "total_tokens": self.total_tokens,
  469. "total_steps": self.total_steps,
  470. "created_by_role": self.created_by_role,
  471. "created_by": self.created_by,
  472. "created_at": self.created_at,
  473. "finished_at": self.finished_at,
  474. "exceptions_count": self.exceptions_count,
  475. }
  476. @classmethod
  477. def from_dict(cls, data: dict) -> "WorkflowRun":
  478. return cls(
  479. id=data.get("id"),
  480. tenant_id=data.get("tenant_id"),
  481. app_id=data.get("app_id"),
  482. workflow_id=data.get("workflow_id"),
  483. type=data.get("type"),
  484. triggered_from=data.get("triggered_from"),
  485. version=data.get("version"),
  486. graph=json.dumps(data.get("graph")),
  487. inputs=json.dumps(data.get("inputs")),
  488. status=data.get("status"),
  489. outputs=json.dumps(data.get("outputs")),
  490. error=data.get("error"),
  491. elapsed_time=data.get("elapsed_time"),
  492. total_tokens=data.get("total_tokens"),
  493. total_steps=data.get("total_steps"),
  494. created_by_role=data.get("created_by_role"),
  495. created_by=data.get("created_by"),
  496. created_at=data.get("created_at"),
  497. finished_at=data.get("finished_at"),
  498. exceptions_count=data.get("exceptions_count"),
  499. )
  500. class WorkflowNodeExecutionTriggeredFrom(StrEnum):
  501. """
  502. Workflow Node Execution Triggered From Enum
  503. """
  504. SINGLE_STEP = "single-step"
  505. WORKFLOW_RUN = "workflow-run"
  506. class WorkflowNodeExecutionModel(Base):
  507. """
  508. Workflow Node Execution
  509. - id (uuid) Execution ID
  510. - tenant_id (uuid) Workspace ID
  511. - app_id (uuid) App ID
  512. - workflow_id (uuid) Workflow ID
  513. - triggered_from (string) Trigger source
  514. `single-step` for single-step debugging
  515. `workflow-run` for workflow execution (debugging / user execution)
  516. - workflow_run_id (uuid) `optional` Workflow run ID
  517. Null for single-step debugging.
  518. - index (int) Execution sequence number, used for displaying Tracing Node order
  519. - predecessor_node_id (string) `optional` Predecessor node ID, used for displaying execution path
  520. - node_id (string) Node ID
  521. - node_type (string) Node type, such as `start`
  522. - title (string) Node title
  523. - inputs (json) All predecessor node variable content used in the node
  524. - process_data (json) Node process data
  525. - outputs (json) `optional` Node output variables
  526. - status (string) Execution status, `running` / `succeeded` / `failed`
  527. - error (string) `optional` Error reason
  528. - elapsed_time (float) `optional` Time consumption (s)
  529. - execution_metadata (text) Metadata
  530. - total_tokens (int) `optional` Total tokens used
  531. - total_price (decimal) `optional` Total cost
  532. - currency (string) `optional` Currency, such as USD / RMB
  533. - created_at (timestamp) Run time
  534. - created_by_role (string) Creator role
  535. - `account` Console account
  536. - `end_user` End user
  537. - created_by (uuid) Runner ID
  538. - finished_at (timestamp) End time
  539. """
  540. __tablename__ = "workflow_node_executions"
  541. @declared_attr
  542. def __table_args__(cls): # noqa
  543. return (
  544. PrimaryKeyConstraint("id", name="workflow_node_execution_pkey"),
  545. Index(
  546. "workflow_node_execution_workflow_run_idx",
  547. "tenant_id",
  548. "app_id",
  549. "workflow_id",
  550. "triggered_from",
  551. "workflow_run_id",
  552. ),
  553. Index(
  554. "workflow_node_execution_node_run_idx",
  555. "tenant_id",
  556. "app_id",
  557. "workflow_id",
  558. "triggered_from",
  559. "node_id",
  560. ),
  561. Index(
  562. "workflow_node_execution_id_idx",
  563. "tenant_id",
  564. "app_id",
  565. "workflow_id",
  566. "triggered_from",
  567. "node_execution_id",
  568. ),
  569. Index(
  570. # The first argument is the index name,
  571. # which we leave as `None`` to allow auto-generation by the ORM.
  572. None,
  573. cls.tenant_id,
  574. cls.workflow_id,
  575. cls.node_id,
  576. # MyPy may flag the following line because it doesn't recognize that
  577. # the `declared_attr` decorator passes the receiving class as the first
  578. # argument to this method, allowing us to reference class attributes.
  579. cls.created_at.desc(), # type: ignore
  580. ),
  581. )
  582. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  583. tenant_id: Mapped[str] = mapped_column(StringUUID)
  584. app_id: Mapped[str] = mapped_column(StringUUID)
  585. workflow_id: Mapped[str] = mapped_column(StringUUID)
  586. triggered_from: Mapped[str] = mapped_column(db.String(255))
  587. workflow_run_id: Mapped[Optional[str]] = mapped_column(StringUUID)
  588. index: Mapped[int] = mapped_column(db.Integer)
  589. predecessor_node_id: Mapped[Optional[str]] = mapped_column(db.String(255))
  590. node_execution_id: Mapped[Optional[str]] = mapped_column(db.String(255))
  591. node_id: Mapped[str] = mapped_column(db.String(255))
  592. node_type: Mapped[str] = mapped_column(db.String(255))
  593. title: Mapped[str] = mapped_column(db.String(255))
  594. inputs: Mapped[Optional[str]] = mapped_column(db.Text)
  595. process_data: Mapped[Optional[str]] = mapped_column(db.Text)
  596. outputs: Mapped[Optional[str]] = mapped_column(db.Text)
  597. status: Mapped[str] = mapped_column(db.String(255))
  598. error: Mapped[Optional[str]] = mapped_column(db.Text)
  599. elapsed_time: Mapped[float] = mapped_column(db.Float, server_default=db.text("0"))
  600. execution_metadata: Mapped[Optional[str]] = mapped_column(db.Text)
  601. created_at: Mapped[datetime] = mapped_column(db.DateTime, server_default=func.current_timestamp())
  602. created_by_role: Mapped[str] = mapped_column(db.String(255))
  603. created_by: Mapped[str] = mapped_column(StringUUID)
  604. finished_at: Mapped[Optional[datetime]] = mapped_column(db.DateTime)
  605. @property
  606. def created_by_account(self):
  607. created_by_role = CreatorUserRole(self.created_by_role)
  608. # TODO(-LAN-): Avoid using db.session.get() here.
  609. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  610. @property
  611. def created_by_end_user(self):
  612. from models.model import EndUser
  613. created_by_role = CreatorUserRole(self.created_by_role)
  614. # TODO(-LAN-): Avoid using db.session.get() here.
  615. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  616. @property
  617. def inputs_dict(self):
  618. return json.loads(self.inputs) if self.inputs else None
  619. @property
  620. def outputs_dict(self) -> dict[str, Any] | None:
  621. return json.loads(self.outputs) if self.outputs else None
  622. @property
  623. def process_data_dict(self):
  624. return json.loads(self.process_data) if self.process_data else None
  625. @property
  626. def execution_metadata_dict(self) -> dict[str, Any]:
  627. # When the metadata is unset, we return an empty dictionary instead of `None`.
  628. # This approach streamlines the logic for the caller, making it easier to handle
  629. # cases where metadata is absent.
  630. return json.loads(self.execution_metadata) if self.execution_metadata else {}
  631. @property
  632. def extras(self):
  633. from core.tools.tool_manager import ToolManager
  634. extras = {}
  635. if self.execution_metadata_dict:
  636. from core.workflow.nodes import NodeType
  637. if self.node_type == NodeType.TOOL.value and "tool_info" in self.execution_metadata_dict:
  638. tool_info = self.execution_metadata_dict["tool_info"]
  639. extras["icon"] = ToolManager.get_tool_icon(
  640. tenant_id=self.tenant_id,
  641. provider_type=tool_info["provider_type"],
  642. provider_id=tool_info["provider_id"],
  643. )
  644. return extras
  645. class WorkflowAppLogCreatedFrom(Enum):
  646. """
  647. Workflow App Log Created From Enum
  648. """
  649. SERVICE_API = "service-api"
  650. WEB_APP = "web-app"
  651. INSTALLED_APP = "installed-app"
  652. @classmethod
  653. def value_of(cls, value: str) -> "WorkflowAppLogCreatedFrom":
  654. """
  655. Get value of given mode.
  656. :param value: mode value
  657. :return: mode
  658. """
  659. for mode in cls:
  660. if mode.value == value:
  661. return mode
  662. raise ValueError(f"invalid workflow app log created from value {value}")
  663. class WorkflowAppLog(Base):
  664. """
  665. Workflow App execution log, excluding workflow debugging records.
  666. Attributes:
  667. - id (uuid) run ID
  668. - tenant_id (uuid) Workspace ID
  669. - app_id (uuid) App ID
  670. - workflow_id (uuid) Associated Workflow ID
  671. - workflow_run_id (uuid) Associated Workflow Run ID
  672. - created_from (string) Creation source
  673. `service-api` App Execution OpenAPI
  674. `web-app` WebApp
  675. `installed-app` Installed App
  676. - created_by_role (string) Creator role
  677. - `account` Console account
  678. - `end_user` End user
  679. - created_by (uuid) Creator ID, depends on the user table according to created_by_role
  680. - created_at (timestamp) Creation time
  681. """
  682. __tablename__ = "workflow_app_logs"
  683. __table_args__ = (
  684. db.PrimaryKeyConstraint("id", name="workflow_app_log_pkey"),
  685. db.Index("workflow_app_log_app_idx", "tenant_id", "app_id"),
  686. )
  687. id: Mapped[str] = mapped_column(StringUUID, server_default=db.text("uuid_generate_v4()"))
  688. tenant_id: Mapped[str] = mapped_column(StringUUID)
  689. app_id: Mapped[str] = mapped_column(StringUUID)
  690. workflow_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  691. workflow_run_id: Mapped[str] = mapped_column(StringUUID)
  692. created_from: Mapped[str] = mapped_column(db.String(255), nullable=False)
  693. created_by_role: Mapped[str] = mapped_column(db.String(255), nullable=False)
  694. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  695. created_at: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, server_default=func.current_timestamp())
  696. @property
  697. def workflow_run(self):
  698. return db.session.get(WorkflowRun, self.workflow_run_id)
  699. @property
  700. def created_by_account(self):
  701. created_by_role = CreatorUserRole(self.created_by_role)
  702. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  703. @property
  704. def created_by_end_user(self):
  705. from models.model import EndUser
  706. created_by_role = CreatorUserRole(self.created_by_role)
  707. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  708. class ConversationVariable(Base):
  709. __tablename__ = "workflow_conversation_variables"
  710. id: Mapped[str] = mapped_column(StringUUID, primary_key=True)
  711. conversation_id: Mapped[str] = mapped_column(StringUUID, nullable=False, primary_key=True, index=True)
  712. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False, index=True)
  713. data: Mapped[str] = mapped_column(db.Text, nullable=False)
  714. created_at: Mapped[datetime] = mapped_column(
  715. db.DateTime, nullable=False, server_default=func.current_timestamp(), index=True
  716. )
  717. updated_at: Mapped[datetime] = mapped_column(
  718. db.DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp()
  719. )
  720. def __init__(self, *, id: str, app_id: str, conversation_id: str, data: str) -> None:
  721. self.id = id
  722. self.app_id = app_id
  723. self.conversation_id = conversation_id
  724. self.data = data
  725. @classmethod
  726. def from_variable(cls, *, app_id: str, conversation_id: str, variable: Variable) -> "ConversationVariable":
  727. obj = cls(
  728. id=variable.id,
  729. app_id=app_id,
  730. conversation_id=conversation_id,
  731. data=variable.model_dump_json(),
  732. )
  733. return obj
  734. def to_variable(self) -> Variable:
  735. mapping = json.loads(self.data)
  736. return variable_factory.build_conversation_variable_from_mapping(mapping)
  737. # Only `sys.query` and `sys.files` could be modified.
  738. _EDITABLE_SYSTEM_VARIABLE = frozenset(["query", "files"])
  739. def _naive_utc_datetime():
  740. return datetime.now(UTC).replace(tzinfo=None)
  741. class WorkflowDraftVariable(Base):
  742. """`WorkflowDraftVariable` record variables and outputs generated during
  743. debugging worfklow or chatflow.
  744. IMPORTANT: This model maintains multiple invariant rules that must be preserved.
  745. Do not instantiate this class directly with the constructor.
  746. Instead, use the factory methods (`new_conversation_variable`, `new_sys_variable`,
  747. `new_node_variable`) defined below to ensure all invariants are properly maintained.
  748. """
  749. @staticmethod
  750. def unique_app_id_node_id_name() -> list[str]:
  751. return [
  752. "app_id",
  753. "node_id",
  754. "name",
  755. ]
  756. __tablename__ = "workflow_draft_variables"
  757. __table_args__ = (UniqueConstraint(*unique_app_id_node_id_name()),)
  758. # Required for instance variable annotation.
  759. __allow_unmapped__ = True
  760. # id is the unique identifier of a draft variable.
  761. id: Mapped[str] = mapped_column(StringUUID, primary_key=True, server_default=db.text("uuid_generate_v4()"))
  762. created_at: Mapped[datetime] = mapped_column(
  763. db.DateTime,
  764. nullable=False,
  765. default=_naive_utc_datetime,
  766. server_default=func.current_timestamp(),
  767. )
  768. updated_at: Mapped[datetime] = mapped_column(
  769. db.DateTime,
  770. nullable=False,
  771. default=_naive_utc_datetime,
  772. server_default=func.current_timestamp(),
  773. onupdate=func.current_timestamp(),
  774. )
  775. # "`app_id` maps to the `id` field in the `model.App` model."
  776. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  777. # `last_edited_at` records when the value of a given draft variable
  778. # is edited.
  779. #
  780. # If it's not edited after creation, its value is `None`.
  781. last_edited_at: Mapped[datetime | None] = mapped_column(
  782. db.DateTime,
  783. nullable=True,
  784. default=None,
  785. )
  786. # The `node_id` field is special.
  787. #
  788. # If the variable is a conversation variable or a system variable, then the value of `node_id`
  789. # is `conversation` or `sys`, respective.
  790. #
  791. # Otherwise, if the variable is a variable belonging to a specific node, the value of `_node_id` is
  792. # the identity of correspond node in graph definition. An example of node id is `"1745769620734"`.
  793. #
  794. # However, there's one caveat. The id of the first "Answer" node in chatflow is "answer". (Other
  795. # "Answer" node conform the rules above.)
  796. node_id: Mapped[str] = mapped_column(sa.String(255), nullable=False, name="node_id")
  797. # From `VARIABLE_PATTERN`, we may conclude that the length of a top level variable is less than
  798. # 80 chars.
  799. #
  800. # ref: api/core/workflow/entities/variable_pool.py:18
  801. name: Mapped[str] = mapped_column(sa.String(255), nullable=False)
  802. description: Mapped[str] = mapped_column(
  803. sa.String(255),
  804. default="",
  805. nullable=False,
  806. )
  807. selector: Mapped[str] = mapped_column(sa.String(255), nullable=False, name="selector")
  808. # The data type of this variable's value
  809. value_type: Mapped[SegmentType] = mapped_column(EnumText(SegmentType, length=20))
  810. # The variable's value serialized as a JSON string
  811. value: Mapped[str] = mapped_column(sa.Text, nullable=False, name="value")
  812. # Controls whether the variable should be displayed in the variable inspection panel
  813. visible: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
  814. # Determines whether this variable can be modified by users
  815. editable: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
  816. # The `node_execution_id` field identifies the workflow node execution that created this variable.
  817. # It corresponds to the `id` field in the `WorkflowNodeExecutionModel` model.
  818. #
  819. # This field is not `None` for system variables and node variables, and is `None`
  820. # for conversation variables.
  821. node_execution_id: Mapped[str | None] = mapped_column(
  822. StringUUID,
  823. nullable=True,
  824. default=None,
  825. )
  826. # Cache for deserialized value
  827. #
  828. # NOTE(QuantumGhost): This field serves two purposes:
  829. #
  830. # 1. Caches deserialized values to reduce repeated parsing costs
  831. # 2. Allows modification of the deserialized value after retrieval,
  832. # particularly important for `File`` variables which require database
  833. # lookups to obtain storage_key and other metadata
  834. #
  835. # Use double underscore prefix for better encapsulation,
  836. # making this attribute harder to access from outside the class.
  837. __value: Segment | None
  838. def __init__(self, *args, **kwargs):
  839. """
  840. The constructor of `WorkflowDraftVariable` is not intended for
  841. direct use outside this file. Its solo purpose is setup private state
  842. used by the model instance.
  843. Please use the factory methods
  844. (`new_conversation_variable`, `new_sys_variable`, `new_node_variable`)
  845. defined below to create instances of this class.
  846. """
  847. super().__init__(*args, **kwargs)
  848. self.__value = None
  849. @orm.reconstructor
  850. def _init_on_load(self):
  851. self.__value = None
  852. def get_selector(self) -> list[str]:
  853. selector = json.loads(self.selector)
  854. if not isinstance(selector, list):
  855. _logger.error(
  856. "invalid selector loaded from database, type=%s, value=%s",
  857. type(selector),
  858. self.selector,
  859. )
  860. raise ValueError("invalid selector.")
  861. return selector
  862. def _set_selector(self, value: list[str]):
  863. self.selector = json.dumps(value)
  864. def _loads_value(self) -> Segment:
  865. value = json.loads(self.value)
  866. return self.build_segment_with_type(self.value_type, value)
  867. @staticmethod
  868. def rebuild_file_types(value: Any) -> Any:
  869. # NOTE(QuantumGhost): Temporary workaround for structured data handling.
  870. # By this point, `output` has been converted to dict by
  871. # `WorkflowEntry.handle_special_values`, so we need to
  872. # reconstruct File objects from their serialized form
  873. # to maintain proper variable saving behavior.
  874. #
  875. # Ideally, we should work with structured data objects directly
  876. # rather than their serialized forms.
  877. # However, multiple components in the codebase depend on
  878. # `WorkflowEntry.handle_special_values`, making a comprehensive migration challenging.
  879. if isinstance(value, dict):
  880. if not maybe_file_object(value):
  881. return value
  882. return File.model_validate(value)
  883. elif isinstance(value, list) and value:
  884. first = value[0]
  885. if not maybe_file_object(first):
  886. return value
  887. return [File.model_validate(i) for i in value]
  888. else:
  889. return value
  890. @classmethod
  891. def build_segment_with_type(cls, segment_type: SegmentType, value: Any) -> Segment:
  892. # Extends `variable_factory.build_segment_with_type` functionality by
  893. # reconstructing `FileSegment`` or `ArrayFileSegment`` objects from
  894. # their serialized dictionary or list representations, respectively.
  895. if segment_type == SegmentType.FILE:
  896. if isinstance(value, File):
  897. return build_segment_with_type(segment_type, value)
  898. elif isinstance(value, dict):
  899. file = cls.rebuild_file_types(value)
  900. return build_segment_with_type(segment_type, file)
  901. else:
  902. raise TypeMismatchError(f"expected dict or File for FileSegment, got {type(value)}")
  903. if segment_type == SegmentType.ARRAY_FILE:
  904. if not isinstance(value, list):
  905. raise TypeMismatchError(f"expected list for ArrayFileSegment, got {type(value)}")
  906. file_list = cls.rebuild_file_types(value)
  907. return build_segment_with_type(segment_type=segment_type, value=file_list)
  908. return build_segment_with_type(segment_type=segment_type, value=value)
  909. def get_value(self) -> Segment:
  910. """Decode the serialized value into its corresponding `Segment` object.
  911. This method caches the result, so repeated calls will return the same
  912. object instance without re-parsing the serialized data.
  913. If you need to modify the returned `Segment`, use `value.model_copy()`
  914. to create a copy first to avoid affecting the cached instance.
  915. For more information about the caching mechanism, see the documentation
  916. of the `__value` field.
  917. Returns:
  918. Segment: The deserialized value as a Segment object.
  919. """
  920. if self.__value is not None:
  921. return self.__value
  922. value = self._loads_value()
  923. self.__value = value
  924. return value
  925. def set_name(self, name: str):
  926. self.name = name
  927. self._set_selector([self.node_id, name])
  928. def set_value(self, value: Segment):
  929. """Updates the `value` and corresponding `value_type` fields in the database model.
  930. This method also stores the provided Segment object in the deserialized cache
  931. without creating a copy, allowing for efficient value access.
  932. Args:
  933. value: The Segment object to store as the variable's value.
  934. """
  935. self.__value = value
  936. self.value = json.dumps(value, cls=variable_utils.SegmentJSONEncoder)
  937. self.value_type = value.value_type
  938. def get_node_id(self) -> str | None:
  939. if self.get_variable_type() == DraftVariableType.NODE:
  940. return self.node_id
  941. else:
  942. return None
  943. def get_variable_type(self) -> DraftVariableType:
  944. match self.node_id:
  945. case DraftVariableType.CONVERSATION:
  946. return DraftVariableType.CONVERSATION
  947. case DraftVariableType.SYS:
  948. return DraftVariableType.SYS
  949. case _:
  950. return DraftVariableType.NODE
  951. @classmethod
  952. def _new(
  953. cls,
  954. *,
  955. app_id: str,
  956. node_id: str,
  957. name: str,
  958. value: Segment,
  959. node_execution_id: str | None,
  960. description: str = "",
  961. ) -> "WorkflowDraftVariable":
  962. variable = WorkflowDraftVariable()
  963. variable.created_at = _naive_utc_datetime()
  964. variable.updated_at = _naive_utc_datetime()
  965. variable.description = description
  966. variable.app_id = app_id
  967. variable.node_id = node_id
  968. variable.name = name
  969. variable.set_value(value)
  970. variable._set_selector(list(variable_utils.to_selector(node_id, name)))
  971. variable.node_execution_id = node_execution_id
  972. return variable
  973. @classmethod
  974. def new_conversation_variable(
  975. cls,
  976. *,
  977. app_id: str,
  978. name: str,
  979. value: Segment,
  980. description: str = "",
  981. ) -> "WorkflowDraftVariable":
  982. variable = cls._new(
  983. app_id=app_id,
  984. node_id=CONVERSATION_VARIABLE_NODE_ID,
  985. name=name,
  986. value=value,
  987. description=description,
  988. node_execution_id=None,
  989. )
  990. variable.editable = True
  991. return variable
  992. @classmethod
  993. def new_sys_variable(
  994. cls,
  995. *,
  996. app_id: str,
  997. name: str,
  998. value: Segment,
  999. node_execution_id: str,
  1000. editable: bool = False,
  1001. ) -> "WorkflowDraftVariable":
  1002. variable = cls._new(
  1003. app_id=app_id,
  1004. node_id=SYSTEM_VARIABLE_NODE_ID,
  1005. name=name,
  1006. node_execution_id=node_execution_id,
  1007. value=value,
  1008. )
  1009. variable.editable = editable
  1010. return variable
  1011. @classmethod
  1012. def new_node_variable(
  1013. cls,
  1014. *,
  1015. app_id: str,
  1016. node_id: str,
  1017. name: str,
  1018. value: Segment,
  1019. node_execution_id: str,
  1020. visible: bool = True,
  1021. editable: bool = True,
  1022. ) -> "WorkflowDraftVariable":
  1023. variable = cls._new(
  1024. app_id=app_id,
  1025. node_id=node_id,
  1026. name=name,
  1027. node_execution_id=node_execution_id,
  1028. value=value,
  1029. )
  1030. variable.visible = visible
  1031. variable.editable = editable
  1032. return variable
  1033. @property
  1034. def edited(self):
  1035. return self.last_edited_at is not None
  1036. def is_system_variable_editable(name: str) -> bool:
  1037. return name in _EDITABLE_SYSTEM_VARIABLE