Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

workflow.py 46KB

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