You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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