Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

workflow.py 46KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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, exists, orm, select
  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.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. stmt = select(
  279. exists().where(
  280. WorkflowToolProvider.tenant_id == self.tenant_id,
  281. WorkflowToolProvider.app_id == self.app_id,
  282. )
  283. )
  284. return db.session.execute(stmt).scalar_one()
  285. @property
  286. def environment_variables(self) -> Sequence[StringVariable | IntegerVariable | FloatVariable | SecretVariable]:
  287. # TODO: find some way to init `self._environment_variables` when instance created.
  288. if self._environment_variables is None:
  289. self._environment_variables = "{}"
  290. # Use workflow.tenant_id to avoid relying on request user in background threads
  291. tenant_id = self.tenant_id
  292. if not tenant_id:
  293. return []
  294. environment_variables_dict: dict[str, Any] = json.loads(self._environment_variables)
  295. results = [
  296. variable_factory.build_environment_variable_from_mapping(v) for v in environment_variables_dict.values()
  297. ]
  298. # decrypt secret variables value
  299. def decrypt_func(var):
  300. if isinstance(var, SecretVariable):
  301. return var.model_copy(update={"value": encrypter.decrypt_token(tenant_id=tenant_id, token=var.value)})
  302. elif isinstance(var, (StringVariable, IntegerVariable, FloatVariable)):
  303. return var
  304. else:
  305. raise AssertionError("this statement should be unreachable.")
  306. decrypted_results: list[SecretVariable | StringVariable | IntegerVariable | FloatVariable] = list(
  307. map(decrypt_func, results)
  308. )
  309. return decrypted_results
  310. @environment_variables.setter
  311. def environment_variables(self, value: Sequence[Variable]):
  312. if not value:
  313. self._environment_variables = "{}"
  314. return
  315. # Use workflow.tenant_id to avoid relying on request user in background threads
  316. tenant_id = self.tenant_id
  317. if not tenant_id:
  318. self._environment_variables = "{}"
  319. return
  320. value = list(value)
  321. if any(var for var in value if not var.id):
  322. raise ValueError("environment variable require a unique id")
  323. # Compare inputs and origin variables,
  324. # if the value is HIDDEN_VALUE, use the origin variable value (only update `name`).
  325. origin_variables_dictionary = {var.id: var for var in self.environment_variables}
  326. for i, variable in enumerate(value):
  327. if variable.id in origin_variables_dictionary and variable.value == HIDDEN_VALUE:
  328. value[i] = origin_variables_dictionary[variable.id].model_copy(update={"name": variable.name})
  329. # encrypt secret variables value
  330. def encrypt_func(var):
  331. if isinstance(var, SecretVariable):
  332. return var.model_copy(update={"value": encrypter.encrypt_token(tenant_id=tenant_id, token=var.value)})
  333. else:
  334. return var
  335. encrypted_vars = list(map(encrypt_func, value))
  336. environment_variables_json = json.dumps(
  337. {var.name: var.model_dump() for var in encrypted_vars},
  338. ensure_ascii=False,
  339. )
  340. self._environment_variables = environment_variables_json
  341. def to_dict(self, *, include_secret: bool = False) -> Mapping[str, Any]:
  342. environment_variables = list(self.environment_variables)
  343. environment_variables = [
  344. v if not isinstance(v, SecretVariable) or include_secret else v.model_copy(update={"value": ""})
  345. for v in environment_variables
  346. ]
  347. result = {
  348. "graph": self.graph_dict,
  349. "features": self.features_dict,
  350. "environment_variables": [var.model_dump(mode="json") for var in environment_variables],
  351. "conversation_variables": [var.model_dump(mode="json") for var in self.conversation_variables],
  352. }
  353. return result
  354. @property
  355. def conversation_variables(self) -> Sequence[Variable]:
  356. # TODO: find some way to init `self._conversation_variables` when instance created.
  357. if self._conversation_variables is None:
  358. self._conversation_variables = "{}"
  359. variables_dict: dict[str, Any] = json.loads(self._conversation_variables)
  360. results = [variable_factory.build_conversation_variable_from_mapping(v) for v in variables_dict.values()]
  361. return results
  362. @conversation_variables.setter
  363. def conversation_variables(self, value: Sequence[Variable]) -> None:
  364. self._conversation_variables = json.dumps(
  365. {var.name: var.model_dump() for var in value},
  366. ensure_ascii=False,
  367. )
  368. @staticmethod
  369. def version_from_datetime(d: datetime) -> str:
  370. return str(d)
  371. class WorkflowRun(Base):
  372. """
  373. Workflow Run
  374. Attributes:
  375. - id (uuid) Run ID
  376. - tenant_id (uuid) Workspace ID
  377. - app_id (uuid) App ID
  378. - workflow_id (uuid) Workflow ID
  379. - type (string) Workflow type
  380. - triggered_from (string) Trigger source
  381. `debugging` for canvas debugging
  382. `app-run` for (published) app execution
  383. - version (string) Version
  384. - graph (text) Workflow canvas configuration (JSON)
  385. - inputs (text) Input parameters
  386. - status (string) Execution status, `running` / `succeeded` / `failed` / `stopped`
  387. - outputs (text) `optional` Output content
  388. - error (string) `optional` Error reason
  389. - elapsed_time (float) `optional` Time consumption (s)
  390. - total_tokens (int) `optional` Total tokens used
  391. - total_steps (int) Total steps (redundant), default 0
  392. - created_by_role (string) Creator role
  393. - `account` Console account
  394. - `end_user` End user
  395. - created_by (uuid) Runner ID
  396. - created_at (timestamp) Run time
  397. - finished_at (timestamp) End time
  398. """
  399. __tablename__ = "workflow_runs"
  400. __table_args__ = (
  401. sa.PrimaryKeyConstraint("id", name="workflow_run_pkey"),
  402. sa.Index("workflow_run_triggerd_from_idx", "tenant_id", "app_id", "triggered_from"),
  403. )
  404. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  405. tenant_id: Mapped[str] = mapped_column(StringUUID)
  406. app_id: Mapped[str] = mapped_column(StringUUID)
  407. workflow_id: Mapped[str] = mapped_column(StringUUID)
  408. type: Mapped[str] = mapped_column(String(255))
  409. triggered_from: Mapped[str] = mapped_column(String(255))
  410. version: Mapped[str] = mapped_column(String(255))
  411. graph: Mapped[Optional[str]] = mapped_column(sa.Text)
  412. inputs: Mapped[Optional[str]] = mapped_column(sa.Text)
  413. status: Mapped[str] = mapped_column(String(255)) # running, succeeded, failed, stopped, partial-succeeded
  414. outputs: Mapped[Optional[str]] = mapped_column(sa.Text, default="{}")
  415. error: Mapped[Optional[str]] = mapped_column(sa.Text)
  416. elapsed_time: Mapped[float] = mapped_column(sa.Float, nullable=False, server_default=sa.text("0"))
  417. total_tokens: Mapped[int] = mapped_column(sa.BigInteger, server_default=sa.text("0"))
  418. total_steps: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"), nullable=True)
  419. created_by_role: Mapped[str] = mapped_column(String(255)) # account, end_user
  420. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  421. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  422. finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
  423. exceptions_count: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"), nullable=True)
  424. @property
  425. def created_by_account(self):
  426. created_by_role = CreatorUserRole(self.created_by_role)
  427. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  428. @property
  429. def created_by_end_user(self):
  430. from models.model import EndUser
  431. created_by_role = CreatorUserRole(self.created_by_role)
  432. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  433. @property
  434. def graph_dict(self) -> Mapping[str, Any]:
  435. return json.loads(self.graph) if self.graph else {}
  436. @property
  437. def inputs_dict(self) -> Mapping[str, Any]:
  438. return json.loads(self.inputs) if self.inputs else {}
  439. @property
  440. def outputs_dict(self) -> Mapping[str, Any]:
  441. return json.loads(self.outputs) if self.outputs else {}
  442. @property
  443. def message(self):
  444. from models.model import Message
  445. return (
  446. db.session.query(Message).where(Message.app_id == self.app_id, Message.workflow_run_id == self.id).first()
  447. )
  448. @property
  449. def workflow(self):
  450. return db.session.query(Workflow).where(Workflow.id == self.workflow_id).first()
  451. def to_dict(self):
  452. return {
  453. "id": self.id,
  454. "tenant_id": self.tenant_id,
  455. "app_id": self.app_id,
  456. "workflow_id": self.workflow_id,
  457. "type": self.type,
  458. "triggered_from": self.triggered_from,
  459. "version": self.version,
  460. "graph": self.graph_dict,
  461. "inputs": self.inputs_dict,
  462. "status": self.status,
  463. "outputs": self.outputs_dict,
  464. "error": self.error,
  465. "elapsed_time": self.elapsed_time,
  466. "total_tokens": self.total_tokens,
  467. "total_steps": self.total_steps,
  468. "created_by_role": self.created_by_role,
  469. "created_by": self.created_by,
  470. "created_at": self.created_at,
  471. "finished_at": self.finished_at,
  472. "exceptions_count": self.exceptions_count,
  473. }
  474. @classmethod
  475. def from_dict(cls, data: dict) -> "WorkflowRun":
  476. return cls(
  477. id=data.get("id"),
  478. tenant_id=data.get("tenant_id"),
  479. app_id=data.get("app_id"),
  480. workflow_id=data.get("workflow_id"),
  481. type=data.get("type"),
  482. triggered_from=data.get("triggered_from"),
  483. version=data.get("version"),
  484. graph=json.dumps(data.get("graph")),
  485. inputs=json.dumps(data.get("inputs")),
  486. status=data.get("status"),
  487. outputs=json.dumps(data.get("outputs")),
  488. error=data.get("error"),
  489. elapsed_time=data.get("elapsed_time"),
  490. total_tokens=data.get("total_tokens"),
  491. total_steps=data.get("total_steps"),
  492. created_by_role=data.get("created_by_role"),
  493. created_by=data.get("created_by"),
  494. created_at=data.get("created_at"),
  495. finished_at=data.get("finished_at"),
  496. exceptions_count=data.get("exceptions_count"),
  497. )
  498. class WorkflowNodeExecutionTriggeredFrom(StrEnum):
  499. """
  500. Workflow Node Execution Triggered From Enum
  501. """
  502. SINGLE_STEP = "single-step"
  503. WORKFLOW_RUN = "workflow-run"
  504. class WorkflowNodeExecutionModel(Base):
  505. """
  506. Workflow Node Execution
  507. - id (uuid) Execution ID
  508. - tenant_id (uuid) Workspace ID
  509. - app_id (uuid) App ID
  510. - workflow_id (uuid) Workflow ID
  511. - triggered_from (string) Trigger source
  512. `single-step` for single-step debugging
  513. `workflow-run` for workflow execution (debugging / user execution)
  514. - workflow_run_id (uuid) `optional` Workflow run ID
  515. Null for single-step debugging.
  516. - index (int) Execution sequence number, used for displaying Tracing Node order
  517. - predecessor_node_id (string) `optional` Predecessor node ID, used for displaying execution path
  518. - node_id (string) Node ID
  519. - node_type (string) Node type, such as `start`
  520. - title (string) Node title
  521. - inputs (json) All predecessor node variable content used in the node
  522. - process_data (json) Node process data
  523. - outputs (json) `optional` Node output variables
  524. - status (string) Execution status, `running` / `succeeded` / `failed`
  525. - error (string) `optional` Error reason
  526. - elapsed_time (float) `optional` Time consumption (s)
  527. - execution_metadata (text) Metadata
  528. - total_tokens (int) `optional` Total tokens used
  529. - total_price (decimal) `optional` Total cost
  530. - currency (string) `optional` Currency, such as USD / RMB
  531. - created_at (timestamp) Run time
  532. - created_by_role (string) Creator role
  533. - `account` Console account
  534. - `end_user` End user
  535. - created_by (uuid) Runner ID
  536. - finished_at (timestamp) End time
  537. """
  538. __tablename__ = "workflow_node_executions"
  539. @declared_attr
  540. def __table_args__(cls): # noqa
  541. return (
  542. PrimaryKeyConstraint("id", name="workflow_node_execution_pkey"),
  543. Index(
  544. "workflow_node_execution_workflow_run_idx",
  545. "tenant_id",
  546. "app_id",
  547. "workflow_id",
  548. "triggered_from",
  549. "workflow_run_id",
  550. ),
  551. Index(
  552. "workflow_node_execution_node_run_idx",
  553. "tenant_id",
  554. "app_id",
  555. "workflow_id",
  556. "triggered_from",
  557. "node_id",
  558. ),
  559. Index(
  560. "workflow_node_execution_id_idx",
  561. "tenant_id",
  562. "app_id",
  563. "workflow_id",
  564. "triggered_from",
  565. "node_execution_id",
  566. ),
  567. Index(
  568. # The first argument is the index name,
  569. # which we leave as `None`` to allow auto-generation by the ORM.
  570. None,
  571. cls.tenant_id,
  572. cls.workflow_id,
  573. cls.node_id,
  574. # MyPy may flag the following line because it doesn't recognize that
  575. # the `declared_attr` decorator passes the receiving class as the first
  576. # argument to this method, allowing us to reference class attributes.
  577. cls.created_at.desc(), # type: ignore
  578. ),
  579. )
  580. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  581. tenant_id: Mapped[str] = mapped_column(StringUUID)
  582. app_id: Mapped[str] = mapped_column(StringUUID)
  583. workflow_id: Mapped[str] = mapped_column(StringUUID)
  584. triggered_from: Mapped[str] = mapped_column(String(255))
  585. workflow_run_id: Mapped[Optional[str]] = mapped_column(StringUUID)
  586. index: Mapped[int] = mapped_column(sa.Integer)
  587. predecessor_node_id: Mapped[Optional[str]] = mapped_column(String(255))
  588. node_execution_id: Mapped[Optional[str]] = mapped_column(String(255))
  589. node_id: Mapped[str] = mapped_column(String(255))
  590. node_type: Mapped[str] = mapped_column(String(255))
  591. title: Mapped[str] = mapped_column(String(255))
  592. inputs: Mapped[Optional[str]] = mapped_column(sa.Text)
  593. process_data: Mapped[Optional[str]] = mapped_column(sa.Text)
  594. outputs: Mapped[Optional[str]] = mapped_column(sa.Text)
  595. status: Mapped[str] = mapped_column(String(255))
  596. error: Mapped[Optional[str]] = mapped_column(sa.Text)
  597. elapsed_time: Mapped[float] = mapped_column(sa.Float, server_default=sa.text("0"))
  598. execution_metadata: Mapped[Optional[str]] = mapped_column(sa.Text)
  599. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.current_timestamp())
  600. created_by_role: Mapped[str] = mapped_column(String(255))
  601. created_by: Mapped[str] = mapped_column(StringUUID)
  602. finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
  603. @property
  604. def created_by_account(self):
  605. created_by_role = CreatorUserRole(self.created_by_role)
  606. # TODO(-LAN-): Avoid using db.session.get() here.
  607. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  608. @property
  609. def created_by_end_user(self):
  610. from models.model import EndUser
  611. created_by_role = CreatorUserRole(self.created_by_role)
  612. # TODO(-LAN-): Avoid using db.session.get() here.
  613. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  614. @property
  615. def inputs_dict(self):
  616. return json.loads(self.inputs) if self.inputs else None
  617. @property
  618. def outputs_dict(self) -> dict[str, Any] | None:
  619. return json.loads(self.outputs) if self.outputs else None
  620. @property
  621. def process_data_dict(self):
  622. return json.loads(self.process_data) if self.process_data else None
  623. @property
  624. def execution_metadata_dict(self) -> dict[str, Any]:
  625. # When the metadata is unset, we return an empty dictionary instead of `None`.
  626. # This approach streamlines the logic for the caller, making it easier to handle
  627. # cases where metadata is absent.
  628. return json.loads(self.execution_metadata) if self.execution_metadata else {}
  629. @property
  630. def extras(self):
  631. from core.tools.tool_manager import ToolManager
  632. extras = {}
  633. if self.execution_metadata_dict:
  634. from core.workflow.nodes import NodeType
  635. if self.node_type == NodeType.TOOL.value and "tool_info" in self.execution_metadata_dict:
  636. tool_info = self.execution_metadata_dict["tool_info"]
  637. extras["icon"] = ToolManager.get_tool_icon(
  638. tenant_id=self.tenant_id,
  639. provider_type=tool_info["provider_type"],
  640. provider_id=tool_info["provider_id"],
  641. )
  642. return extras
  643. class WorkflowAppLogCreatedFrom(Enum):
  644. """
  645. Workflow App Log Created From Enum
  646. """
  647. SERVICE_API = "service-api"
  648. WEB_APP = "web-app"
  649. INSTALLED_APP = "installed-app"
  650. @classmethod
  651. def value_of(cls, value: str) -> "WorkflowAppLogCreatedFrom":
  652. """
  653. Get value of given mode.
  654. :param value: mode value
  655. :return: mode
  656. """
  657. for mode in cls:
  658. if mode.value == value:
  659. return mode
  660. raise ValueError(f"invalid workflow app log created from value {value}")
  661. class WorkflowAppLog(Base):
  662. """
  663. Workflow App execution log, excluding workflow debugging records.
  664. Attributes:
  665. - id (uuid) run ID
  666. - tenant_id (uuid) Workspace ID
  667. - app_id (uuid) App ID
  668. - workflow_id (uuid) Associated Workflow ID
  669. - workflow_run_id (uuid) Associated Workflow Run ID
  670. - created_from (string) Creation source
  671. `service-api` App Execution OpenAPI
  672. `web-app` WebApp
  673. `installed-app` Installed App
  674. - created_by_role (string) Creator role
  675. - `account` Console account
  676. - `end_user` End user
  677. - created_by (uuid) Creator ID, depends on the user table according to created_by_role
  678. - created_at (timestamp) Creation time
  679. """
  680. __tablename__ = "workflow_app_logs"
  681. __table_args__ = (
  682. sa.PrimaryKeyConstraint("id", name="workflow_app_log_pkey"),
  683. sa.Index("workflow_app_log_app_idx", "tenant_id", "app_id"),
  684. )
  685. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  686. tenant_id: Mapped[str] = mapped_column(StringUUID)
  687. app_id: Mapped[str] = mapped_column(StringUUID)
  688. workflow_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  689. workflow_run_id: Mapped[str] = mapped_column(StringUUID)
  690. created_from: Mapped[str] = mapped_column(String(255), nullable=False)
  691. created_by_role: Mapped[str] = mapped_column(String(255), nullable=False)
  692. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  693. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  694. @property
  695. def workflow_run(self):
  696. return db.session.get(WorkflowRun, self.workflow_run_id)
  697. @property
  698. def created_by_account(self):
  699. created_by_role = CreatorUserRole(self.created_by_role)
  700. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  701. @property
  702. def created_by_end_user(self):
  703. from models.model import EndUser
  704. created_by_role = CreatorUserRole(self.created_by_role)
  705. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  706. def to_dict(self):
  707. return {
  708. "id": self.id,
  709. "tenant_id": self.tenant_id,
  710. "app_id": self.app_id,
  711. "workflow_id": self.workflow_id,
  712. "workflow_run_id": self.workflow_run_id,
  713. "created_from": self.created_from,
  714. "created_by_role": self.created_by_role,
  715. "created_by": self.created_by,
  716. "created_at": self.created_at,
  717. }
  718. class ConversationVariable(Base):
  719. __tablename__ = "workflow_conversation_variables"
  720. id: Mapped[str] = mapped_column(StringUUID, primary_key=True)
  721. conversation_id: Mapped[str] = mapped_column(StringUUID, nullable=False, primary_key=True, index=True)
  722. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False, index=True)
  723. data: Mapped[str] = mapped_column(sa.Text, nullable=False)
  724. created_at: Mapped[datetime] = mapped_column(
  725. DateTime, nullable=False, server_default=func.current_timestamp(), index=True
  726. )
  727. updated_at: Mapped[datetime] = mapped_column(
  728. DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp()
  729. )
  730. def __init__(self, *, id: str, app_id: str, conversation_id: str, data: str) -> None:
  731. self.id = id
  732. self.app_id = app_id
  733. self.conversation_id = conversation_id
  734. self.data = data
  735. @classmethod
  736. def from_variable(cls, *, app_id: str, conversation_id: str, variable: Variable) -> "ConversationVariable":
  737. obj = cls(
  738. id=variable.id,
  739. app_id=app_id,
  740. conversation_id=conversation_id,
  741. data=variable.model_dump_json(),
  742. )
  743. return obj
  744. def to_variable(self) -> Variable:
  745. mapping = json.loads(self.data)
  746. return variable_factory.build_conversation_variable_from_mapping(mapping)
  747. # Only `sys.query` and `sys.files` could be modified.
  748. _EDITABLE_SYSTEM_VARIABLE = frozenset(["query", "files"])
  749. def _naive_utc_datetime():
  750. return naive_utc_now()
  751. class WorkflowDraftVariable(Base):
  752. """`WorkflowDraftVariable` record variables and outputs generated during
  753. debugging workflow or chatflow.
  754. IMPORTANT: This model maintains multiple invariant rules that must be preserved.
  755. Do not instantiate this class directly with the constructor.
  756. Instead, use the factory methods (`new_conversation_variable`, `new_sys_variable`,
  757. `new_node_variable`) defined below to ensure all invariants are properly maintained.
  758. """
  759. @staticmethod
  760. def unique_app_id_node_id_name() -> list[str]:
  761. return [
  762. "app_id",
  763. "node_id",
  764. "name",
  765. ]
  766. __tablename__ = "workflow_draft_variables"
  767. __table_args__ = (UniqueConstraint(*unique_app_id_node_id_name()),)
  768. # Required for instance variable annotation.
  769. __allow_unmapped__ = True
  770. # id is the unique identifier of a draft variable.
  771. id: Mapped[str] = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  772. created_at: Mapped[datetime] = mapped_column(
  773. DateTime,
  774. nullable=False,
  775. default=_naive_utc_datetime,
  776. server_default=func.current_timestamp(),
  777. )
  778. updated_at: Mapped[datetime] = mapped_column(
  779. DateTime,
  780. nullable=False,
  781. default=_naive_utc_datetime,
  782. server_default=func.current_timestamp(),
  783. onupdate=func.current_timestamp(),
  784. )
  785. # "`app_id` maps to the `id` field in the `model.App` model."
  786. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  787. # `last_edited_at` records when the value of a given draft variable
  788. # is edited.
  789. #
  790. # If it's not edited after creation, its value is `None`.
  791. last_edited_at: Mapped[datetime | None] = mapped_column(
  792. DateTime,
  793. nullable=True,
  794. default=None,
  795. )
  796. # The `node_id` field is special.
  797. #
  798. # If the variable is a conversation variable or a system variable, then the value of `node_id`
  799. # is `conversation` or `sys`, respective.
  800. #
  801. # Otherwise, if the variable is a variable belonging to a specific node, the value of `_node_id` is
  802. # the identity of correspond node in graph definition. An example of node id is `"1745769620734"`.
  803. #
  804. # However, there's one caveat. The id of the first "Answer" node in chatflow is "answer". (Other
  805. # "Answer" node conform the rules above.)
  806. node_id: Mapped[str] = mapped_column(sa.String(255), nullable=False, name="node_id")
  807. # From `VARIABLE_PATTERN`, we may conclude that the length of a top level variable is less than
  808. # 80 chars.
  809. #
  810. # ref: api/core/workflow/entities/variable_pool.py:18
  811. name: Mapped[str] = mapped_column(sa.String(255), nullable=False)
  812. description: Mapped[str] = mapped_column(
  813. sa.String(255),
  814. default="",
  815. nullable=False,
  816. )
  817. selector: Mapped[str] = mapped_column(sa.String(255), nullable=False, name="selector")
  818. # The data type of this variable's value
  819. value_type: Mapped[SegmentType] = mapped_column(EnumText(SegmentType, length=20))
  820. # The variable's value serialized as a JSON string
  821. value: Mapped[str] = mapped_column(sa.Text, nullable=False, name="value")
  822. # Controls whether the variable should be displayed in the variable inspection panel
  823. visible: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
  824. # Determines whether this variable can be modified by users
  825. editable: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
  826. # The `node_execution_id` field identifies the workflow node execution that created this variable.
  827. # It corresponds to the `id` field in the `WorkflowNodeExecutionModel` model.
  828. #
  829. # This field is not `None` for system variables and node variables, and is `None`
  830. # for conversation variables.
  831. node_execution_id: Mapped[str | None] = mapped_column(
  832. StringUUID,
  833. nullable=True,
  834. default=None,
  835. )
  836. # Cache for deserialized value
  837. #
  838. # NOTE(QuantumGhost): This field serves two purposes:
  839. #
  840. # 1. Caches deserialized values to reduce repeated parsing costs
  841. # 2. Allows modification of the deserialized value after retrieval,
  842. # particularly important for `File`` variables which require database
  843. # lookups to obtain storage_key and other metadata
  844. #
  845. # Use double underscore prefix for better encapsulation,
  846. # making this attribute harder to access from outside the class.
  847. __value: Segment | None
  848. def __init__(self, *args, **kwargs):
  849. """
  850. The constructor of `WorkflowDraftVariable` is not intended for
  851. direct use outside this file. Its solo purpose is setup private state
  852. used by the model instance.
  853. Please use the factory methods
  854. (`new_conversation_variable`, `new_sys_variable`, `new_node_variable`)
  855. defined below to create instances of this class.
  856. """
  857. super().__init__(*args, **kwargs)
  858. self.__value = None
  859. @orm.reconstructor
  860. def _init_on_load(self):
  861. self.__value = None
  862. def get_selector(self) -> list[str]:
  863. selector = json.loads(self.selector)
  864. if not isinstance(selector, list):
  865. logger.error(
  866. "invalid selector loaded from database, type=%s, value=%s",
  867. type(selector),
  868. self.selector,
  869. )
  870. raise ValueError("invalid selector.")
  871. return selector
  872. def _set_selector(self, value: list[str]):
  873. self.selector = json.dumps(value)
  874. def _loads_value(self) -> Segment:
  875. value = json.loads(self.value)
  876. return self.build_segment_with_type(self.value_type, value)
  877. @staticmethod
  878. def rebuild_file_types(value: Any) -> Any:
  879. # NOTE(QuantumGhost): Temporary workaround for structured data handling.
  880. # By this point, `output` has been converted to dict by
  881. # `WorkflowEntry.handle_special_values`, so we need to
  882. # reconstruct File objects from their serialized form
  883. # to maintain proper variable saving behavior.
  884. #
  885. # Ideally, we should work with structured data objects directly
  886. # rather than their serialized forms.
  887. # However, multiple components in the codebase depend on
  888. # `WorkflowEntry.handle_special_values`, making a comprehensive migration challenging.
  889. if isinstance(value, dict):
  890. if not maybe_file_object(value):
  891. return value
  892. return File.model_validate(value)
  893. elif isinstance(value, list) and value:
  894. first = value[0]
  895. if not maybe_file_object(first):
  896. return value
  897. return [File.model_validate(i) for i in value]
  898. else:
  899. return value
  900. @classmethod
  901. def build_segment_with_type(cls, segment_type: SegmentType, value: Any) -> Segment:
  902. # Extends `variable_factory.build_segment_with_type` functionality by
  903. # reconstructing `FileSegment`` or `ArrayFileSegment`` objects from
  904. # their serialized dictionary or list representations, respectively.
  905. if segment_type == SegmentType.FILE:
  906. if isinstance(value, File):
  907. return build_segment_with_type(segment_type, value)
  908. elif isinstance(value, dict):
  909. file = cls.rebuild_file_types(value)
  910. return build_segment_with_type(segment_type, file)
  911. else:
  912. raise TypeMismatchError(f"expected dict or File for FileSegment, got {type(value)}")
  913. if segment_type == SegmentType.ARRAY_FILE:
  914. if not isinstance(value, list):
  915. raise TypeMismatchError(f"expected list for ArrayFileSegment, got {type(value)}")
  916. file_list = cls.rebuild_file_types(value)
  917. return build_segment_with_type(segment_type=segment_type, value=file_list)
  918. return build_segment_with_type(segment_type=segment_type, value=value)
  919. def get_value(self) -> Segment:
  920. """Decode the serialized value into its corresponding `Segment` object.
  921. This method caches the result, so repeated calls will return the same
  922. object instance without re-parsing the serialized data.
  923. If you need to modify the returned `Segment`, use `value.model_copy()`
  924. to create a copy first to avoid affecting the cached instance.
  925. For more information about the caching mechanism, see the documentation
  926. of the `__value` field.
  927. Returns:
  928. Segment: The deserialized value as a Segment object.
  929. """
  930. if self.__value is not None:
  931. return self.__value
  932. value = self._loads_value()
  933. self.__value = value
  934. return value
  935. def set_name(self, name: str):
  936. self.name = name
  937. self._set_selector([self.node_id, name])
  938. def set_value(self, value: Segment):
  939. """Updates the `value` and corresponding `value_type` fields in the database model.
  940. This method also stores the provided Segment object in the deserialized cache
  941. without creating a copy, allowing for efficient value access.
  942. Args:
  943. value: The Segment object to store as the variable's value.
  944. """
  945. self.__value = value
  946. self.value = variable_utils.dumps_with_segments(value)
  947. self.value_type = value.value_type
  948. def get_node_id(self) -> str | None:
  949. if self.get_variable_type() == DraftVariableType.NODE:
  950. return self.node_id
  951. else:
  952. return None
  953. def get_variable_type(self) -> DraftVariableType:
  954. match self.node_id:
  955. case DraftVariableType.CONVERSATION:
  956. return DraftVariableType.CONVERSATION
  957. case DraftVariableType.SYS:
  958. return DraftVariableType.SYS
  959. case _:
  960. return DraftVariableType.NODE
  961. @classmethod
  962. def _new(
  963. cls,
  964. *,
  965. app_id: str,
  966. node_id: str,
  967. name: str,
  968. value: Segment,
  969. node_execution_id: str | None,
  970. description: str = "",
  971. ) -> "WorkflowDraftVariable":
  972. variable = WorkflowDraftVariable()
  973. variable.created_at = _naive_utc_datetime()
  974. variable.updated_at = _naive_utc_datetime()
  975. variable.description = description
  976. variable.app_id = app_id
  977. variable.node_id = node_id
  978. variable.name = name
  979. variable.set_value(value)
  980. variable._set_selector(list(variable_utils.to_selector(node_id, name)))
  981. variable.node_execution_id = node_execution_id
  982. return variable
  983. @classmethod
  984. def new_conversation_variable(
  985. cls,
  986. *,
  987. app_id: str,
  988. name: str,
  989. value: Segment,
  990. description: str = "",
  991. ) -> "WorkflowDraftVariable":
  992. variable = cls._new(
  993. app_id=app_id,
  994. node_id=CONVERSATION_VARIABLE_NODE_ID,
  995. name=name,
  996. value=value,
  997. description=description,
  998. node_execution_id=None,
  999. )
  1000. variable.editable = True
  1001. return variable
  1002. @classmethod
  1003. def new_sys_variable(
  1004. cls,
  1005. *,
  1006. app_id: str,
  1007. name: str,
  1008. value: Segment,
  1009. node_execution_id: str,
  1010. editable: bool = False,
  1011. ) -> "WorkflowDraftVariable":
  1012. variable = cls._new(
  1013. app_id=app_id,
  1014. node_id=SYSTEM_VARIABLE_NODE_ID,
  1015. name=name,
  1016. node_execution_id=node_execution_id,
  1017. value=value,
  1018. )
  1019. variable.editable = editable
  1020. return variable
  1021. @classmethod
  1022. def new_node_variable(
  1023. cls,
  1024. *,
  1025. app_id: str,
  1026. node_id: str,
  1027. name: str,
  1028. value: Segment,
  1029. node_execution_id: str,
  1030. visible: bool = True,
  1031. editable: bool = True,
  1032. ) -> "WorkflowDraftVariable":
  1033. variable = cls._new(
  1034. app_id=app_id,
  1035. node_id=node_id,
  1036. name=name,
  1037. node_execution_id=node_execution_id,
  1038. value=value,
  1039. )
  1040. variable.visible = visible
  1041. variable.editable = editable
  1042. return variable
  1043. @property
  1044. def edited(self):
  1045. return self.last_edited_at is not None
  1046. def is_system_variable_editable(name: str) -> bool:
  1047. return name in _EDITABLE_SYSTEM_VARIABLE