您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

workflow_draft_variable_service.py 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. import dataclasses
  2. import datetime
  3. import logging
  4. from collections.abc import Mapping, Sequence
  5. from enum import StrEnum
  6. from typing import Any, ClassVar
  7. from sqlalchemy import Engine, orm, select
  8. from sqlalchemy.dialects.postgresql import insert
  9. from sqlalchemy.orm import Session
  10. from sqlalchemy.sql.expression import and_, or_
  11. from core.app.entities.app_invoke_entities import InvokeFrom
  12. from core.file.models import File
  13. from core.variables import Segment, StringSegment, Variable
  14. from core.variables.consts import MIN_SELECTORS_LENGTH
  15. from core.variables.segments import ArrayFileSegment, FileSegment
  16. from core.variables.types import SegmentType
  17. from core.workflow.constants import CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID, SYSTEM_VARIABLE_NODE_ID
  18. from core.workflow.enums import SystemVariableKey
  19. from core.workflow.nodes import NodeType
  20. from core.workflow.nodes.variable_assigner.common.helpers import get_updated_variables
  21. from core.workflow.variable_loader import VariableLoader
  22. from factories.file_factory import StorageKeyLoader
  23. from factories.variable_factory import build_segment, segment_to_variable
  24. from models import App, Conversation
  25. from models.enums import DraftVariableType
  26. from models.workflow import Workflow, WorkflowDraftVariable, WorkflowNodeExecutionModel, is_system_variable_editable
  27. _logger = logging.getLogger(__name__)
  28. @dataclasses.dataclass(frozen=True)
  29. class WorkflowDraftVariableList:
  30. variables: list[WorkflowDraftVariable]
  31. total: int | None = None
  32. class WorkflowDraftVariableError(Exception):
  33. pass
  34. class VariableResetError(WorkflowDraftVariableError):
  35. pass
  36. class UpdateNotSupportedError(WorkflowDraftVariableError):
  37. pass
  38. class DraftVarLoader(VariableLoader):
  39. # This implements the VariableLoader interface for loading draft variables.
  40. #
  41. # ref: core.workflow.variable_loader.VariableLoader
  42. # Database engine used for loading variables.
  43. _engine: Engine
  44. # Application ID for which variables are being loaded.
  45. _app_id: str
  46. _tenant_id: str
  47. _fallback_variables: Sequence[Variable]
  48. def __init__(
  49. self,
  50. engine: Engine,
  51. app_id: str,
  52. tenant_id: str,
  53. fallback_variables: Sequence[Variable] | None = None,
  54. ) -> None:
  55. self._engine = engine
  56. self._app_id = app_id
  57. self._tenant_id = tenant_id
  58. self._fallback_variables = fallback_variables or []
  59. def _selector_to_tuple(self, selector: Sequence[str]) -> tuple[str, str]:
  60. return (selector[0], selector[1])
  61. def load_variables(self, selectors: list[list[str]]) -> list[Variable]:
  62. if not selectors:
  63. return []
  64. # Map each selector (as a tuple via `_selector_to_tuple`) to its corresponding Variable instance.
  65. variable_by_selector: dict[tuple[str, str], Variable] = {}
  66. with Session(bind=self._engine, expire_on_commit=False) as session:
  67. srv = WorkflowDraftVariableService(session)
  68. draft_vars = srv.get_draft_variables_by_selectors(self._app_id, selectors)
  69. for draft_var in draft_vars:
  70. segment = draft_var.get_value()
  71. variable = segment_to_variable(
  72. segment=segment,
  73. selector=draft_var.get_selector(),
  74. id=draft_var.id,
  75. name=draft_var.name,
  76. description=draft_var.description,
  77. )
  78. selector_tuple = self._selector_to_tuple(variable.selector)
  79. variable_by_selector[selector_tuple] = variable
  80. # Important:
  81. files: list[File] = []
  82. for draft_var in draft_vars:
  83. value = draft_var.get_value()
  84. if isinstance(value, FileSegment):
  85. files.append(value.value)
  86. elif isinstance(value, ArrayFileSegment):
  87. files.extend(value.value)
  88. with Session(bind=self._engine) as session:
  89. storage_key_loader = StorageKeyLoader(session, tenant_id=self._tenant_id)
  90. storage_key_loader.load_storage_keys(files)
  91. return list(variable_by_selector.values())
  92. class WorkflowDraftVariableService:
  93. _session: Session
  94. def __init__(self, session: Session) -> None:
  95. self._session = session
  96. def get_variable(self, variable_id: str) -> WorkflowDraftVariable | None:
  97. return self._session.query(WorkflowDraftVariable).filter(WorkflowDraftVariable.id == variable_id).first()
  98. def get_draft_variables_by_selectors(
  99. self,
  100. app_id: str,
  101. selectors: Sequence[list[str]],
  102. ) -> list[WorkflowDraftVariable]:
  103. ors = []
  104. for selector in selectors:
  105. node_id, name = selector
  106. ors.append(and_(WorkflowDraftVariable.node_id == node_id, WorkflowDraftVariable.name == name))
  107. # NOTE(QuantumGhost): Although the number of `or` expressions may be large, as long as
  108. # each expression includes conditions on both `node_id` and `name` (which are covered by the unique index),
  109. # PostgreSQL can efficiently retrieve the results using a bitmap index scan.
  110. #
  111. # Alternatively, a `SELECT` statement could be constructed for each selector and
  112. # combined using `UNION` to fetch all rows.
  113. # Benchmarking indicates that both approaches yield comparable performance.
  114. variables = (
  115. self._session.query(WorkflowDraftVariable).where(WorkflowDraftVariable.app_id == app_id, or_(*ors)).all()
  116. )
  117. return variables
  118. def list_variables_without_values(self, app_id: str, page: int, limit: int) -> WorkflowDraftVariableList:
  119. criteria = WorkflowDraftVariable.app_id == app_id
  120. total = None
  121. query = self._session.query(WorkflowDraftVariable).filter(criteria)
  122. if page == 1:
  123. total = query.count()
  124. variables = (
  125. # Do not load the `value` field.
  126. query.options(orm.defer(WorkflowDraftVariable.value))
  127. .order_by(WorkflowDraftVariable.id.desc())
  128. .limit(limit)
  129. .offset((page - 1) * limit)
  130. .all()
  131. )
  132. return WorkflowDraftVariableList(variables=variables, total=total)
  133. def _list_node_variables(self, app_id: str, node_id: str) -> WorkflowDraftVariableList:
  134. criteria = (
  135. WorkflowDraftVariable.app_id == app_id,
  136. WorkflowDraftVariable.node_id == node_id,
  137. )
  138. query = self._session.query(WorkflowDraftVariable).filter(*criteria)
  139. variables = query.order_by(WorkflowDraftVariable.id.desc()).all()
  140. return WorkflowDraftVariableList(variables=variables)
  141. def list_node_variables(self, app_id: str, node_id: str) -> WorkflowDraftVariableList:
  142. return self._list_node_variables(app_id, node_id)
  143. def list_conversation_variables(self, app_id: str) -> WorkflowDraftVariableList:
  144. return self._list_node_variables(app_id, CONVERSATION_VARIABLE_NODE_ID)
  145. def list_system_variables(self, app_id: str) -> WorkflowDraftVariableList:
  146. return self._list_node_variables(app_id, SYSTEM_VARIABLE_NODE_ID)
  147. def get_conversation_variable(self, app_id: str, name: str) -> WorkflowDraftVariable | None:
  148. return self._get_variable(app_id=app_id, node_id=CONVERSATION_VARIABLE_NODE_ID, name=name)
  149. def get_system_variable(self, app_id: str, name: str) -> WorkflowDraftVariable | None:
  150. return self._get_variable(app_id=app_id, node_id=SYSTEM_VARIABLE_NODE_ID, name=name)
  151. def get_node_variable(self, app_id: str, node_id: str, name: str) -> WorkflowDraftVariable | None:
  152. return self._get_variable(app_id, node_id, name)
  153. def _get_variable(self, app_id: str, node_id: str, name: str) -> WorkflowDraftVariable | None:
  154. variable = (
  155. self._session.query(WorkflowDraftVariable)
  156. .where(
  157. WorkflowDraftVariable.app_id == app_id,
  158. WorkflowDraftVariable.node_id == node_id,
  159. WorkflowDraftVariable.name == name,
  160. )
  161. .first()
  162. )
  163. return variable
  164. def update_variable(
  165. self,
  166. variable: WorkflowDraftVariable,
  167. name: str | None = None,
  168. value: Segment | None = None,
  169. ) -> WorkflowDraftVariable:
  170. if not variable.editable:
  171. raise UpdateNotSupportedError(f"variable not support updating, id={variable.id}")
  172. if name is not None:
  173. variable.set_name(name)
  174. if value is not None:
  175. variable.set_value(value)
  176. variable.last_edited_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  177. self._session.flush()
  178. return variable
  179. def _reset_conv_var(self, workflow: Workflow, variable: WorkflowDraftVariable) -> WorkflowDraftVariable | None:
  180. conv_var_by_name = {i.name: i for i in workflow.conversation_variables}
  181. conv_var = conv_var_by_name.get(variable.name)
  182. if conv_var is None:
  183. self._session.delete(instance=variable)
  184. self._session.flush()
  185. _logger.warning(
  186. "Conversation variable not found for draft variable, id=%s, name=%s", variable.id, variable.name
  187. )
  188. return None
  189. variable.set_value(conv_var)
  190. variable.last_edited_at = None
  191. self._session.add(variable)
  192. self._session.flush()
  193. return variable
  194. def _reset_node_var(self, workflow: Workflow, variable: WorkflowDraftVariable) -> WorkflowDraftVariable | None:
  195. # If a variable does not allow updating, it makes no sence to resetting it.
  196. if not variable.editable:
  197. return variable
  198. # No execution record for this variable, delete the variable instead.
  199. if variable.node_execution_id is None:
  200. self._session.delete(instance=variable)
  201. self._session.flush()
  202. _logger.warning("draft variable has no node_execution_id, id=%s, name=%s", variable.id, variable.name)
  203. return None
  204. query = select(WorkflowNodeExecutionModel).where(WorkflowNodeExecutionModel.id == variable.node_execution_id)
  205. node_exec = self._session.scalars(query).first()
  206. if node_exec is None:
  207. _logger.warning(
  208. "Node exectution not found for draft variable, id=%s, name=%s, node_execution_id=%s",
  209. variable.id,
  210. variable.name,
  211. variable.node_execution_id,
  212. )
  213. self._session.delete(instance=variable)
  214. self._session.flush()
  215. return None
  216. # Get node type for proper value extraction
  217. node_config = workflow.get_node_config_by_id(variable.node_id)
  218. node_type = workflow.get_node_type_from_node_config(node_config)
  219. outputs_dict = node_exec.outputs_dict or {}
  220. # Note: Based on the implementation in `_build_from_variable_assigner_mapping`,
  221. # VariableAssignerNode (both v1 and v2) can only create conversation draft variables.
  222. # For consistency, we should simply return when processing VARIABLE_ASSIGNER nodes.
  223. #
  224. # This implementation must remain synchronized with the `_build_from_variable_assigner_mapping`
  225. # and `save` methods.
  226. if node_type == NodeType.VARIABLE_ASSIGNER:
  227. return variable
  228. if variable.name not in outputs_dict:
  229. # If variable not found in execution data, delete the variable
  230. self._session.delete(instance=variable)
  231. self._session.flush()
  232. return None
  233. value = outputs_dict[variable.name]
  234. value_seg = WorkflowDraftVariable.build_segment_with_type(variable.value_type, value)
  235. # Extract variable value using unified logic
  236. variable.set_value(value_seg)
  237. variable.last_edited_at = None # Reset to indicate this is a reset operation
  238. self._session.flush()
  239. return variable
  240. def reset_variable(self, workflow: Workflow, variable: WorkflowDraftVariable) -> WorkflowDraftVariable | None:
  241. variable_type = variable.get_variable_type()
  242. if variable_type == DraftVariableType.CONVERSATION:
  243. return self._reset_conv_var(workflow, variable)
  244. elif variable_type == DraftVariableType.NODE:
  245. return self._reset_node_var(workflow, variable)
  246. else:
  247. raise VariableResetError(f"cannot reset system variable, variable_id={variable.id}")
  248. def delete_variable(self, variable: WorkflowDraftVariable):
  249. self._session.delete(variable)
  250. def delete_workflow_variables(self, app_id: str):
  251. (
  252. self._session.query(WorkflowDraftVariable)
  253. .filter(WorkflowDraftVariable.app_id == app_id)
  254. .delete(synchronize_session=False)
  255. )
  256. def delete_node_variables(self, app_id: str, node_id: str):
  257. return self._delete_node_variables(app_id, node_id)
  258. def _delete_node_variables(self, app_id: str, node_id: str):
  259. self._session.query(WorkflowDraftVariable).where(
  260. WorkflowDraftVariable.app_id == app_id,
  261. WorkflowDraftVariable.node_id == node_id,
  262. ).delete()
  263. def _get_conversation_id_from_draft_variable(self, app_id: str) -> str | None:
  264. draft_var = self._get_variable(
  265. app_id=app_id,
  266. node_id=SYSTEM_VARIABLE_NODE_ID,
  267. name=str(SystemVariableKey.CONVERSATION_ID),
  268. )
  269. if draft_var is None:
  270. return None
  271. segment = draft_var.get_value()
  272. if not isinstance(segment, StringSegment):
  273. _logger.warning(
  274. "sys.conversation_id variable is not a string: app_id=%s, id=%s",
  275. app_id,
  276. draft_var.id,
  277. )
  278. return None
  279. return segment.value
  280. def get_or_create_conversation(
  281. self,
  282. account_id: str,
  283. app: App,
  284. workflow: Workflow,
  285. ) -> str:
  286. """
  287. get_or_create_conversation creates and returns the ID of a conversation for debugging.
  288. If a conversation already exists, as determined by the following criteria, its ID is returned:
  289. - The system variable `sys.conversation_id` exists in the draft variable table, and
  290. - A corresponding conversation record is found in the database.
  291. If no such conversation exists, a new conversation is created and its ID is returned.
  292. """
  293. conv_id = self._get_conversation_id_from_draft_variable(workflow.app_id)
  294. if conv_id is not None:
  295. conversation = (
  296. self._session.query(Conversation)
  297. .filter(
  298. Conversation.id == conv_id,
  299. Conversation.app_id == workflow.app_id,
  300. )
  301. .first()
  302. )
  303. # Only return the conversation ID if it exists and is valid (has a correspond conversation record in DB).
  304. if conversation is not None:
  305. return conv_id
  306. conversation = Conversation(
  307. app_id=workflow.app_id,
  308. app_model_config_id=app.app_model_config_id,
  309. model_provider=None,
  310. model_id="",
  311. override_model_configs=None,
  312. mode=app.mode,
  313. name="Draft Debugging Conversation",
  314. inputs={},
  315. introduction="",
  316. system_instruction="",
  317. system_instruction_tokens=0,
  318. status="normal",
  319. invoke_from=InvokeFrom.DEBUGGER.value,
  320. from_source="console",
  321. from_end_user_id=None,
  322. from_account_id=account_id,
  323. )
  324. self._session.add(conversation)
  325. self._session.flush()
  326. return conversation.id
  327. def prefill_conversation_variable_default_values(self, workflow: Workflow):
  328. """"""
  329. draft_conv_vars: list[WorkflowDraftVariable] = []
  330. for conv_var in workflow.conversation_variables:
  331. draft_var = WorkflowDraftVariable.new_conversation_variable(
  332. app_id=workflow.app_id,
  333. name=conv_var.name,
  334. value=conv_var,
  335. description=conv_var.description,
  336. )
  337. draft_conv_vars.append(draft_var)
  338. _batch_upsert_draft_varaible(
  339. self._session,
  340. draft_conv_vars,
  341. policy=_UpsertPolicy.IGNORE,
  342. )
  343. class _UpsertPolicy(StrEnum):
  344. IGNORE = "ignore"
  345. OVERWRITE = "overwrite"
  346. def _batch_upsert_draft_varaible(
  347. session: Session,
  348. draft_vars: Sequence[WorkflowDraftVariable],
  349. policy: _UpsertPolicy = _UpsertPolicy.OVERWRITE,
  350. ) -> None:
  351. if not draft_vars:
  352. return None
  353. # Although we could use SQLAlchemy ORM operations here, we choose not to for several reasons:
  354. #
  355. # 1. The variable saving process involves writing multiple rows to the
  356. # `workflow_draft_variables` table. Batch insertion significantly improves performance.
  357. # 2. Using the ORM would require either:
  358. #
  359. # a. Checking for the existence of each variable before insertion,
  360. # resulting in 2n SQL statements for n variables and potential concurrency issues.
  361. # b. Attempting insertion first, then updating if a unique index violation occurs,
  362. # which still results in n to 2n SQL statements.
  363. #
  364. # Both approaches are inefficient and suboptimal.
  365. # 3. We do not need to retrieve the results of the SQL execution or populate ORM
  366. # model instances with the returned values.
  367. # 4. Batch insertion with `ON CONFLICT DO UPDATE` allows us to insert or update all
  368. # variables in a single SQL statement, avoiding the issues above.
  369. #
  370. # For these reasons, we use the SQLAlchemy query builder and rely on dialect-specific
  371. # insert operations instead of the ORM layer.
  372. stmt = insert(WorkflowDraftVariable).values([_model_to_insertion_dict(v) for v in draft_vars])
  373. if policy == _UpsertPolicy.OVERWRITE:
  374. stmt = stmt.on_conflict_do_update(
  375. index_elements=WorkflowDraftVariable.unique_app_id_node_id_name(),
  376. set_={
  377. "updated_at": stmt.excluded.updated_at,
  378. "last_edited_at": stmt.excluded.last_edited_at,
  379. "description": stmt.excluded.description,
  380. "value_type": stmt.excluded.value_type,
  381. "value": stmt.excluded.value,
  382. "visible": stmt.excluded.visible,
  383. "editable": stmt.excluded.editable,
  384. "node_execution_id": stmt.excluded.node_execution_id,
  385. },
  386. )
  387. elif _UpsertPolicy.IGNORE:
  388. stmt = stmt.on_conflict_do_nothing(index_elements=WorkflowDraftVariable.unique_app_id_node_id_name())
  389. else:
  390. raise Exception("Invalid value for update policy.")
  391. session.execute(stmt)
  392. def _model_to_insertion_dict(model: WorkflowDraftVariable) -> dict[str, Any]:
  393. d: dict[str, Any] = {
  394. "app_id": model.app_id,
  395. "last_edited_at": None,
  396. "node_id": model.node_id,
  397. "name": model.name,
  398. "selector": model.selector,
  399. "value_type": model.value_type,
  400. "value": model.value,
  401. "node_execution_id": model.node_execution_id,
  402. }
  403. if model.visible is not None:
  404. d["visible"] = model.visible
  405. if model.editable is not None:
  406. d["editable"] = model.editable
  407. if model.created_at is not None:
  408. d["created_at"] = model.created_at
  409. if model.updated_at is not None:
  410. d["updated_at"] = model.updated_at
  411. if model.description is not None:
  412. d["description"] = model.description
  413. return d
  414. def _build_segment_for_serialized_values(v: Any) -> Segment:
  415. """
  416. Reconstructs Segment objects from serialized values, with special handling
  417. for FileSegment and ArrayFileSegment types.
  418. This function should only be used when:
  419. 1. No explicit type information is available
  420. 2. The input value is in serialized form (dict or list)
  421. It detects potential file objects in the serialized data and properly rebuilds the
  422. appropriate segment type.
  423. """
  424. return build_segment(WorkflowDraftVariable.rebuild_file_types(v))
  425. class DraftVariableSaver:
  426. # _DUMMY_OUTPUT_IDENTITY is a placeholder output for workflow nodes.
  427. # Its sole possible value is `None`.
  428. #
  429. # This is used to signal the execution of a workflow node when it has no other outputs.
  430. _DUMMY_OUTPUT_IDENTITY: ClassVar[str] = "__dummy__"
  431. _DUMMY_OUTPUT_VALUE: ClassVar[None] = None
  432. # _EXCLUDE_VARIABLE_NAMES_MAPPING maps node types and versions to variable names that
  433. # should be excluded when saving draft variables. This prevents certain internal or
  434. # technical variables from being exposed in the draft environment, particularly those
  435. # that aren't meant to be directly edited or viewed by users.
  436. _EXCLUDE_VARIABLE_NAMES_MAPPING: dict[NodeType, frozenset[str]] = {
  437. NodeType.LLM: frozenset(["finish_reason"]),
  438. NodeType.LOOP: frozenset(["loop_round"]),
  439. }
  440. # Database session used for persisting draft variables.
  441. _session: Session
  442. # The application ID associated with the draft variables.
  443. # This should match the `Workflow.app_id` of the workflow to which the current node belongs.
  444. _app_id: str
  445. # The ID of the node for which DraftVariableSaver is saving output variables.
  446. _node_id: str
  447. # The type of the current node (see NodeType).
  448. _node_type: NodeType
  449. # Indicates how the workflow execution was triggered (see InvokeFrom).
  450. _invoke_from: InvokeFrom
  451. #
  452. _node_execution_id: str
  453. # _enclosing_node_id identifies the container node that the current node belongs to.
  454. # For example, if the current node is an LLM node inside an Iteration node
  455. # or Loop node, then `_enclosing_node_id` refers to the ID of
  456. # the containing Iteration or Loop node.
  457. #
  458. # If the current node is not nested within another node, `_enclosing_node_id` is
  459. # `None`.
  460. _enclosing_node_id: str | None
  461. def __init__(
  462. self,
  463. session: Session,
  464. app_id: str,
  465. node_id: str,
  466. node_type: NodeType,
  467. invoke_from: InvokeFrom,
  468. node_execution_id: str,
  469. enclosing_node_id: str | None = None,
  470. ):
  471. self._session = session
  472. self._app_id = app_id
  473. self._node_id = node_id
  474. self._node_type = node_type
  475. self._invoke_from = invoke_from
  476. self._node_execution_id = node_execution_id
  477. self._enclosing_node_id = enclosing_node_id
  478. def _create_dummy_output_variable(self):
  479. return WorkflowDraftVariable.new_node_variable(
  480. app_id=self._app_id,
  481. node_id=self._node_id,
  482. name=self._DUMMY_OUTPUT_IDENTITY,
  483. node_execution_id=self._node_execution_id,
  484. value=build_segment(self._DUMMY_OUTPUT_VALUE),
  485. visible=False,
  486. editable=False,
  487. )
  488. def _should_save_output_variables_for_draft(self) -> bool:
  489. # Only save output variables for debugging execution of workflow.
  490. if self._invoke_from != InvokeFrom.DEBUGGER:
  491. return False
  492. if self._enclosing_node_id is not None and self._node_type != NodeType.VARIABLE_ASSIGNER:
  493. # Currently we do not save output variables for nodes inside loop or iteration.
  494. return False
  495. return True
  496. def _build_from_variable_assigner_mapping(self, process_data: Mapping[str, Any]) -> list[WorkflowDraftVariable]:
  497. draft_vars: list[WorkflowDraftVariable] = []
  498. updated_variables = get_updated_variables(process_data) or []
  499. for item in updated_variables:
  500. selector = item.selector
  501. if len(selector) < MIN_SELECTORS_LENGTH:
  502. raise Exception("selector too short")
  503. # NOTE(QuantumGhost): only the following two kinds of variable could be updated by
  504. # VariableAssigner: ConversationVariable and iteration variable.
  505. # We only save conversation variable here.
  506. if selector[0] != CONVERSATION_VARIABLE_NODE_ID:
  507. continue
  508. segment = WorkflowDraftVariable.build_segment_with_type(segment_type=item.value_type, value=item.new_value)
  509. draft_vars.append(
  510. WorkflowDraftVariable.new_conversation_variable(
  511. app_id=self._app_id,
  512. name=item.name,
  513. value=segment,
  514. )
  515. )
  516. # Add a dummy output variable to indicate that this node is executed.
  517. draft_vars.append(self._create_dummy_output_variable())
  518. return draft_vars
  519. def _build_variables_from_start_mapping(self, output: Mapping[str, Any]) -> list[WorkflowDraftVariable]:
  520. draft_vars = []
  521. has_non_sys_variables = False
  522. for name, value in output.items():
  523. value_seg = _build_segment_for_serialized_values(value)
  524. node_id, name = self._normalize_variable_for_start_node(name)
  525. # If node_id is not `sys`, it means that the variable is a user-defined input field
  526. # in `Start` node.
  527. if node_id != SYSTEM_VARIABLE_NODE_ID:
  528. draft_vars.append(
  529. WorkflowDraftVariable.new_node_variable(
  530. app_id=self._app_id,
  531. node_id=self._node_id,
  532. name=name,
  533. node_execution_id=self._node_execution_id,
  534. value=value_seg,
  535. visible=True,
  536. editable=True,
  537. )
  538. )
  539. has_non_sys_variables = True
  540. else:
  541. if name == SystemVariableKey.FILES:
  542. # Here we know the type of variable must be `array[file]`, we
  543. # just build files from the value.
  544. files = [File.model_validate(v) for v in value]
  545. if files:
  546. value_seg = WorkflowDraftVariable.build_segment_with_type(SegmentType.ARRAY_FILE, files)
  547. else:
  548. value_seg = ArrayFileSegment(value=[])
  549. draft_vars.append(
  550. WorkflowDraftVariable.new_sys_variable(
  551. app_id=self._app_id,
  552. name=name,
  553. node_execution_id=self._node_execution_id,
  554. value=value_seg,
  555. editable=self._should_variable_be_editable(node_id, name),
  556. )
  557. )
  558. if not has_non_sys_variables:
  559. draft_vars.append(self._create_dummy_output_variable())
  560. return draft_vars
  561. def _normalize_variable_for_start_node(self, name: str) -> tuple[str, str]:
  562. if not name.startswith(f"{SYSTEM_VARIABLE_NODE_ID}."):
  563. return self._node_id, name
  564. _, name_ = name.split(".", maxsplit=1)
  565. return SYSTEM_VARIABLE_NODE_ID, name_
  566. def _build_variables_from_mapping(self, output: Mapping[str, Any]) -> list[WorkflowDraftVariable]:
  567. draft_vars = []
  568. for name, value in output.items():
  569. if not self._should_variable_be_saved(name):
  570. _logger.debug(
  571. "Skip saving variable as it has been excluded by its node_type, name=%s, node_type=%s",
  572. name,
  573. self._node_type,
  574. )
  575. continue
  576. if isinstance(value, Segment):
  577. value_seg = value
  578. else:
  579. value_seg = _build_segment_for_serialized_values(value)
  580. draft_vars.append(
  581. WorkflowDraftVariable.new_node_variable(
  582. app_id=self._app_id,
  583. node_id=self._node_id,
  584. name=name,
  585. node_execution_id=self._node_execution_id,
  586. value=value_seg,
  587. visible=self._should_variable_be_visible(self._node_id, self._node_type, name),
  588. )
  589. )
  590. return draft_vars
  591. def save(
  592. self,
  593. process_data: Mapping[str, Any] | None = None,
  594. outputs: Mapping[str, Any] | None = None,
  595. ):
  596. draft_vars: list[WorkflowDraftVariable] = []
  597. if outputs is None:
  598. outputs = {}
  599. if process_data is None:
  600. process_data = {}
  601. if not self._should_save_output_variables_for_draft():
  602. return
  603. if self._node_type == NodeType.VARIABLE_ASSIGNER:
  604. draft_vars = self._build_from_variable_assigner_mapping(process_data=process_data)
  605. elif self._node_type == NodeType.START:
  606. draft_vars = self._build_variables_from_start_mapping(outputs)
  607. else:
  608. draft_vars = self._build_variables_from_mapping(outputs)
  609. _batch_upsert_draft_varaible(self._session, draft_vars)
  610. @staticmethod
  611. def _should_variable_be_editable(node_id: str, name: str) -> bool:
  612. if node_id in (CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID):
  613. return False
  614. if node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name):
  615. return False
  616. return True
  617. @staticmethod
  618. def _should_variable_be_visible(node_id: str, node_type: NodeType, name: str) -> bool:
  619. if node_type in NodeType.IF_ELSE:
  620. return False
  621. if node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name):
  622. return False
  623. return True
  624. def _should_variable_be_saved(self, name: str) -> bool:
  625. exclude_var_names = self._EXCLUDE_VARIABLE_NAMES_MAPPING.get(self._node_type)
  626. if exclude_var_names is None:
  627. return True
  628. return name not in exclude_var_names