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 47KB

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