Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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