Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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