Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

workflow.py 59KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  1. import json
  2. import logging
  3. from collections.abc import Mapping, Sequence
  4. from datetime import datetime
  5. from enum import StrEnum
  6. from typing import TYPE_CHECKING, Any, Optional, Union, cast
  7. from uuid import uuid4
  8. import sqlalchemy as sa
  9. from sqlalchemy import DateTime, Select, 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 extensions.ext_storage import Storage
  17. from factories.variable_factory import TypeMismatchError, build_segment_with_type
  18. from libs.datetime_utils import naive_utc_now
  19. from libs.uuid_utils import uuidv7
  20. from ._workflow_exc import NodeNotFoundError, WorkflowDataError
  21. if TYPE_CHECKING:
  22. from models.model import AppMode, UploadFile
  23. from sqlalchemy import Index, PrimaryKeyConstraint, String, UniqueConstraint, func
  24. from sqlalchemy.orm import Mapped, declared_attr, mapped_column
  25. from constants import DEFAULT_FILE_NUMBER_LIMITS, HIDDEN_VALUE
  26. from core.helper import encrypter
  27. from core.variables import SecretVariable, Segment, SegmentType, Variable
  28. from factories import variable_factory
  29. from libs import helper
  30. from .account import Account
  31. from .base import Base
  32. from .engine import db
  33. from .enums import CreatorUserRole, DraftVariableType, ExecutionOffLoadType
  34. from .types import EnumText, StringUUID
  35. logger = logging.getLogger(__name__)
  36. class WorkflowType(StrEnum):
  37. """
  38. Workflow Type Enum
  39. """
  40. WORKFLOW = "workflow"
  41. CHAT = "chat"
  42. RAG_PIPELINE = "rag-pipeline"
  43. @classmethod
  44. def value_of(cls, value: str) -> "WorkflowType":
  45. """
  46. Get value of given mode.
  47. :param value: mode value
  48. :return: mode
  49. """
  50. for mode in cls:
  51. if mode.value == value:
  52. return mode
  53. raise ValueError(f"invalid workflow type value {value}")
  54. @classmethod
  55. def from_app_mode(cls, app_mode: Union[str, "AppMode"]) -> "WorkflowType":
  56. """
  57. Get workflow type from app mode.
  58. :param app_mode: app mode
  59. :return: workflow type
  60. """
  61. from models.model import AppMode
  62. app_mode = app_mode if isinstance(app_mode, AppMode) else AppMode.value_of(app_mode)
  63. return cls.WORKFLOW if app_mode == AppMode.WORKFLOW else cls.CHAT
  64. class _InvalidGraphDefinitionError(Exception):
  65. pass
  66. class Workflow(Base):
  67. """
  68. Workflow, for `Workflow App` and `Chat App workflow mode`.
  69. Attributes:
  70. - id (uuid) Workflow ID, pk
  71. - tenant_id (uuid) Workspace ID
  72. - app_id (uuid) App ID
  73. - type (string) Workflow type
  74. `workflow` for `Workflow App`
  75. `chat` for `Chat App workflow mode`
  76. - version (string) Version
  77. `draft` for draft version (only one for each app), other for version number (redundant)
  78. - graph (text) Workflow canvas configuration (JSON)
  79. The entire canvas configuration JSON, including Node, Edge, and other configurations
  80. - nodes (array[object]) Node list, see Node Schema
  81. - edges (array[object]) Edge list, see Edge Schema
  82. - created_by (uuid) Creator ID
  83. - created_at (timestamp) Creation time
  84. - updated_by (uuid) `optional` Last updater ID
  85. - updated_at (timestamp) `optional` Last update time
  86. """
  87. __tablename__ = "workflows"
  88. __table_args__ = (
  89. sa.PrimaryKeyConstraint("id", name="workflow_pkey"),
  90. sa.Index("workflow_version_idx", "tenant_id", "app_id", "version"),
  91. )
  92. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  93. tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  94. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  95. type: Mapped[str] = mapped_column(String(255), nullable=False)
  96. version: Mapped[str] = mapped_column(String(255), nullable=False)
  97. marked_name: Mapped[str] = mapped_column(default="", server_default="")
  98. marked_comment: Mapped[str] = mapped_column(default="", server_default="")
  99. graph: Mapped[str] = mapped_column(sa.Text)
  100. _features: Mapped[str] = mapped_column("features", sa.TEXT)
  101. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  102. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  103. updated_by: Mapped[str | None] = mapped_column(StringUUID)
  104. updated_at: Mapped[datetime] = mapped_column(
  105. DateTime,
  106. nullable=False,
  107. default=naive_utc_now(),
  108. server_onupdate=func.current_timestamp(),
  109. )
  110. _environment_variables: Mapped[str] = mapped_column(
  111. "environment_variables", sa.Text, nullable=False, server_default="{}"
  112. )
  113. _conversation_variables: Mapped[str] = mapped_column(
  114. "conversation_variables", sa.Text, nullable=False, server_default="{}"
  115. )
  116. _rag_pipeline_variables: Mapped[str] = mapped_column(
  117. "rag_pipeline_variables", db.Text, nullable=False, server_default="{}"
  118. )
  119. VERSION_DRAFT = "draft"
  120. @classmethod
  121. def new(
  122. cls,
  123. *,
  124. tenant_id: str,
  125. app_id: str,
  126. type: str,
  127. version: str,
  128. graph: str,
  129. features: str,
  130. created_by: str,
  131. environment_variables: Sequence[Variable],
  132. conversation_variables: Sequence[Variable],
  133. rag_pipeline_variables: list[dict],
  134. marked_name: str = "",
  135. marked_comment: str = "",
  136. ) -> "Workflow":
  137. workflow = Workflow()
  138. workflow.id = str(uuid4())
  139. workflow.tenant_id = tenant_id
  140. workflow.app_id = app_id
  141. workflow.type = type
  142. workflow.version = version
  143. workflow.graph = graph
  144. workflow.features = features
  145. workflow.created_by = created_by
  146. workflow.environment_variables = environment_variables or []
  147. workflow.conversation_variables = conversation_variables or []
  148. workflow.rag_pipeline_variables = rag_pipeline_variables or []
  149. workflow.marked_name = marked_name
  150. workflow.marked_comment = marked_comment
  151. workflow.created_at = naive_utc_now()
  152. workflow.updated_at = workflow.created_at
  153. return workflow
  154. @property
  155. def created_by_account(self):
  156. return db.session.get(Account, self.created_by)
  157. @property
  158. def updated_by_account(self):
  159. return db.session.get(Account, self.updated_by) if self.updated_by else None
  160. @property
  161. def graph_dict(self) -> Mapping[str, Any]:
  162. # TODO(QuantumGhost): Consider caching `graph_dict` to avoid repeated JSON decoding.
  163. #
  164. # Using `functools.cached_property` could help, but some code in the codebase may
  165. # modify the returned dict, which can cause issues elsewhere.
  166. #
  167. # For example, changing this property to a cached property led to errors like the
  168. # following when single stepping an `Iteration` node:
  169. #
  170. # Root node id 1748401971780start not found in the graph
  171. #
  172. # There is currently no standard way to make a dict deeply immutable in Python,
  173. # and tracking modifications to the returned dict is difficult. For now, we leave
  174. # the code as-is to avoid these issues.
  175. #
  176. # Currently, the following functions / methods would mutate the returned dict:
  177. #
  178. # - `_get_graph_and_variable_pool_of_single_iteration`.
  179. # - `_get_graph_and_variable_pool_of_single_loop`.
  180. return json.loads(self.graph) if self.graph else {}
  181. def get_node_config_by_id(self, node_id: str) -> Mapping[str, Any]:
  182. """Extract a node configuration from the workflow graph by node ID.
  183. A node configuration is a dictionary containing the node's properties, including
  184. the node's id, title, and its data as a dict.
  185. """
  186. workflow_graph = self.graph_dict
  187. if not workflow_graph:
  188. raise WorkflowDataError(f"workflow graph not found, workflow_id={self.id}")
  189. nodes = workflow_graph.get("nodes")
  190. if not nodes:
  191. raise WorkflowDataError("nodes not found in workflow graph")
  192. try:
  193. node_config: dict[str, Any] = next(filter(lambda node: node["id"] == node_id, nodes))
  194. except StopIteration:
  195. raise NodeNotFoundError(node_id)
  196. assert isinstance(node_config, dict)
  197. return node_config
  198. @staticmethod
  199. def get_node_type_from_node_config(node_config: Mapping[str, Any]) -> NodeType:
  200. """Extract type of a node from the node configuration returned by `get_node_config_by_id`."""
  201. node_config_data = node_config.get("data", {})
  202. # Get node class
  203. node_type = NodeType(node_config_data.get("type"))
  204. return node_type
  205. @staticmethod
  206. def get_enclosing_node_type_and_id(node_config: Mapping[str, Any]) -> tuple[NodeType, str] | None:
  207. in_loop = node_config.get("isInLoop", False)
  208. in_iteration = node_config.get("isInIteration", False)
  209. if in_loop:
  210. loop_id = node_config.get("loop_id")
  211. if loop_id is None:
  212. raise _InvalidGraphDefinitionError("invalid graph")
  213. return NodeType.LOOP, loop_id
  214. elif in_iteration:
  215. iteration_id = node_config.get("iteration_id")
  216. if iteration_id is None:
  217. raise _InvalidGraphDefinitionError("invalid graph")
  218. return NodeType.ITERATION, iteration_id
  219. else:
  220. return None
  221. @property
  222. def features(self) -> str:
  223. """
  224. Convert old features structure to new features structure.
  225. """
  226. if not self._features:
  227. return self._features
  228. features = json.loads(self._features)
  229. if features.get("file_upload", {}).get("image", {}).get("enabled", False):
  230. image_enabled = True
  231. image_number_limits = int(features["file_upload"]["image"].get("number_limits", DEFAULT_FILE_NUMBER_LIMITS))
  232. image_transfer_methods = features["file_upload"]["image"].get(
  233. "transfer_methods", ["remote_url", "local_file"]
  234. )
  235. features["file_upload"]["enabled"] = image_enabled
  236. features["file_upload"]["number_limits"] = image_number_limits
  237. features["file_upload"]["allowed_file_upload_methods"] = image_transfer_methods
  238. features["file_upload"]["allowed_file_types"] = features["file_upload"].get("allowed_file_types", ["image"])
  239. features["file_upload"]["allowed_file_extensions"] = features["file_upload"].get(
  240. "allowed_file_extensions", []
  241. )
  242. del features["file_upload"]["image"]
  243. self._features = json.dumps(features)
  244. return self._features
  245. @features.setter
  246. def features(self, value: str):
  247. self._features = value
  248. @property
  249. def features_dict(self) -> dict[str, Any]:
  250. return json.loads(self.features) if self.features else {}
  251. def user_input_form(self, to_old_structure: bool = False) -> list[Any]:
  252. # get start node from graph
  253. if not self.graph:
  254. return []
  255. graph_dict = self.graph_dict
  256. if "nodes" not in graph_dict:
  257. return []
  258. start_node = next((node for node in graph_dict["nodes"] if node["data"]["type"] == "start"), None)
  259. if not start_node:
  260. return []
  261. # get user_input_form from start node
  262. variables: list[Any] = start_node.get("data", {}).get("variables", [])
  263. if to_old_structure:
  264. old_structure_variables: list[dict[str, Any]] = []
  265. for variable in variables:
  266. old_structure_variables.append({variable["type"]: variable})
  267. return old_structure_variables
  268. return variables
  269. def rag_pipeline_user_input_form(self) -> list:
  270. # get user_input_form from start node
  271. variables: list[Any] = self.rag_pipeline_variables
  272. return variables
  273. @property
  274. def unique_hash(self) -> str:
  275. """
  276. Get hash of workflow.
  277. :return: hash
  278. """
  279. entity = {"graph": self.graph_dict, "features": self.features_dict}
  280. return helper.generate_text_hash(json.dumps(entity, sort_keys=True))
  281. @property
  282. def tool_published(self) -> bool:
  283. """
  284. DEPRECATED: This property is not accurate for determining if a workflow is published as a tool.
  285. It only checks if there's a WorkflowToolProvider for the app, not if this specific workflow version
  286. is the one being used by the tool.
  287. For accurate checking, use a direct query with tenant_id, app_id, and version.
  288. """
  289. from models.tools import WorkflowToolProvider
  290. stmt = select(
  291. exists().where(
  292. WorkflowToolProvider.tenant_id == self.tenant_id,
  293. WorkflowToolProvider.app_id == self.app_id,
  294. )
  295. )
  296. return db.session.execute(stmt).scalar_one()
  297. @property
  298. def environment_variables(self) -> Sequence[StringVariable | IntegerVariable | FloatVariable | SecretVariable]:
  299. # _environment_variables is guaranteed to be non-None due to server_default="{}"
  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 or "{}")
  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: Variable) -> StringVariable | IntegerVariable | FloatVariable | SecretVariable:
  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. # Other variable types are not supported for environment variables
  316. raise AssertionError(f"Unexpected variable type for environment variable: {type(var)}")
  317. decrypted_results: list[SecretVariable | StringVariable | IntegerVariable | FloatVariable] = [
  318. decrypt_func(var) for var in results
  319. ]
  320. return decrypted_results
  321. @environment_variables.setter
  322. def environment_variables(self, value: Sequence[Variable]):
  323. if not value:
  324. self._environment_variables = "{}"
  325. return
  326. # Use workflow.tenant_id to avoid relying on request user in background threads
  327. tenant_id = self.tenant_id
  328. if not tenant_id:
  329. self._environment_variables = "{}"
  330. return
  331. value = list(value)
  332. if any(var for var in value if not var.id):
  333. raise ValueError("environment variable require a unique id")
  334. # Compare inputs and origin variables,
  335. # if the value is HIDDEN_VALUE, use the origin variable value (only update `name`).
  336. origin_variables_dictionary = {var.id: var for var in self.environment_variables}
  337. for i, variable in enumerate(value):
  338. if variable.id in origin_variables_dictionary and variable.value == HIDDEN_VALUE:
  339. value[i] = origin_variables_dictionary[variable.id].model_copy(update={"name": variable.name})
  340. # encrypt secret variables value
  341. def encrypt_func(var: Variable) -> Variable:
  342. if isinstance(var, SecretVariable):
  343. return var.model_copy(update={"value": encrypter.encrypt_token(tenant_id=tenant_id, token=var.value)})
  344. else:
  345. return var
  346. encrypted_vars = list(map(encrypt_func, value))
  347. environment_variables_json = json.dumps(
  348. {var.name: var.model_dump() for var in encrypted_vars},
  349. ensure_ascii=False,
  350. )
  351. self._environment_variables = environment_variables_json
  352. def to_dict(self, *, include_secret: bool = False) -> Mapping[str, Any]:
  353. environment_variables = list(self.environment_variables)
  354. environment_variables = [
  355. v if not isinstance(v, SecretVariable) or include_secret else v.model_copy(update={"value": ""})
  356. for v in environment_variables
  357. ]
  358. result = {
  359. "graph": self.graph_dict,
  360. "features": self.features_dict,
  361. "environment_variables": [var.model_dump(mode="json") for var in environment_variables],
  362. "conversation_variables": [var.model_dump(mode="json") for var in self.conversation_variables],
  363. "rag_pipeline_variables": self.rag_pipeline_variables,
  364. }
  365. return result
  366. @property
  367. def conversation_variables(self) -> Sequence[Variable]:
  368. # _conversation_variables is guaranteed to be non-None due to server_default="{}"
  369. variables_dict: dict[str, Any] = json.loads(self._conversation_variables)
  370. results = [variable_factory.build_conversation_variable_from_mapping(v) for v in variables_dict.values()]
  371. return results
  372. @conversation_variables.setter
  373. def conversation_variables(self, value: Sequence[Variable]):
  374. self._conversation_variables = json.dumps(
  375. {var.name: var.model_dump() for var in value},
  376. ensure_ascii=False,
  377. )
  378. @property
  379. def rag_pipeline_variables(self) -> list[dict]:
  380. # TODO: find some way to init `self._conversation_variables` when instance created.
  381. if self._rag_pipeline_variables is None:
  382. self._rag_pipeline_variables = "{}"
  383. variables_dict: dict[str, Any] = json.loads(self._rag_pipeline_variables)
  384. results = list(variables_dict.values())
  385. return results
  386. @rag_pipeline_variables.setter
  387. def rag_pipeline_variables(self, values: list[dict]) -> None:
  388. self._rag_pipeline_variables = json.dumps(
  389. {item["variable"]: item for item in values},
  390. ensure_ascii=False,
  391. )
  392. @staticmethod
  393. def version_from_datetime(d: datetime) -> str:
  394. return str(d)
  395. class WorkflowRun(Base):
  396. """
  397. Workflow Run
  398. Attributes:
  399. - id (uuid) Run ID
  400. - tenant_id (uuid) Workspace ID
  401. - app_id (uuid) App ID
  402. - workflow_id (uuid) Workflow ID
  403. - type (string) Workflow type
  404. - triggered_from (string) Trigger source
  405. `debugging` for canvas debugging
  406. `app-run` for (published) app execution
  407. - version (string) Version
  408. - graph (text) Workflow canvas configuration (JSON)
  409. - inputs (text) Input parameters
  410. - status (string) Execution status, `running` / `succeeded` / `failed` / `stopped`
  411. - outputs (text) `optional` Output content
  412. - error (string) `optional` Error reason
  413. - elapsed_time (float) `optional` Time consumption (s)
  414. - total_tokens (int) `optional` Total tokens used
  415. - total_steps (int) Total steps (redundant), default 0
  416. - created_by_role (string) Creator role
  417. - `account` Console account
  418. - `end_user` End user
  419. - created_by (uuid) Runner ID
  420. - created_at (timestamp) Run time
  421. - finished_at (timestamp) End time
  422. """
  423. __tablename__ = "workflow_runs"
  424. __table_args__ = (
  425. sa.PrimaryKeyConstraint("id", name="workflow_run_pkey"),
  426. sa.Index("workflow_run_triggerd_from_idx", "tenant_id", "app_id", "triggered_from"),
  427. )
  428. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  429. tenant_id: Mapped[str] = mapped_column(StringUUID)
  430. app_id: Mapped[str] = mapped_column(StringUUID)
  431. workflow_id: Mapped[str] = mapped_column(StringUUID)
  432. type: Mapped[str] = mapped_column(String(255))
  433. triggered_from: Mapped[str] = mapped_column(String(255))
  434. version: Mapped[str] = mapped_column(String(255))
  435. graph: Mapped[str | None] = mapped_column(sa.Text)
  436. inputs: Mapped[str | None] = mapped_column(sa.Text)
  437. status: Mapped[str] = mapped_column(String(255)) # running, succeeded, failed, stopped, partial-succeeded
  438. outputs: Mapped[str | None] = mapped_column(sa.Text, default="{}")
  439. error: Mapped[str | None] = mapped_column(sa.Text)
  440. elapsed_time: Mapped[float] = mapped_column(sa.Float, nullable=False, server_default=sa.text("0"))
  441. total_tokens: Mapped[int] = mapped_column(sa.BigInteger, server_default=sa.text("0"))
  442. total_steps: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"), nullable=True)
  443. created_by_role: Mapped[str] = mapped_column(String(255)) # account, end_user
  444. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  445. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  446. finished_at: Mapped[datetime | None] = mapped_column(DateTime)
  447. exceptions_count: Mapped[int] = mapped_column(sa.Integer, server_default=sa.text("0"), nullable=True)
  448. @property
  449. def created_by_account(self):
  450. created_by_role = CreatorUserRole(self.created_by_role)
  451. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  452. @property
  453. def created_by_end_user(self):
  454. from models.model import EndUser
  455. created_by_role = CreatorUserRole(self.created_by_role)
  456. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  457. @property
  458. def graph_dict(self) -> Mapping[str, Any]:
  459. return json.loads(self.graph) if self.graph else {}
  460. @property
  461. def inputs_dict(self) -> Mapping[str, Any]:
  462. return json.loads(self.inputs) if self.inputs else {}
  463. @property
  464. def outputs_dict(self) -> Mapping[str, Any]:
  465. return json.loads(self.outputs) if self.outputs else {}
  466. @property
  467. def message(self):
  468. from models.model import Message
  469. return (
  470. db.session.query(Message).where(Message.app_id == self.app_id, Message.workflow_run_id == self.id).first()
  471. )
  472. @property
  473. def workflow(self):
  474. return db.session.query(Workflow).where(Workflow.id == self.workflow_id).first()
  475. def to_dict(self):
  476. return {
  477. "id": self.id,
  478. "tenant_id": self.tenant_id,
  479. "app_id": self.app_id,
  480. "workflow_id": self.workflow_id,
  481. "type": self.type,
  482. "triggered_from": self.triggered_from,
  483. "version": self.version,
  484. "graph": self.graph_dict,
  485. "inputs": self.inputs_dict,
  486. "status": self.status,
  487. "outputs": self.outputs_dict,
  488. "error": self.error,
  489. "elapsed_time": self.elapsed_time,
  490. "total_tokens": self.total_tokens,
  491. "total_steps": self.total_steps,
  492. "created_by_role": self.created_by_role,
  493. "created_by": self.created_by,
  494. "created_at": self.created_at,
  495. "finished_at": self.finished_at,
  496. "exceptions_count": self.exceptions_count,
  497. }
  498. @classmethod
  499. def from_dict(cls, data: dict[str, Any]) -> "WorkflowRun":
  500. return cls(
  501. id=data.get("id"),
  502. tenant_id=data.get("tenant_id"),
  503. app_id=data.get("app_id"),
  504. workflow_id=data.get("workflow_id"),
  505. type=data.get("type"),
  506. triggered_from=data.get("triggered_from"),
  507. version=data.get("version"),
  508. graph=json.dumps(data.get("graph")),
  509. inputs=json.dumps(data.get("inputs")),
  510. status=data.get("status"),
  511. outputs=json.dumps(data.get("outputs")),
  512. error=data.get("error"),
  513. elapsed_time=data.get("elapsed_time"),
  514. total_tokens=data.get("total_tokens"),
  515. total_steps=data.get("total_steps"),
  516. created_by_role=data.get("created_by_role"),
  517. created_by=data.get("created_by"),
  518. created_at=data.get("created_at"),
  519. finished_at=data.get("finished_at"),
  520. exceptions_count=data.get("exceptions_count"),
  521. )
  522. class WorkflowNodeExecutionTriggeredFrom(StrEnum):
  523. """
  524. Workflow Node Execution Triggered From Enum
  525. """
  526. SINGLE_STEP = "single-step"
  527. WORKFLOW_RUN = "workflow-run"
  528. RAG_PIPELINE_RUN = "rag-pipeline-run"
  529. class WorkflowNodeExecutionModel(Base): # This model is expected to have `offload_data` preloaded in most cases.
  530. """
  531. Workflow Node Execution
  532. - id (uuid) Execution ID
  533. - tenant_id (uuid) Workspace ID
  534. - app_id (uuid) App ID
  535. - workflow_id (uuid) Workflow ID
  536. - triggered_from (string) Trigger source
  537. `single-step` for single-step debugging
  538. `workflow-run` for workflow execution (debugging / user execution)
  539. - workflow_run_id (uuid) `optional` Workflow run ID
  540. Null for single-step debugging.
  541. - index (int) Execution sequence number, used for displaying Tracing Node order
  542. - predecessor_node_id (string) `optional` Predecessor node ID, used for displaying execution path
  543. - node_id (string) Node ID
  544. - node_type (string) Node type, such as `start`
  545. - title (string) Node title
  546. - inputs (json) All predecessor node variable content used in the node
  547. - process_data (json) Node process data
  548. - outputs (json) `optional` Node output variables
  549. - status (string) Execution status, `running` / `succeeded` / `failed`
  550. - error (string) `optional` Error reason
  551. - elapsed_time (float) `optional` Time consumption (s)
  552. - execution_metadata (text) Metadata
  553. - total_tokens (int) `optional` Total tokens used
  554. - total_price (decimal) `optional` Total cost
  555. - currency (string) `optional` Currency, such as USD / RMB
  556. - created_at (timestamp) Run time
  557. - created_by_role (string) Creator role
  558. - `account` Console account
  559. - `end_user` End user
  560. - created_by (uuid) Runner ID
  561. - finished_at (timestamp) End time
  562. """
  563. __tablename__ = "workflow_node_executions"
  564. @declared_attr
  565. @classmethod
  566. def __table_args__(cls) -> Any:
  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(),
  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[str | None] = mapped_column(StringUUID)
  612. index: Mapped[int] = mapped_column(sa.Integer)
  613. predecessor_node_id: Mapped[str | None] = mapped_column(String(255))
  614. node_execution_id: Mapped[str | None] = 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[str | None] = mapped_column(sa.Text)
  619. process_data: Mapped[str | None] = mapped_column(sa.Text)
  620. outputs: Mapped[str | None] = mapped_column(sa.Text)
  621. status: Mapped[str] = mapped_column(String(255))
  622. error: Mapped[str | None] = mapped_column(sa.Text)
  623. elapsed_time: Mapped[float] = mapped_column(sa.Float, server_default=sa.text("0"))
  624. execution_metadata: Mapped[str | None] = 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[datetime | None] = mapped_column(DateTime)
  629. offload_data: Mapped[list["WorkflowNodeExecutionOffload"]] = orm.relationship(
  630. "WorkflowNodeExecutionOffload",
  631. primaryjoin="WorkflowNodeExecutionModel.id == foreign(WorkflowNodeExecutionOffload.node_execution_id)",
  632. uselist=True,
  633. lazy="raise",
  634. back_populates="execution",
  635. )
  636. @staticmethod
  637. def preload_offload_data(
  638. query: Select[tuple["WorkflowNodeExecutionModel"]] | orm.Query["WorkflowNodeExecutionModel"],
  639. ):
  640. return query.options(orm.selectinload(WorkflowNodeExecutionModel.offload_data))
  641. @staticmethod
  642. def preload_offload_data_and_files(
  643. query: Select[tuple["WorkflowNodeExecutionModel"]] | orm.Query["WorkflowNodeExecutionModel"],
  644. ):
  645. return query.options(
  646. orm.selectinload(WorkflowNodeExecutionModel.offload_data).options(
  647. # Using `joinedload` instead of `selectinload` to minimize database roundtrips,
  648. # as `selectinload` would require separate queries for `inputs_file` and `outputs_file`.
  649. orm.selectinload(WorkflowNodeExecutionOffload.file),
  650. )
  651. )
  652. @property
  653. def created_by_account(self):
  654. created_by_role = CreatorUserRole(self.created_by_role)
  655. # TODO(-LAN-): Avoid using db.session.get() here.
  656. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  657. @property
  658. def created_by_end_user(self):
  659. from models.model import EndUser
  660. created_by_role = CreatorUserRole(self.created_by_role)
  661. # TODO(-LAN-): Avoid using db.session.get() here.
  662. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  663. @property
  664. def inputs_dict(self):
  665. return json.loads(self.inputs) if self.inputs else None
  666. @property
  667. def outputs_dict(self) -> dict[str, Any] | None:
  668. return json.loads(self.outputs) if self.outputs else None
  669. @property
  670. def process_data_dict(self):
  671. return json.loads(self.process_data) if self.process_data else None
  672. @property
  673. def execution_metadata_dict(self) -> dict[str, Any]:
  674. # When the metadata is unset, we return an empty dictionary instead of `None`.
  675. # This approach streamlines the logic for the caller, making it easier to handle
  676. # cases where metadata is absent.
  677. return json.loads(self.execution_metadata) if self.execution_metadata else {}
  678. @property
  679. def extras(self) -> dict[str, Any]:
  680. from core.tools.tool_manager import ToolManager
  681. extras: dict[str, Any] = {}
  682. if self.execution_metadata_dict:
  683. from core.workflow.nodes import NodeType
  684. if self.node_type == NodeType.TOOL.value and "tool_info" in self.execution_metadata_dict:
  685. tool_info: dict[str, Any] = self.execution_metadata_dict["tool_info"]
  686. extras["icon"] = ToolManager.get_tool_icon(
  687. tenant_id=self.tenant_id,
  688. provider_type=tool_info["provider_type"],
  689. provider_id=tool_info["provider_id"],
  690. )
  691. elif self.node_type == NodeType.DATASOURCE.value and "datasource_info" in self.execution_metadata_dict:
  692. datasource_info = self.execution_metadata_dict["datasource_info"]
  693. extras["icon"] = datasource_info.get("icon")
  694. return extras
  695. def _get_offload_by_type(self, type_: ExecutionOffLoadType) -> Optional["WorkflowNodeExecutionOffload"]:
  696. return next(iter([i for i in self.offload_data if i.type_ == type_]), None)
  697. @property
  698. def inputs_truncated(self) -> bool:
  699. """Check if inputs were truncated (offloaded to external storage)."""
  700. return self._get_offload_by_type(ExecutionOffLoadType.INPUTS) is not None
  701. @property
  702. def outputs_truncated(self) -> bool:
  703. """Check if outputs were truncated (offloaded to external storage)."""
  704. return self._get_offload_by_type(ExecutionOffLoadType.OUTPUTS) is not None
  705. @property
  706. def process_data_truncated(self) -> bool:
  707. """Check if process_data were truncated (offloaded to external storage)."""
  708. return self._get_offload_by_type(ExecutionOffLoadType.PROCESS_DATA) is not None
  709. @staticmethod
  710. def _load_full_content(session: orm.Session, file_id: str, storage: Storage):
  711. from .model import UploadFile
  712. stmt = sa.select(UploadFile).where(UploadFile.id == file_id)
  713. file = session.scalars(stmt).first()
  714. assert file is not None, f"UploadFile with id {file_id} should exist but not"
  715. content = storage.load(file.key)
  716. return json.loads(content)
  717. def load_full_inputs(self, session: orm.Session, storage: Storage) -> Mapping[str, Any] | None:
  718. offload = self._get_offload_by_type(ExecutionOffLoadType.INPUTS)
  719. if offload is None:
  720. return self.inputs_dict
  721. return self._load_full_content(session, offload.file_id, storage)
  722. def load_full_outputs(self, session: orm.Session, storage: Storage) -> Mapping[str, Any] | None:
  723. offload: WorkflowNodeExecutionOffload | None = self._get_offload_by_type(ExecutionOffLoadType.OUTPUTS)
  724. if offload is None:
  725. return self.outputs_dict
  726. return self._load_full_content(session, offload.file_id, storage)
  727. def load_full_process_data(self, session: orm.Session, storage: Storage) -> Mapping[str, Any] | None:
  728. offload: WorkflowNodeExecutionOffload | None = self._get_offload_by_type(ExecutionOffLoadType.PROCESS_DATA)
  729. if offload is None:
  730. return self.process_data_dict
  731. return self._load_full_content(session, offload.file_id, storage)
  732. class WorkflowNodeExecutionOffload(Base):
  733. __tablename__ = "workflow_node_execution_offload"
  734. __table_args__ = (
  735. # PostgreSQL 14 treats NULL values as distinct in unique constraints by default,
  736. # allowing multiple records with NULL values for the same column combination.
  737. #
  738. # This behavior allows us to have multiple records with NULL node_execution_id,
  739. # simplifying garbage collection process.
  740. UniqueConstraint(
  741. "node_execution_id",
  742. "type",
  743. # Note: PostgreSQL 15+ supports explicit `nulls distinct` behavior through
  744. # `postgresql_nulls_not_distinct=False`, which would make our intention clearer.
  745. # We rely on PostgreSQL's default behavior of treating NULLs as distinct values.
  746. # postgresql_nulls_not_distinct=False,
  747. ),
  748. )
  749. _HASH_COL_SIZE = 64
  750. id: Mapped[str] = mapped_column(
  751. StringUUID,
  752. primary_key=True,
  753. server_default=sa.text("uuidv7()"),
  754. )
  755. created_at: Mapped[datetime] = mapped_column(
  756. DateTime, default=naive_utc_now, server_default=func.current_timestamp()
  757. )
  758. tenant_id: Mapped[str] = mapped_column(StringUUID)
  759. app_id: Mapped[str] = mapped_column(StringUUID)
  760. # `node_execution_id` indicates the `WorkflowNodeExecutionModel` associated with this offload record.
  761. # A value of `None` signifies that this offload record is not linked to any execution record
  762. # and should be considered for garbage collection.
  763. node_execution_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
  764. type_: Mapped[ExecutionOffLoadType] = mapped_column(EnumText(ExecutionOffLoadType), name="type", nullable=False)
  765. # Design Decision: Combining inputs and outputs into a single object was considered to reduce I/O
  766. # operations. However, due to the current design of `WorkflowNodeExecutionRepository`,
  767. # the `save` method is called at two distinct times:
  768. #
  769. # - When the node starts execution: the `inputs` field exists, but the `outputs` field is absent
  770. # - When the node completes execution (either succeeded or failed): the `outputs` field becomes available
  771. #
  772. # It's difficult to correlate these two successive calls to `save` for combined storage.
  773. # Converting the `WorkflowNodeExecutionRepository` to buffer the first `save` call and flush
  774. # when execution completes was also considered, but this would make the execution state unobservable
  775. # until completion, significantly damaging the observability of workflow execution.
  776. #
  777. # Given these constraints, `inputs` and `outputs` are stored separately to maintain real-time
  778. # observability and system reliability.
  779. # `file_id` references to the offloaded storage object containing the data.
  780. file_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  781. execution: Mapped[WorkflowNodeExecutionModel] = orm.relationship(
  782. foreign_keys=[node_execution_id],
  783. lazy="raise",
  784. uselist=False,
  785. primaryjoin="WorkflowNodeExecutionOffload.node_execution_id == WorkflowNodeExecutionModel.id",
  786. back_populates="offload_data",
  787. )
  788. file: Mapped[Optional["UploadFile"]] = orm.relationship(
  789. foreign_keys=[file_id],
  790. lazy="raise",
  791. uselist=False,
  792. primaryjoin="WorkflowNodeExecutionOffload.file_id == UploadFile.id",
  793. )
  794. class WorkflowAppLogCreatedFrom(StrEnum):
  795. """
  796. Workflow App Log Created From Enum
  797. """
  798. SERVICE_API = "service-api"
  799. WEB_APP = "web-app"
  800. INSTALLED_APP = "installed-app"
  801. @classmethod
  802. def value_of(cls, value: str) -> "WorkflowAppLogCreatedFrom":
  803. """
  804. Get value of given mode.
  805. :param value: mode value
  806. :return: mode
  807. """
  808. for mode in cls:
  809. if mode.value == value:
  810. return mode
  811. raise ValueError(f"invalid workflow app log created from value {value}")
  812. class WorkflowAppLog(Base):
  813. """
  814. Workflow App execution log, excluding workflow debugging records.
  815. Attributes:
  816. - id (uuid) run ID
  817. - tenant_id (uuid) Workspace ID
  818. - app_id (uuid) App ID
  819. - workflow_id (uuid) Associated Workflow ID
  820. - workflow_run_id (uuid) Associated Workflow Run ID
  821. - created_from (string) Creation source
  822. `service-api` App Execution OpenAPI
  823. `web-app` WebApp
  824. `installed-app` Installed App
  825. - created_by_role (string) Creator role
  826. - `account` Console account
  827. - `end_user` End user
  828. - created_by (uuid) Creator ID, depends on the user table according to created_by_role
  829. - created_at (timestamp) Creation time
  830. """
  831. __tablename__ = "workflow_app_logs"
  832. __table_args__ = (
  833. sa.PrimaryKeyConstraint("id", name="workflow_app_log_pkey"),
  834. sa.Index("workflow_app_log_app_idx", "tenant_id", "app_id"),
  835. sa.Index("workflow_app_log_workflow_run_id_idx", "workflow_run_id"),
  836. )
  837. id: Mapped[str] = mapped_column(StringUUID, server_default=sa.text("uuid_generate_v4()"))
  838. tenant_id: Mapped[str] = mapped_column(StringUUID)
  839. app_id: Mapped[str] = mapped_column(StringUUID)
  840. workflow_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  841. workflow_run_id: Mapped[str] = mapped_column(StringUUID)
  842. created_from: Mapped[str] = mapped_column(String(255), nullable=False)
  843. created_by_role: Mapped[str] = mapped_column(String(255), nullable=False)
  844. created_by: Mapped[str] = mapped_column(StringUUID, nullable=False)
  845. created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.current_timestamp())
  846. @property
  847. def workflow_run(self):
  848. return db.session.get(WorkflowRun, self.workflow_run_id)
  849. @property
  850. def created_by_account(self):
  851. created_by_role = CreatorUserRole(self.created_by_role)
  852. return db.session.get(Account, self.created_by) if created_by_role == CreatorUserRole.ACCOUNT else None
  853. @property
  854. def created_by_end_user(self):
  855. from models.model import EndUser
  856. created_by_role = CreatorUserRole(self.created_by_role)
  857. return db.session.get(EndUser, self.created_by) if created_by_role == CreatorUserRole.END_USER else None
  858. def to_dict(self):
  859. return {
  860. "id": self.id,
  861. "tenant_id": self.tenant_id,
  862. "app_id": self.app_id,
  863. "workflow_id": self.workflow_id,
  864. "workflow_run_id": self.workflow_run_id,
  865. "created_from": self.created_from,
  866. "created_by_role": self.created_by_role,
  867. "created_by": self.created_by,
  868. "created_at": self.created_at,
  869. }
  870. class ConversationVariable(Base):
  871. __tablename__ = "workflow_conversation_variables"
  872. id: Mapped[str] = mapped_column(StringUUID, primary_key=True)
  873. conversation_id: Mapped[str] = mapped_column(StringUUID, nullable=False, primary_key=True, index=True)
  874. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False, index=True)
  875. data: Mapped[str] = mapped_column(sa.Text, nullable=False)
  876. created_at: Mapped[datetime] = mapped_column(
  877. DateTime, nullable=False, server_default=func.current_timestamp(), index=True
  878. )
  879. updated_at: Mapped[datetime] = mapped_column(
  880. DateTime, nullable=False, server_default=func.current_timestamp(), onupdate=func.current_timestamp()
  881. )
  882. def __init__(self, *, id: str, app_id: str, conversation_id: str, data: str):
  883. self.id = id
  884. self.app_id = app_id
  885. self.conversation_id = conversation_id
  886. self.data = data
  887. @classmethod
  888. def from_variable(cls, *, app_id: str, conversation_id: str, variable: Variable) -> "ConversationVariable":
  889. obj = cls(
  890. id=variable.id,
  891. app_id=app_id,
  892. conversation_id=conversation_id,
  893. data=variable.model_dump_json(),
  894. )
  895. return obj
  896. def to_variable(self) -> Variable:
  897. mapping = json.loads(self.data)
  898. return variable_factory.build_conversation_variable_from_mapping(mapping)
  899. # Only `sys.query` and `sys.files` could be modified.
  900. _EDITABLE_SYSTEM_VARIABLE = frozenset(["query", "files"])
  901. def _naive_utc_datetime():
  902. return naive_utc_now()
  903. class WorkflowDraftVariable(Base):
  904. """`WorkflowDraftVariable` record variables and outputs generated during
  905. debugging workflow or chatflow.
  906. IMPORTANT: This model maintains multiple invariant rules that must be preserved.
  907. Do not instantiate this class directly with the constructor.
  908. Instead, use the factory methods (`new_conversation_variable`, `new_sys_variable`,
  909. `new_node_variable`) defined below to ensure all invariants are properly maintained.
  910. """
  911. @staticmethod
  912. def unique_app_id_node_id_name() -> list[str]:
  913. return [
  914. "app_id",
  915. "node_id",
  916. "name",
  917. ]
  918. __tablename__ = "workflow_draft_variables"
  919. __table_args__ = (
  920. UniqueConstraint(*unique_app_id_node_id_name()),
  921. Index("workflow_draft_variable_file_id_idx", "file_id"),
  922. )
  923. # Required for instance variable annotation.
  924. __allow_unmapped__ = True
  925. # id is the unique identifier of a draft variable.
  926. id: Mapped[str] = mapped_column(StringUUID, primary_key=True, server_default=sa.text("uuid_generate_v4()"))
  927. created_at: Mapped[datetime] = mapped_column(
  928. DateTime,
  929. nullable=False,
  930. default=_naive_utc_datetime,
  931. server_default=func.current_timestamp(),
  932. )
  933. updated_at: Mapped[datetime] = mapped_column(
  934. DateTime,
  935. nullable=False,
  936. default=_naive_utc_datetime,
  937. server_default=func.current_timestamp(),
  938. onupdate=func.current_timestamp(),
  939. )
  940. # "`app_id` maps to the `id` field in the `model.App` model."
  941. app_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
  942. # `last_edited_at` records when the value of a given draft variable
  943. # is edited.
  944. #
  945. # If it's not edited after creation, its value is `None`.
  946. last_edited_at: Mapped[datetime | None] = mapped_column(
  947. DateTime,
  948. nullable=True,
  949. default=None,
  950. )
  951. # The `node_id` field is special.
  952. #
  953. # If the variable is a conversation variable or a system variable, then the value of `node_id`
  954. # is `conversation` or `sys`, respective.
  955. #
  956. # Otherwise, if the variable is a variable belonging to a specific node, the value of `_node_id` is
  957. # the identity of correspond node in graph definition. An example of node id is `"1745769620734"`.
  958. #
  959. # However, there's one caveat. The id of the first "Answer" node in chatflow is "answer". (Other
  960. # "Answer" node conform the rules above.)
  961. node_id: Mapped[str] = mapped_column(sa.String(255), nullable=False, name="node_id")
  962. # From `VARIABLE_PATTERN`, we may conclude that the length of a top level variable is less than
  963. # 80 chars.
  964. #
  965. # ref: api/core/workflow/entities/variable_pool.py:18
  966. name: Mapped[str] = mapped_column(sa.String(255), nullable=False)
  967. description: Mapped[str] = mapped_column(
  968. sa.String(255),
  969. default="",
  970. nullable=False,
  971. )
  972. selector: Mapped[str] = mapped_column(sa.String(255), nullable=False, name="selector")
  973. # The data type of this variable's value
  974. #
  975. # If the variable is offloaded, `value_type` represents the type of the truncated value,
  976. # which may differ from the original value's type. Typically, they are the same,
  977. # but in cases where the structurally truncated value still exceeds the size limit,
  978. # text slicing is applied, and the `value_type` is converted to `STRING`.
  979. value_type: Mapped[SegmentType] = mapped_column(EnumText(SegmentType, length=20))
  980. # The variable's value serialized as a JSON string
  981. #
  982. # If the variable is offloaded, `value` contains a truncated version, not the full original value.
  983. value: Mapped[str] = mapped_column(sa.Text, nullable=False, name="value")
  984. # Controls whether the variable should be displayed in the variable inspection panel
  985. visible: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=True)
  986. # Determines whether this variable can be modified by users
  987. editable: Mapped[bool] = mapped_column(sa.Boolean, nullable=False, default=False)
  988. # The `node_execution_id` field identifies the workflow node execution that created this variable.
  989. # It corresponds to the `id` field in the `WorkflowNodeExecutionModel` model.
  990. #
  991. # This field is not `None` for system variables and node variables, and is `None`
  992. # for conversation variables.
  993. node_execution_id: Mapped[str | None] = mapped_column(
  994. StringUUID,
  995. nullable=True,
  996. default=None,
  997. )
  998. # Reference to WorkflowDraftVariableFile for offloaded large variables
  999. #
  1000. # Indicates whether the current draft variable is offloaded.
  1001. # If not offloaded, this field will be None.
  1002. file_id: Mapped[str | None] = mapped_column(
  1003. StringUUID,
  1004. nullable=True,
  1005. default=None,
  1006. comment="Reference to WorkflowDraftVariableFile if variable is offloaded to external storage",
  1007. )
  1008. is_default_value: Mapped[bool] = mapped_column(
  1009. sa.Boolean,
  1010. nullable=False,
  1011. default=False,
  1012. comment=(
  1013. "Indicates whether the current value is the default for a conversation variable. "
  1014. "Always `FALSE` for other types of variables."
  1015. ),
  1016. )
  1017. # Relationship to WorkflowDraftVariableFile
  1018. variable_file: Mapped[Optional["WorkflowDraftVariableFile"]] = orm.relationship(
  1019. foreign_keys=[file_id],
  1020. lazy="raise",
  1021. uselist=False,
  1022. primaryjoin="WorkflowDraftVariableFile.id == WorkflowDraftVariable.file_id",
  1023. )
  1024. # Cache for deserialized value
  1025. #
  1026. # NOTE(QuantumGhost): This field serves two purposes:
  1027. #
  1028. # 1. Caches deserialized values to reduce repeated parsing costs
  1029. # 2. Allows modification of the deserialized value after retrieval,
  1030. # particularly important for `File`` variables which require database
  1031. # lookups to obtain storage_key and other metadata
  1032. #
  1033. # Use double underscore prefix for better encapsulation,
  1034. # making this attribute harder to access from outside the class.
  1035. __value: Segment | None
  1036. def __init__(self, *args: Any, **kwargs: Any) -> None:
  1037. """
  1038. The constructor of `WorkflowDraftVariable` is not intended for
  1039. direct use outside this file. Its solo purpose is setup private state
  1040. used by the model instance.
  1041. Please use the factory methods
  1042. (`new_conversation_variable`, `new_sys_variable`, `new_node_variable`)
  1043. defined below to create instances of this class.
  1044. """
  1045. super().__init__(*args, **kwargs)
  1046. self.__value = None
  1047. @orm.reconstructor
  1048. def _init_on_load(self):
  1049. self.__value = None
  1050. def get_selector(self) -> list[str]:
  1051. selector: Any = json.loads(self.selector)
  1052. if not isinstance(selector, list):
  1053. logger.error(
  1054. "invalid selector loaded from database, type=%s, value=%s",
  1055. type(selector).__name__,
  1056. self.selector,
  1057. )
  1058. raise ValueError("invalid selector.")
  1059. return cast(list[str], selector)
  1060. def _set_selector(self, value: list[str]):
  1061. self.selector = json.dumps(value)
  1062. def _loads_value(self) -> Segment:
  1063. value = json.loads(self.value)
  1064. return self.build_segment_with_type(self.value_type, value)
  1065. @staticmethod
  1066. def rebuild_file_types(value: Any):
  1067. # NOTE(QuantumGhost): Temporary workaround for structured data handling.
  1068. # By this point, `output` has been converted to dict by
  1069. # `WorkflowEntry.handle_special_values`, so we need to
  1070. # reconstruct File objects from their serialized form
  1071. # to maintain proper variable saving behavior.
  1072. #
  1073. # Ideally, we should work with structured data objects directly
  1074. # rather than their serialized forms.
  1075. # However, multiple components in the codebase depend on
  1076. # `WorkflowEntry.handle_special_values`, making a comprehensive migration challenging.
  1077. if isinstance(value, dict):
  1078. if not maybe_file_object(value):
  1079. return cast(Any, value)
  1080. return File.model_validate(value)
  1081. elif isinstance(value, list) and value:
  1082. value_list = cast(list[Any], value)
  1083. first: Any = value_list[0]
  1084. if not maybe_file_object(first):
  1085. return cast(Any, value)
  1086. file_list: list[File] = [File.model_validate(cast(dict[str, Any], i)) for i in value_list]
  1087. return cast(Any, file_list)
  1088. else:
  1089. return cast(Any, value)
  1090. @classmethod
  1091. def build_segment_with_type(cls, segment_type: SegmentType, value: Any) -> Segment:
  1092. # Extends `variable_factory.build_segment_with_type` functionality by
  1093. # reconstructing `FileSegment`` or `ArrayFileSegment`` objects from
  1094. # their serialized dictionary or list representations, respectively.
  1095. if segment_type == SegmentType.FILE:
  1096. if isinstance(value, File):
  1097. return build_segment_with_type(segment_type, value)
  1098. elif isinstance(value, dict):
  1099. file = cls.rebuild_file_types(value)
  1100. return build_segment_with_type(segment_type, file)
  1101. else:
  1102. raise TypeMismatchError(f"expected dict or File for FileSegment, got {type(value)}")
  1103. if segment_type == SegmentType.ARRAY_FILE:
  1104. if not isinstance(value, list):
  1105. raise TypeMismatchError(f"expected list for ArrayFileSegment, got {type(value)}")
  1106. file_list = cls.rebuild_file_types(value)
  1107. return build_segment_with_type(segment_type=segment_type, value=file_list)
  1108. return build_segment_with_type(segment_type=segment_type, value=value)
  1109. def get_value(self) -> Segment:
  1110. """Decode the serialized value into its corresponding `Segment` object.
  1111. This method caches the result, so repeated calls will return the same
  1112. object instance without re-parsing the serialized data.
  1113. If you need to modify the returned `Segment`, use `value.model_copy()`
  1114. to create a copy first to avoid affecting the cached instance.
  1115. For more information about the caching mechanism, see the documentation
  1116. of the `__value` field.
  1117. Returns:
  1118. Segment: The deserialized value as a Segment object.
  1119. """
  1120. if self.__value is not None:
  1121. return self.__value
  1122. value = self._loads_value()
  1123. self.__value = value
  1124. return value
  1125. def set_name(self, name: str):
  1126. self.name = name
  1127. self._set_selector([self.node_id, name])
  1128. def set_value(self, value: Segment):
  1129. """Updates the `value` and corresponding `value_type` fields in the database model.
  1130. This method also stores the provided Segment object in the deserialized cache
  1131. without creating a copy, allowing for efficient value access.
  1132. Args:
  1133. value: The Segment object to store as the variable's value.
  1134. """
  1135. self.__value = value
  1136. self.value = variable_utils.dumps_with_segments(value)
  1137. self.value_type = value.value_type
  1138. def get_node_id(self) -> str | None:
  1139. if self.get_variable_type() == DraftVariableType.NODE:
  1140. return self.node_id
  1141. else:
  1142. return None
  1143. def get_variable_type(self) -> DraftVariableType:
  1144. match self.node_id:
  1145. case DraftVariableType.CONVERSATION:
  1146. return DraftVariableType.CONVERSATION
  1147. case DraftVariableType.SYS:
  1148. return DraftVariableType.SYS
  1149. case _:
  1150. return DraftVariableType.NODE
  1151. def is_truncated(self) -> bool:
  1152. return self.file_id is not None
  1153. @classmethod
  1154. def _new(
  1155. cls,
  1156. *,
  1157. app_id: str,
  1158. node_id: str,
  1159. name: str,
  1160. value: Segment,
  1161. node_execution_id: str | None,
  1162. description: str = "",
  1163. file_id: str | None = None,
  1164. ) -> "WorkflowDraftVariable":
  1165. variable = WorkflowDraftVariable()
  1166. variable.created_at = _naive_utc_datetime()
  1167. variable.updated_at = _naive_utc_datetime()
  1168. variable.description = description
  1169. variable.app_id = app_id
  1170. variable.node_id = node_id
  1171. variable.name = name
  1172. variable.set_value(value)
  1173. variable.file_id = file_id
  1174. variable._set_selector(list(variable_utils.to_selector(node_id, name)))
  1175. variable.node_execution_id = node_execution_id
  1176. return variable
  1177. @classmethod
  1178. def new_conversation_variable(
  1179. cls,
  1180. *,
  1181. app_id: str,
  1182. name: str,
  1183. value: Segment,
  1184. description: str = "",
  1185. ) -> "WorkflowDraftVariable":
  1186. variable = cls._new(
  1187. app_id=app_id,
  1188. node_id=CONVERSATION_VARIABLE_NODE_ID,
  1189. name=name,
  1190. value=value,
  1191. description=description,
  1192. node_execution_id=None,
  1193. )
  1194. variable.editable = True
  1195. return variable
  1196. @classmethod
  1197. def new_sys_variable(
  1198. cls,
  1199. *,
  1200. app_id: str,
  1201. name: str,
  1202. value: Segment,
  1203. node_execution_id: str,
  1204. editable: bool = False,
  1205. ) -> "WorkflowDraftVariable":
  1206. variable = cls._new(
  1207. app_id=app_id,
  1208. node_id=SYSTEM_VARIABLE_NODE_ID,
  1209. name=name,
  1210. node_execution_id=node_execution_id,
  1211. value=value,
  1212. )
  1213. variable.editable = editable
  1214. return variable
  1215. @classmethod
  1216. def new_node_variable(
  1217. cls,
  1218. *,
  1219. app_id: str,
  1220. node_id: str,
  1221. name: str,
  1222. value: Segment,
  1223. node_execution_id: str,
  1224. visible: bool = True,
  1225. editable: bool = True,
  1226. file_id: str | None = None,
  1227. ) -> "WorkflowDraftVariable":
  1228. variable = cls._new(
  1229. app_id=app_id,
  1230. node_id=node_id,
  1231. name=name,
  1232. node_execution_id=node_execution_id,
  1233. value=value,
  1234. file_id=file_id,
  1235. )
  1236. variable.visible = visible
  1237. variable.editable = editable
  1238. return variable
  1239. @property
  1240. def edited(self):
  1241. return self.last_edited_at is not None
  1242. class WorkflowDraftVariableFile(Base):
  1243. """Stores metadata about files associated with large workflow draft variables.
  1244. This model acts as an intermediary between WorkflowDraftVariable and UploadFile,
  1245. allowing for proper cleanup of orphaned files when variables are updated or deleted.
  1246. The MIME type of the stored content is recorded in `UploadFile.mime_type`.
  1247. Possible values are 'application/json' for JSON types other than plain text,
  1248. and 'text/plain' for JSON strings.
  1249. """
  1250. __tablename__ = "workflow_draft_variable_files"
  1251. # Primary key
  1252. id: Mapped[str] = mapped_column(
  1253. StringUUID,
  1254. primary_key=True,
  1255. default=uuidv7,
  1256. server_default=sa.text("uuidv7()"),
  1257. )
  1258. created_at: Mapped[datetime] = mapped_column(
  1259. DateTime,
  1260. nullable=False,
  1261. default=_naive_utc_datetime,
  1262. server_default=func.current_timestamp(),
  1263. )
  1264. tenant_id: Mapped[str] = mapped_column(
  1265. StringUUID,
  1266. nullable=False,
  1267. comment="The tenant to which the WorkflowDraftVariableFile belongs, referencing Tenant.id",
  1268. )
  1269. app_id: Mapped[str] = mapped_column(
  1270. StringUUID,
  1271. nullable=False,
  1272. comment="The application to which the WorkflowDraftVariableFile belongs, referencing App.id",
  1273. )
  1274. user_id: Mapped[str] = mapped_column(
  1275. StringUUID,
  1276. nullable=False,
  1277. comment="The owner to of the WorkflowDraftVariableFile, referencing Account.id",
  1278. )
  1279. # Reference to the `UploadFile.id` field
  1280. upload_file_id: Mapped[str] = mapped_column(
  1281. StringUUID,
  1282. nullable=False,
  1283. comment="Reference to UploadFile containing the large variable data",
  1284. )
  1285. # -------------- metadata about the variable content --------------
  1286. # The `size` is already recorded in UploadFiles. It is duplicated here to avoid an additional database lookup.
  1287. size: Mapped[int | None] = mapped_column(
  1288. sa.BigInteger,
  1289. nullable=False,
  1290. comment="Size of the original variable content in bytes",
  1291. )
  1292. length: Mapped[int | None] = mapped_column(
  1293. sa.Integer,
  1294. nullable=True,
  1295. comment=(
  1296. "Length of the original variable content. For array and array-like types, "
  1297. "this represents the number of elements. For object types, it indicates the number of keys. "
  1298. "For other types, the value is NULL."
  1299. ),
  1300. )
  1301. # The `value_type` field records the type of the original value.
  1302. value_type: Mapped[SegmentType] = mapped_column(
  1303. EnumText(SegmentType, length=20),
  1304. nullable=False,
  1305. )
  1306. # Relationship to UploadFile
  1307. upload_file: Mapped["UploadFile"] = orm.relationship(
  1308. foreign_keys=[upload_file_id],
  1309. lazy="raise",
  1310. uselist=False,
  1311. primaryjoin="WorkflowDraftVariableFile.upload_file_id == UploadFile.id",
  1312. )
  1313. def is_system_variable_editable(name: str) -> bool:
  1314. return name in _EDITABLE_SYSTEM_VARIABLE