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

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