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

workflow_draft_variable_service.py 42KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. import dataclasses
  2. import json
  3. import logging
  4. from collections.abc import Mapping, Sequence
  5. from concurrent.futures import ThreadPoolExecutor
  6. from enum import StrEnum
  7. from typing import Any, ClassVar
  8. from sqlalchemy import Engine, orm, select
  9. from sqlalchemy.dialects.postgresql import insert
  10. from sqlalchemy.orm import Session, sessionmaker
  11. from sqlalchemy.sql.expression import and_, or_
  12. from configs import dify_config
  13. from core.app.entities.app_invoke_entities import InvokeFrom
  14. from core.file.models import File
  15. from core.variables import Segment, StringSegment, Variable
  16. from core.variables.consts import SELECTORS_LENGTH
  17. from core.variables.segments import (
  18. ArrayFileSegment,
  19. FileSegment,
  20. )
  21. from core.variables.types import SegmentType
  22. from core.variables.utils import dumps_with_segments
  23. from core.workflow.constants import CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID, SYSTEM_VARIABLE_NODE_ID
  24. from core.workflow.enums import SystemVariableKey
  25. from core.workflow.nodes import NodeType
  26. from core.workflow.nodes.variable_assigner.common.helpers import get_updated_variables
  27. from core.workflow.variable_loader import VariableLoader
  28. from extensions.ext_storage import storage
  29. from factories.file_factory import StorageKeyLoader
  30. from factories.variable_factory import build_segment, segment_to_variable
  31. from libs.datetime_utils import naive_utc_now
  32. from libs.uuid_utils import uuidv7
  33. from models import App, Conversation
  34. from models.account import Account
  35. from models.enums import DraftVariableType
  36. from models.workflow import Workflow, WorkflowDraftVariable, WorkflowDraftVariableFile, is_system_variable_editable
  37. from repositories.factory import DifyAPIRepositoryFactory
  38. from services.file_service import FileService
  39. from services.variable_truncator import VariableTruncator
  40. logger = logging.getLogger(__name__)
  41. @dataclasses.dataclass(frozen=True)
  42. class WorkflowDraftVariableList:
  43. variables: list[WorkflowDraftVariable]
  44. total: int | None = None
  45. @dataclasses.dataclass(frozen=True)
  46. class DraftVarFileDeletion:
  47. draft_var_id: str
  48. draft_var_file_id: str
  49. class WorkflowDraftVariableError(Exception):
  50. pass
  51. class VariableResetError(WorkflowDraftVariableError):
  52. pass
  53. class UpdateNotSupportedError(WorkflowDraftVariableError):
  54. pass
  55. class DraftVarLoader(VariableLoader):
  56. # This implements the VariableLoader interface for loading draft variables.
  57. #
  58. # ref: core.workflow.variable_loader.VariableLoader
  59. # Database engine used for loading variables.
  60. _engine: Engine
  61. # Application ID for which variables are being loaded.
  62. _app_id: str
  63. _tenant_id: str
  64. _fallback_variables: Sequence[Variable]
  65. def __init__(
  66. self,
  67. engine: Engine,
  68. app_id: str,
  69. tenant_id: str,
  70. fallback_variables: Sequence[Variable] | None = None,
  71. ):
  72. self._engine = engine
  73. self._app_id = app_id
  74. self._tenant_id = tenant_id
  75. self._fallback_variables = fallback_variables or []
  76. def _selector_to_tuple(self, selector: Sequence[str]) -> tuple[str, str]:
  77. return (selector[0], selector[1])
  78. def load_variables(self, selectors: list[list[str]]) -> list[Variable]:
  79. if not selectors:
  80. return []
  81. # Map each selector (as a tuple via `_selector_to_tuple`) to its corresponding Variable instance.
  82. variable_by_selector: dict[tuple[str, str], Variable] = {}
  83. with Session(bind=self._engine, expire_on_commit=False) as session:
  84. srv = WorkflowDraftVariableService(session)
  85. draft_vars = srv.get_draft_variables_by_selectors(self._app_id, selectors)
  86. # Important:
  87. files: list[File] = []
  88. # FileSegment and ArrayFileSegment are not subject to offloading, so their values
  89. # can be safely accessed before any offloading logic is applied.
  90. for draft_var in draft_vars:
  91. value = draft_var.get_value()
  92. if isinstance(value, FileSegment):
  93. files.append(value.value)
  94. elif isinstance(value, ArrayFileSegment):
  95. files.extend(value.value)
  96. with Session(bind=self._engine) as session:
  97. storage_key_loader = StorageKeyLoader(session, tenant_id=self._tenant_id)
  98. storage_key_loader.load_storage_keys(files)
  99. offloaded_draft_vars = []
  100. for draft_var in draft_vars:
  101. if draft_var.is_truncated():
  102. offloaded_draft_vars.append(draft_var)
  103. continue
  104. segment = draft_var.get_value()
  105. variable = segment_to_variable(
  106. segment=segment,
  107. selector=draft_var.get_selector(),
  108. id=draft_var.id,
  109. name=draft_var.name,
  110. description=draft_var.description,
  111. )
  112. selector_tuple = self._selector_to_tuple(variable.selector)
  113. variable_by_selector[selector_tuple] = variable
  114. # Load offloaded variables using multithreading.
  115. # This approach reduces loading time by querying external systems concurrently.
  116. with ThreadPoolExecutor(max_workers=10) as executor:
  117. offloaded_variables = executor.map(self._load_offloaded_variable, offloaded_draft_vars)
  118. for selector, variable in offloaded_variables:
  119. variable_by_selector[selector] = variable
  120. return list(variable_by_selector.values())
  121. def _load_offloaded_variable(self, draft_var: WorkflowDraftVariable) -> tuple[tuple[str, str], Variable]:
  122. # This logic is closely tied to `WorkflowDraftVaribleService._try_offload_large_variable`
  123. # and must remain synchronized with it.
  124. # Ideally, these should be co-located for better maintainability.
  125. # However, due to the current code structure, this is not straightforward.
  126. variable_file = draft_var.variable_file
  127. assert variable_file is not None
  128. upload_file = variable_file.upload_file
  129. assert upload_file is not None
  130. content = storage.load(upload_file.key)
  131. if variable_file.value_type == SegmentType.STRING:
  132. # The inferenced type is StringSegment, which is not correct inside this function.
  133. segment: Segment = StringSegment(value=content.decode())
  134. variable = segment_to_variable(
  135. segment=segment,
  136. selector=draft_var.get_selector(),
  137. id=draft_var.id,
  138. name=draft_var.name,
  139. description=draft_var.description,
  140. )
  141. return (draft_var.node_id, draft_var.name), variable
  142. deserialized = json.loads(content)
  143. segment = WorkflowDraftVariable.build_segment_with_type(variable_file.value_type, deserialized)
  144. variable = segment_to_variable(
  145. segment=segment,
  146. selector=draft_var.get_selector(),
  147. id=draft_var.id,
  148. name=draft_var.name,
  149. description=draft_var.description,
  150. )
  151. # No special handling needed for ArrayFileSegment, as we do not offload ArrayFileSegment
  152. return (draft_var.node_id, draft_var.name), variable
  153. class WorkflowDraftVariableService:
  154. _session: Session
  155. def __init__(self, session: Session):
  156. """
  157. Initialize the WorkflowDraftVariableService with a SQLAlchemy session.
  158. Args:
  159. session (Session): The SQLAlchemy session used to execute database queries.
  160. The provided session must be bound to an `Engine` object, not a specific `Connection`.
  161. Raises:
  162. AssertionError: If the provided session is not bound to an `Engine` object.
  163. """
  164. self._session = session
  165. engine = session.get_bind()
  166. # Ensure the session is bound to a engine.
  167. assert isinstance(engine, Engine)
  168. session_maker = sessionmaker(bind=engine, expire_on_commit=False)
  169. self._api_node_execution_repo = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(
  170. session_maker
  171. )
  172. def get_variable(self, variable_id: str) -> WorkflowDraftVariable | None:
  173. return (
  174. self._session.query(WorkflowDraftVariable)
  175. .options(orm.selectinload(WorkflowDraftVariable.variable_file))
  176. .where(WorkflowDraftVariable.id == variable_id)
  177. .first()
  178. )
  179. def get_draft_variables_by_selectors(
  180. self,
  181. app_id: str,
  182. selectors: Sequence[list[str]],
  183. ) -> list[WorkflowDraftVariable]:
  184. """
  185. Retrieve WorkflowDraftVariable instances based on app_id and selectors.
  186. The returned WorkflowDraftVariable objects are guaranteed to have their
  187. associated variable_file and variable_file.upload_file relationships preloaded.
  188. """
  189. ors = []
  190. for selector in selectors:
  191. assert len(selector) >= SELECTORS_LENGTH, f"Invalid selector to get: {selector}"
  192. node_id, name = selector[:2]
  193. ors.append(and_(WorkflowDraftVariable.node_id == node_id, WorkflowDraftVariable.name == name))
  194. # NOTE(QuantumGhost): Although the number of `or` expressions may be large, as long as
  195. # each expression includes conditions on both `node_id` and `name` (which are covered by the unique index),
  196. # PostgreSQL can efficiently retrieve the results using a bitmap index scan.
  197. #
  198. # Alternatively, a `SELECT` statement could be constructed for each selector and
  199. # combined using `UNION` to fetch all rows.
  200. # Benchmarking indicates that both approaches yield comparable performance.
  201. variables = (
  202. self._session.query(WorkflowDraftVariable)
  203. .options(
  204. orm.selectinload(WorkflowDraftVariable.variable_file).selectinload(
  205. WorkflowDraftVariableFile.upload_file
  206. )
  207. )
  208. .where(WorkflowDraftVariable.app_id == app_id, or_(*ors))
  209. .all()
  210. )
  211. return variables
  212. def list_variables_without_values(self, app_id: str, page: int, limit: int) -> WorkflowDraftVariableList:
  213. criteria = WorkflowDraftVariable.app_id == app_id
  214. total = None
  215. query = self._session.query(WorkflowDraftVariable).where(criteria)
  216. if page == 1:
  217. total = query.count()
  218. variables = (
  219. # Do not load the `value` field
  220. query.options(
  221. orm.defer(WorkflowDraftVariable.value, raiseload=True),
  222. )
  223. .order_by(WorkflowDraftVariable.created_at.desc())
  224. .limit(limit)
  225. .offset((page - 1) * limit)
  226. .all()
  227. )
  228. return WorkflowDraftVariableList(variables=variables, total=total)
  229. def _list_node_variables(self, app_id: str, node_id: str) -> WorkflowDraftVariableList:
  230. criteria = (
  231. WorkflowDraftVariable.app_id == app_id,
  232. WorkflowDraftVariable.node_id == node_id,
  233. )
  234. query = self._session.query(WorkflowDraftVariable).where(*criteria)
  235. variables = (
  236. query.options(orm.selectinload(WorkflowDraftVariable.variable_file))
  237. .order_by(WorkflowDraftVariable.created_at.desc())
  238. .all()
  239. )
  240. return WorkflowDraftVariableList(variables=variables)
  241. def list_node_variables(self, app_id: str, node_id: str) -> WorkflowDraftVariableList:
  242. return self._list_node_variables(app_id, node_id)
  243. def list_conversation_variables(self, app_id: str) -> WorkflowDraftVariableList:
  244. return self._list_node_variables(app_id, CONVERSATION_VARIABLE_NODE_ID)
  245. def list_system_variables(self, app_id: str) -> WorkflowDraftVariableList:
  246. return self._list_node_variables(app_id, SYSTEM_VARIABLE_NODE_ID)
  247. def get_conversation_variable(self, app_id: str, name: str) -> WorkflowDraftVariable | None:
  248. return self._get_variable(app_id=app_id, node_id=CONVERSATION_VARIABLE_NODE_ID, name=name)
  249. def get_system_variable(self, app_id: str, name: str) -> WorkflowDraftVariable | None:
  250. return self._get_variable(app_id=app_id, node_id=SYSTEM_VARIABLE_NODE_ID, name=name)
  251. def get_node_variable(self, app_id: str, node_id: str, name: str) -> WorkflowDraftVariable | None:
  252. return self._get_variable(app_id, node_id, name)
  253. def _get_variable(self, app_id: str, node_id: str, name: str) -> WorkflowDraftVariable | None:
  254. variable = (
  255. self._session.query(WorkflowDraftVariable)
  256. .options(orm.selectinload(WorkflowDraftVariable.variable_file))
  257. .where(
  258. WorkflowDraftVariable.app_id == app_id,
  259. WorkflowDraftVariable.node_id == node_id,
  260. WorkflowDraftVariable.name == name,
  261. )
  262. .first()
  263. )
  264. return variable
  265. def update_variable(
  266. self,
  267. variable: WorkflowDraftVariable,
  268. name: str | None = None,
  269. value: Segment | None = None,
  270. ) -> WorkflowDraftVariable:
  271. if not variable.editable:
  272. raise UpdateNotSupportedError(f"variable not support updating, id={variable.id}")
  273. if name is not None:
  274. variable.set_name(name)
  275. if value is not None:
  276. variable.set_value(value)
  277. variable.last_edited_at = naive_utc_now()
  278. self._session.flush()
  279. return variable
  280. def _reset_conv_var(self, workflow: Workflow, variable: WorkflowDraftVariable) -> WorkflowDraftVariable | None:
  281. conv_var_by_name = {i.name: i for i in workflow.conversation_variables}
  282. conv_var = conv_var_by_name.get(variable.name)
  283. if conv_var is None:
  284. self._session.delete(instance=variable)
  285. self._session.flush()
  286. logger.warning(
  287. "Conversation variable not found for draft variable, id=%s, name=%s", variable.id, variable.name
  288. )
  289. return None
  290. variable.set_value(conv_var)
  291. variable.last_edited_at = None
  292. self._session.add(variable)
  293. self._session.flush()
  294. return variable
  295. def _reset_node_var_or_sys_var(
  296. self, workflow: Workflow, variable: WorkflowDraftVariable
  297. ) -> WorkflowDraftVariable | None:
  298. # If a variable does not allow updating, it makes no sense to reset it.
  299. if not variable.editable:
  300. return variable
  301. # No execution record for this variable, delete the variable instead.
  302. if variable.node_execution_id is None:
  303. self._session.delete(instance=variable)
  304. self._session.flush()
  305. logger.warning("draft variable has no node_execution_id, id=%s, name=%s", variable.id, variable.name)
  306. return None
  307. node_exec = self._api_node_execution_repo.get_execution_by_id(variable.node_execution_id)
  308. if node_exec is None:
  309. logger.warning(
  310. "Node exectution not found for draft variable, id=%s, name=%s, node_execution_id=%s",
  311. variable.id,
  312. variable.name,
  313. variable.node_execution_id,
  314. )
  315. self._session.delete(instance=variable)
  316. self._session.flush()
  317. return None
  318. outputs_dict = node_exec.load_full_outputs(self._session, storage) or {}
  319. # a sentinel value used to check the absent of the output variable key.
  320. absent = object()
  321. if variable.get_variable_type() == DraftVariableType.NODE:
  322. # Get node type for proper value extraction
  323. node_config = workflow.get_node_config_by_id(variable.node_id)
  324. node_type = workflow.get_node_type_from_node_config(node_config)
  325. # Note: Based on the implementation in `_build_from_variable_assigner_mapping`,
  326. # VariableAssignerNode (both v1 and v2) can only create conversation draft variables.
  327. # For consistency, we should simply return when processing VARIABLE_ASSIGNER nodes.
  328. #
  329. # This implementation must remain synchronized with the `_build_from_variable_assigner_mapping`
  330. # and `save` methods.
  331. if node_type == NodeType.VARIABLE_ASSIGNER:
  332. return variable
  333. output_value = outputs_dict.get(variable.name, absent)
  334. else:
  335. output_value = outputs_dict.get(f"sys.{variable.name}", absent)
  336. # We cannot use `is None` to check the existence of an output variable here as
  337. # the value of the output may be `None`.
  338. if output_value is absent:
  339. # If variable not found in execution data, delete the variable
  340. self._session.delete(instance=variable)
  341. self._session.flush()
  342. return None
  343. value_seg = WorkflowDraftVariable.build_segment_with_type(variable.value_type, output_value)
  344. # Extract variable value using unified logic
  345. variable.set_value(value_seg)
  346. variable.last_edited_at = None # Reset to indicate this is a reset operation
  347. self._session.flush()
  348. return variable
  349. def reset_variable(self, workflow: Workflow, variable: WorkflowDraftVariable) -> WorkflowDraftVariable | None:
  350. variable_type = variable.get_variable_type()
  351. if variable_type == DraftVariableType.SYS and not is_system_variable_editable(variable.name):
  352. raise VariableResetError(f"cannot reset system variable, variable_id={variable.id}")
  353. if variable_type == DraftVariableType.CONVERSATION:
  354. return self._reset_conv_var(workflow, variable)
  355. else:
  356. return self._reset_node_var_or_sys_var(workflow, variable)
  357. def delete_variable(self, variable: WorkflowDraftVariable):
  358. if not variable.is_truncated():
  359. self._session.delete(variable)
  360. return
  361. variable_query = (
  362. select(WorkflowDraftVariable)
  363. .options(
  364. orm.selectinload(WorkflowDraftVariable.variable_file).selectinload(
  365. WorkflowDraftVariableFile.upload_file
  366. ),
  367. )
  368. .where(WorkflowDraftVariable.id == variable.id)
  369. )
  370. variable_reloaded = self._session.execute(variable_query).scalars().first()
  371. variable_file = variable_reloaded.variable_file
  372. if variable_file is None:
  373. logger.warning(
  374. "Associated WorkflowDraftVariableFile not found, draft_var_id=%s, file_id=%s",
  375. variable_reloaded.id,
  376. variable_reloaded.file_id,
  377. )
  378. self._session.delete(variable)
  379. return
  380. upload_file = variable_file.upload_file
  381. if upload_file is None:
  382. logger.warning(
  383. "Associated UploadFile not found, draft_var_id=%s, file_id=%s, upload_file_id=%s",
  384. variable_reloaded.id,
  385. variable_reloaded.file_id,
  386. variable_file.upload_file_id,
  387. )
  388. self._session.delete(variable)
  389. self._session.delete(variable_file)
  390. return
  391. storage.delete(upload_file.key)
  392. self._session.delete(upload_file)
  393. self._session.delete(upload_file)
  394. self._session.delete(variable)
  395. def delete_workflow_variables(self, app_id: str):
  396. (
  397. self._session.query(WorkflowDraftVariable)
  398. .where(WorkflowDraftVariable.app_id == app_id)
  399. .delete(synchronize_session=False)
  400. )
  401. def delete_workflow_draft_variable_file(self, deletions: list[DraftVarFileDeletion]):
  402. variable_files_query = (
  403. select(WorkflowDraftVariableFile)
  404. .options(orm.selectinload(WorkflowDraftVariableFile.upload_file))
  405. .where(WorkflowDraftVariableFile.id.in_([i.draft_var_file_id for i in deletions]))
  406. )
  407. variable_files = self._session.execute(variable_files_query).scalars().all()
  408. variable_files_by_id = {i.id: i for i in variable_files}
  409. for i in deletions:
  410. variable_file = variable_files_by_id.get(i.draft_var_file_id)
  411. if variable_file is None:
  412. logger.warning(
  413. "Associated WorkflowDraftVariableFile not found, draft_var_id=%s, file_id=%s",
  414. i.draft_var_id,
  415. i.draft_var_file_id,
  416. )
  417. continue
  418. upload_file = variable_file.upload_file
  419. if upload_file is None:
  420. logger.warning(
  421. "Associated UploadFile not found, draft_var_id=%s, file_id=%s, upload_file_id=%s",
  422. i.draft_var_id,
  423. i.draft_var_file_id,
  424. variable_file.upload_file_id,
  425. )
  426. self._session.delete(variable_file)
  427. else:
  428. storage.delete(upload_file.key)
  429. self._session.delete(upload_file)
  430. self._session.delete(variable_file)
  431. def delete_node_variables(self, app_id: str, node_id: str):
  432. return self._delete_node_variables(app_id, node_id)
  433. def _delete_node_variables(self, app_id: str, node_id: str):
  434. self._session.query(WorkflowDraftVariable).where(
  435. WorkflowDraftVariable.app_id == app_id,
  436. WorkflowDraftVariable.node_id == node_id,
  437. ).delete()
  438. def _get_conversation_id_from_draft_variable(self, app_id: str) -> str | None:
  439. draft_var = self._get_variable(
  440. app_id=app_id,
  441. node_id=SYSTEM_VARIABLE_NODE_ID,
  442. name=str(SystemVariableKey.CONVERSATION_ID),
  443. )
  444. if draft_var is None:
  445. return None
  446. segment = draft_var.get_value()
  447. if not isinstance(segment, StringSegment):
  448. logger.warning(
  449. "sys.conversation_id variable is not a string: app_id=%s, id=%s",
  450. app_id,
  451. draft_var.id,
  452. )
  453. return None
  454. return segment.value
  455. def get_or_create_conversation(
  456. self,
  457. account_id: str,
  458. app: App,
  459. workflow: Workflow,
  460. ) -> str:
  461. """
  462. get_or_create_conversation creates and returns the ID of a conversation for debugging.
  463. If a conversation already exists, as determined by the following criteria, its ID is returned:
  464. - The system variable `sys.conversation_id` exists in the draft variable table, and
  465. - A corresponding conversation record is found in the database.
  466. If no such conversation exists, a new conversation is created and its ID is returned.
  467. """
  468. conv_id = self._get_conversation_id_from_draft_variable(workflow.app_id)
  469. if conv_id is not None:
  470. conversation = (
  471. self._session.query(Conversation)
  472. .where(
  473. Conversation.id == conv_id,
  474. Conversation.app_id == workflow.app_id,
  475. )
  476. .first()
  477. )
  478. # Only return the conversation ID if it exists and is valid (has a correspond conversation record in DB).
  479. if conversation is not None:
  480. return conv_id
  481. conversation = Conversation(
  482. app_id=workflow.app_id,
  483. app_model_config_id=app.app_model_config_id,
  484. model_provider=None,
  485. model_id="",
  486. override_model_configs=None,
  487. mode=app.mode,
  488. name="Draft Debugging Conversation",
  489. inputs={},
  490. introduction="",
  491. system_instruction="",
  492. system_instruction_tokens=0,
  493. status="normal",
  494. invoke_from=InvokeFrom.DEBUGGER.value,
  495. from_source="console",
  496. from_end_user_id=None,
  497. from_account_id=account_id,
  498. )
  499. self._session.add(conversation)
  500. self._session.flush()
  501. return conversation.id
  502. def prefill_conversation_variable_default_values(self, workflow: Workflow):
  503. """"""
  504. draft_conv_vars: list[WorkflowDraftVariable] = []
  505. for conv_var in workflow.conversation_variables:
  506. draft_var = WorkflowDraftVariable.new_conversation_variable(
  507. app_id=workflow.app_id,
  508. name=conv_var.name,
  509. value=conv_var,
  510. description=conv_var.description,
  511. )
  512. draft_conv_vars.append(draft_var)
  513. _batch_upsert_draft_variable(
  514. self._session,
  515. draft_conv_vars,
  516. policy=_UpsertPolicy.IGNORE,
  517. )
  518. class _UpsertPolicy(StrEnum):
  519. IGNORE = "ignore"
  520. OVERWRITE = "overwrite"
  521. def _batch_upsert_draft_variable(
  522. session: Session,
  523. draft_vars: Sequence[WorkflowDraftVariable],
  524. policy: _UpsertPolicy = _UpsertPolicy.OVERWRITE,
  525. ):
  526. if not draft_vars:
  527. return None
  528. # Although we could use SQLAlchemy ORM operations here, we choose not to for several reasons:
  529. #
  530. # 1. The variable saving process involves writing multiple rows to the
  531. # `workflow_draft_variables` table. Batch insertion significantly improves performance.
  532. # 2. Using the ORM would require either:
  533. #
  534. # a. Checking for the existence of each variable before insertion,
  535. # resulting in 2n SQL statements for n variables and potential concurrency issues.
  536. # b. Attempting insertion first, then updating if a unique index violation occurs,
  537. # which still results in n to 2n SQL statements.
  538. #
  539. # Both approaches are inefficient and suboptimal.
  540. # 3. We do not need to retrieve the results of the SQL execution or populate ORM
  541. # model instances with the returned values.
  542. # 4. Batch insertion with `ON CONFLICT DO UPDATE` allows us to insert or update all
  543. # variables in a single SQL statement, avoiding the issues above.
  544. #
  545. # For these reasons, we use the SQLAlchemy query builder and rely on dialect-specific
  546. # insert operations instead of the ORM layer.
  547. stmt = insert(WorkflowDraftVariable).values([_model_to_insertion_dict(v) for v in draft_vars])
  548. if policy == _UpsertPolicy.OVERWRITE:
  549. stmt = stmt.on_conflict_do_update(
  550. index_elements=WorkflowDraftVariable.unique_app_id_node_id_name(),
  551. set_={
  552. # Refresh creation timestamp to ensure updated variables
  553. # appear first in chronologically sorted result sets.
  554. "created_at": stmt.excluded.created_at,
  555. "updated_at": stmt.excluded.updated_at,
  556. "last_edited_at": stmt.excluded.last_edited_at,
  557. "description": stmt.excluded.description,
  558. "value_type": stmt.excluded.value_type,
  559. "value": stmt.excluded.value,
  560. "visible": stmt.excluded.visible,
  561. "editable": stmt.excluded.editable,
  562. "node_execution_id": stmt.excluded.node_execution_id,
  563. "file_id": stmt.excluded.file_id,
  564. },
  565. )
  566. elif policy == _UpsertPolicy.IGNORE:
  567. stmt = stmt.on_conflict_do_nothing(index_elements=WorkflowDraftVariable.unique_app_id_node_id_name())
  568. else:
  569. raise Exception("Invalid value for update policy.")
  570. session.execute(stmt)
  571. def _model_to_insertion_dict(model: WorkflowDraftVariable) -> dict[str, Any]:
  572. d: dict[str, Any] = {
  573. "app_id": model.app_id,
  574. "last_edited_at": None,
  575. "node_id": model.node_id,
  576. "name": model.name,
  577. "selector": model.selector,
  578. "value_type": model.value_type,
  579. "value": model.value,
  580. "node_execution_id": model.node_execution_id,
  581. "file_id": model.file_id,
  582. }
  583. if model.visible is not None:
  584. d["visible"] = model.visible
  585. if model.editable is not None:
  586. d["editable"] = model.editable
  587. if model.created_at is not None:
  588. d["created_at"] = model.created_at
  589. if model.updated_at is not None:
  590. d["updated_at"] = model.updated_at
  591. if model.description is not None:
  592. d["description"] = model.description
  593. return d
  594. def _build_segment_for_serialized_values(v: Any) -> Segment:
  595. """
  596. Reconstructs Segment objects from serialized values, with special handling
  597. for FileSegment and ArrayFileSegment types.
  598. This function should only be used when:
  599. 1. No explicit type information is available
  600. 2. The input value is in serialized form (dict or list)
  601. It detects potential file objects in the serialized data and properly rebuilds the
  602. appropriate segment type.
  603. """
  604. return build_segment(WorkflowDraftVariable.rebuild_file_types(v))
  605. def _make_filename_trans_table() -> dict[int, str]:
  606. linux_chars = ["/", "\x00"]
  607. windows_chars = [
  608. "<",
  609. ">",
  610. ":",
  611. '"',
  612. "/",
  613. "\\",
  614. "|",
  615. "?",
  616. "*",
  617. ]
  618. windows_chars.extend(chr(i) for i in range(32))
  619. trans_table = dict.fromkeys(linux_chars + windows_chars, "_")
  620. return str.maketrans(trans_table)
  621. _FILENAME_TRANS_TABLE = _make_filename_trans_table()
  622. class DraftVariableSaver:
  623. # _DUMMY_OUTPUT_IDENTITY is a placeholder output for workflow nodes.
  624. # Its sole possible value is `None`.
  625. #
  626. # This is used to signal the execution of a workflow node when it has no other outputs.
  627. _DUMMY_OUTPUT_IDENTITY: ClassVar[str] = "__dummy__"
  628. _DUMMY_OUTPUT_VALUE: ClassVar[None] = None
  629. # _EXCLUDE_VARIABLE_NAMES_MAPPING maps node types and versions to variable names that
  630. # should be excluded when saving draft variables. This prevents certain internal or
  631. # technical variables from being exposed in the draft environment, particularly those
  632. # that aren't meant to be directly edited or viewed by users.
  633. _EXCLUDE_VARIABLE_NAMES_MAPPING: dict[NodeType, frozenset[str]] = {
  634. NodeType.LLM: frozenset(["finish_reason"]),
  635. NodeType.LOOP: frozenset(["loop_round"]),
  636. }
  637. # Database session used for persisting draft variables.
  638. _session: Session
  639. # The application ID associated with the draft variables.
  640. # This should match the `Workflow.app_id` of the workflow to which the current node belongs.
  641. _app_id: str
  642. # The ID of the node for which DraftVariableSaver is saving output variables.
  643. _node_id: str
  644. # The type of the current node (see NodeType).
  645. _node_type: NodeType
  646. #
  647. _node_execution_id: str
  648. # _enclosing_node_id identifies the container node that the current node belongs to.
  649. # For example, if the current node is an LLM node inside an Iteration node
  650. # or Loop node, then `_enclosing_node_id` refers to the ID of
  651. # the containing Iteration or Loop node.
  652. #
  653. # If the current node is not nested within another node, `_enclosing_node_id` is
  654. # `None`.
  655. _enclosing_node_id: str | None
  656. def __init__(
  657. self,
  658. session: Session,
  659. app_id: str,
  660. node_id: str,
  661. node_type: NodeType,
  662. node_execution_id: str,
  663. user: Account,
  664. enclosing_node_id: str | None = None,
  665. ):
  666. # Important: `node_execution_id` parameter refers to the primary key (`id`) of the
  667. # WorkflowNodeExecutionModel/WorkflowNodeExecution, not their `node_execution_id`
  668. # field. These are distinct database fields with different purposes.
  669. self._session = session
  670. self._app_id = app_id
  671. self._node_id = node_id
  672. self._node_type = node_type
  673. self._node_execution_id = node_execution_id
  674. self._user = user
  675. self._enclosing_node_id = enclosing_node_id
  676. def _create_dummy_output_variable(self):
  677. return WorkflowDraftVariable.new_node_variable(
  678. app_id=self._app_id,
  679. node_id=self._node_id,
  680. name=self._DUMMY_OUTPUT_IDENTITY,
  681. node_execution_id=self._node_execution_id,
  682. value=build_segment(self._DUMMY_OUTPUT_VALUE),
  683. visible=False,
  684. editable=False,
  685. )
  686. def _should_save_output_variables_for_draft(self) -> bool:
  687. if self._enclosing_node_id is not None and self._node_type != NodeType.VARIABLE_ASSIGNER:
  688. # Currently we do not save output variables for nodes inside loop or iteration.
  689. return False
  690. return True
  691. def _build_from_variable_assigner_mapping(self, process_data: Mapping[str, Any]) -> list[WorkflowDraftVariable]:
  692. draft_vars: list[WorkflowDraftVariable] = []
  693. updated_variables = get_updated_variables(process_data) or []
  694. for item in updated_variables:
  695. selector = item.selector
  696. if len(selector) < SELECTORS_LENGTH:
  697. raise Exception("selector too short")
  698. # NOTE(QuantumGhost): only the following two kinds of variable could be updated by
  699. # VariableAssigner: ConversationVariable and iteration variable.
  700. # We only save conversation variable here.
  701. if selector[0] != CONVERSATION_VARIABLE_NODE_ID:
  702. continue
  703. segment = WorkflowDraftVariable.build_segment_with_type(segment_type=item.value_type, value=item.new_value)
  704. draft_vars.append(
  705. WorkflowDraftVariable.new_conversation_variable(
  706. app_id=self._app_id,
  707. name=item.name,
  708. value=segment,
  709. )
  710. )
  711. # Add a dummy output variable to indicate that this node is executed.
  712. draft_vars.append(self._create_dummy_output_variable())
  713. return draft_vars
  714. def _build_variables_from_start_mapping(self, output: Mapping[str, Any]) -> list[WorkflowDraftVariable]:
  715. draft_vars = []
  716. has_non_sys_variables = False
  717. for name, value in output.items():
  718. value_seg = _build_segment_for_serialized_values(value)
  719. node_id, name = self._normalize_variable_for_start_node(name)
  720. # If node_id is not `sys`, it means that the variable is a user-defined input field
  721. # in `Start` node.
  722. if node_id != SYSTEM_VARIABLE_NODE_ID:
  723. draft_vars.append(
  724. WorkflowDraftVariable.new_node_variable(
  725. app_id=self._app_id,
  726. node_id=self._node_id,
  727. name=name,
  728. node_execution_id=self._node_execution_id,
  729. value=value_seg,
  730. visible=True,
  731. editable=True,
  732. )
  733. )
  734. has_non_sys_variables = True
  735. else:
  736. if name == SystemVariableKey.FILES:
  737. # Here we know the type of variable must be `array[file]`, we
  738. # just build files from the value.
  739. files = [File.model_validate(v) for v in value]
  740. if files:
  741. value_seg = WorkflowDraftVariable.build_segment_with_type(SegmentType.ARRAY_FILE, files)
  742. else:
  743. value_seg = ArrayFileSegment(value=[])
  744. draft_vars.append(
  745. WorkflowDraftVariable.new_sys_variable(
  746. app_id=self._app_id,
  747. name=name,
  748. node_execution_id=self._node_execution_id,
  749. value=value_seg,
  750. editable=self._should_variable_be_editable(node_id, name),
  751. )
  752. )
  753. if not has_non_sys_variables:
  754. draft_vars.append(self._create_dummy_output_variable())
  755. return draft_vars
  756. def _normalize_variable_for_start_node(self, name: str) -> tuple[str, str]:
  757. if not name.startswith(f"{SYSTEM_VARIABLE_NODE_ID}."):
  758. return self._node_id, name
  759. _, name_ = name.split(".", maxsplit=1)
  760. return SYSTEM_VARIABLE_NODE_ID, name_
  761. def _build_variables_from_mapping(self, output: Mapping[str, Any]) -> list[WorkflowDraftVariable]:
  762. draft_vars = []
  763. for name, value in output.items():
  764. if not self._should_variable_be_saved(name):
  765. logger.debug(
  766. "Skip saving variable as it has been excluded by its node_type, name=%s, node_type=%s",
  767. name,
  768. self._node_type,
  769. )
  770. continue
  771. if isinstance(value, Segment):
  772. value_seg = value
  773. else:
  774. value_seg = _build_segment_for_serialized_values(value)
  775. draft_vars.append(
  776. self._create_draft_variable(
  777. name=name,
  778. value=value_seg,
  779. visible=True,
  780. editable=True,
  781. ),
  782. # WorkflowDraftVariable.new_node_variable(
  783. # app_id=self._app_id,
  784. # node_id=self._node_id,
  785. # name=name,
  786. # node_execution_id=self._node_execution_id,
  787. # value=value_seg,
  788. # visible=self._should_variable_be_visible(self._node_id, self._node_type, name),
  789. # )
  790. )
  791. return draft_vars
  792. def _generate_filename(self, name: str):
  793. node_id_escaped = self._node_id.translate(_FILENAME_TRANS_TABLE)
  794. return f"{node_id_escaped}-{name}"
  795. def _try_offload_large_variable(
  796. self,
  797. name: str,
  798. value_seg: Segment,
  799. ) -> tuple[Segment, WorkflowDraftVariableFile] | None:
  800. # This logic is closely tied to `DraftVarLoader._load_offloaded_variable` and must remain
  801. # synchronized with it.
  802. # Ideally, these should be co-located for better maintainability.
  803. # However, due to the current code structure, this is not straightforward.
  804. truncator = VariableTruncator(
  805. max_size_bytes=dify_config.WORKFLOW_VARIABLE_TRUNCATION_MAX_SIZE,
  806. array_element_limit=dify_config.WORKFLOW_VARIABLE_TRUNCATION_ARRAY_LENGTH,
  807. string_length_limit=dify_config.WORKFLOW_VARIABLE_TRUNCATION_STRING_LENGTH,
  808. )
  809. truncation_result = truncator.truncate(value_seg)
  810. if not truncation_result.truncated:
  811. return None
  812. original_length = None
  813. if isinstance(value_seg.value, (list, dict)):
  814. original_length = len(value_seg.value)
  815. # Prepare content for storage
  816. if isinstance(value_seg, StringSegment):
  817. # For string types, store as plain text
  818. original_content_serialized = value_seg.value
  819. content_type = "text/plain"
  820. filename = f"{self._generate_filename(name)}.txt"
  821. else:
  822. # For other types, store as JSON
  823. original_content_serialized = dumps_with_segments(value_seg.value, ensure_ascii=False)
  824. content_type = "application/json"
  825. filename = f"{self._generate_filename(name)}.json"
  826. original_size = len(original_content_serialized.encode("utf-8"))
  827. bind = self._session.get_bind()
  828. assert isinstance(bind, Engine)
  829. file_srv = FileService(bind)
  830. upload_file = file_srv.upload_file(
  831. filename=filename,
  832. content=original_content_serialized.encode(),
  833. mimetype=content_type,
  834. user=self._user,
  835. )
  836. # Create WorkflowDraftVariableFile record
  837. variable_file = WorkflowDraftVariableFile(
  838. id=uuidv7(),
  839. upload_file_id=upload_file.id,
  840. size=original_size,
  841. length=original_length,
  842. value_type=value_seg.value_type,
  843. app_id=self._app_id,
  844. tenant_id=self._user.current_tenant_id,
  845. user_id=self._user.id,
  846. )
  847. engine = bind = self._session.get_bind()
  848. assert isinstance(engine, Engine)
  849. with Session(bind=engine, expire_on_commit=False) as session:
  850. session.add(variable_file)
  851. session.commit()
  852. return truncation_result.result, variable_file
  853. def _create_draft_variable(
  854. self,
  855. *,
  856. name: str,
  857. value: Segment,
  858. visible: bool = True,
  859. editable: bool = True,
  860. ) -> WorkflowDraftVariable:
  861. """Create a draft variable with large variable handling and truncation."""
  862. # Handle Segment values
  863. offload_result = self._try_offload_large_variable(name, value)
  864. if offload_result is None:
  865. # Create the draft variable
  866. draft_var = WorkflowDraftVariable.new_node_variable(
  867. app_id=self._app_id,
  868. node_id=self._node_id,
  869. name=name,
  870. node_execution_id=self._node_execution_id,
  871. value=value,
  872. visible=visible,
  873. editable=editable,
  874. )
  875. return draft_var
  876. else:
  877. truncated, var_file = offload_result
  878. # Create the draft variable
  879. draft_var = WorkflowDraftVariable.new_node_variable(
  880. app_id=self._app_id,
  881. node_id=self._node_id,
  882. name=name,
  883. node_execution_id=self._node_execution_id,
  884. value=truncated,
  885. visible=visible,
  886. editable=False,
  887. file_id=var_file.id,
  888. )
  889. return draft_var
  890. def save(
  891. self,
  892. process_data: Mapping[str, Any] | None = None,
  893. outputs: Mapping[str, Any] | None = None,
  894. ):
  895. draft_vars: list[WorkflowDraftVariable] = []
  896. if outputs is None:
  897. outputs = {}
  898. if process_data is None:
  899. process_data = {}
  900. if not self._should_save_output_variables_for_draft():
  901. return
  902. if self._node_type == NodeType.VARIABLE_ASSIGNER:
  903. draft_vars = self._build_from_variable_assigner_mapping(process_data=process_data)
  904. elif self._node_type == NodeType.START:
  905. draft_vars = self._build_variables_from_start_mapping(outputs)
  906. else:
  907. draft_vars = self._build_variables_from_mapping(outputs)
  908. _batch_upsert_draft_variable(self._session, draft_vars)
  909. @staticmethod
  910. def _should_variable_be_editable(node_id: str, name: str) -> bool:
  911. if node_id in (CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID):
  912. return False
  913. if node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name):
  914. return False
  915. return True
  916. @staticmethod
  917. def _should_variable_be_visible(node_id: str, node_type: NodeType, name: str) -> bool:
  918. if node_type in NodeType.IF_ELSE:
  919. return False
  920. if node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name):
  921. return False
  922. return True
  923. def _should_variable_be_saved(self, name: str) -> bool:
  924. exclude_var_names = self._EXCLUDE_VARIABLE_NAMES_MAPPING.get(self._node_type)
  925. if exclude_var_names is None:
  926. return True
  927. return name not in exclude_var_names