node.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import logging
  2. from abc import abstractmethod
  3. from collections.abc import Generator, Mapping, Sequence
  4. from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, Union, cast
  5. from core.workflow.entities.node_entities import NodeRunResult
  6. from core.workflow.nodes.enums import CONTINUE_ON_ERROR_NODE_TYPE, NodeType
  7. from core.workflow.nodes.event import NodeEvent, RunCompletedEvent
  8. from models.workflow import WorkflowNodeExecutionStatus
  9. from .entities import BaseNodeData
  10. if TYPE_CHECKING:
  11. from core.workflow.graph_engine.entities.event import InNodeEvent
  12. from core.workflow.graph_engine.entities.graph import Graph
  13. from core.workflow.graph_engine.entities.graph_init_params import GraphInitParams
  14. from core.workflow.graph_engine.entities.graph_runtime_state import GraphRuntimeState
  15. logger = logging.getLogger(__name__)
  16. GenericNodeData = TypeVar("GenericNodeData", bound=BaseNodeData)
  17. class BaseNode(Generic[GenericNodeData]):
  18. _node_data_cls: type[BaseNodeData]
  19. _node_type: NodeType
  20. def __init__(
  21. self,
  22. id: str,
  23. config: Mapping[str, Any],
  24. graph_init_params: "GraphInitParams",
  25. graph: "Graph",
  26. graph_runtime_state: "GraphRuntimeState",
  27. previous_node_id: Optional[str] = None,
  28. thread_pool_id: Optional[str] = None,
  29. ) -> None:
  30. self.id = id
  31. self.tenant_id = graph_init_params.tenant_id
  32. self.app_id = graph_init_params.app_id
  33. self.workflow_type = graph_init_params.workflow_type
  34. self.workflow_id = graph_init_params.workflow_id
  35. self.graph_config = graph_init_params.graph_config
  36. self.user_id = graph_init_params.user_id
  37. self.user_from = graph_init_params.user_from
  38. self.invoke_from = graph_init_params.invoke_from
  39. self.workflow_call_depth = graph_init_params.call_depth
  40. self.graph = graph
  41. self.graph_runtime_state = graph_runtime_state
  42. self.previous_node_id = previous_node_id
  43. self.thread_pool_id = thread_pool_id
  44. node_id = config.get("id")
  45. if not node_id:
  46. raise ValueError("Node ID is required.")
  47. self.node_id = node_id
  48. node_data = self._node_data_cls.model_validate(config.get("data", {}))
  49. self.node_data = cast(GenericNodeData, node_data)
  50. @abstractmethod
  51. def _run(self) -> NodeRunResult | Generator[Union[NodeEvent, "InNodeEvent"], None, None]:
  52. """
  53. Run node
  54. :return:
  55. """
  56. raise NotImplementedError
  57. def run(self) -> Generator[Union[NodeEvent, "InNodeEvent"], None, None]:
  58. try:
  59. result = self._run()
  60. except Exception as e:
  61. logger.exception(f"Node {self.node_id} failed to run")
  62. result = NodeRunResult(status=WorkflowNodeExecutionStatus.FAILED, error=str(e), error_type="SystemError")
  63. if isinstance(result, NodeRunResult):
  64. yield RunCompletedEvent(run_result=result)
  65. else:
  66. yield from result
  67. @classmethod
  68. def extract_variable_selector_to_variable_mapping(
  69. cls,
  70. *,
  71. graph_config: Mapping[str, Any],
  72. config: Mapping[str, Any],
  73. ) -> Mapping[str, Sequence[str]]:
  74. """
  75. Extract variable selector to variable mapping
  76. :param graph_config: graph config
  77. :param config: node config
  78. :return:
  79. """
  80. node_id = config.get("id")
  81. if not node_id:
  82. raise ValueError("Node ID is required when extracting variable selector to variable mapping.")
  83. node_data = cls._node_data_cls(**config.get("data", {}))
  84. return cls._extract_variable_selector_to_variable_mapping(
  85. graph_config=graph_config, node_id=node_id, node_data=cast(GenericNodeData, node_data)
  86. )
  87. @classmethod
  88. def _extract_variable_selector_to_variable_mapping(
  89. cls,
  90. *,
  91. graph_config: Mapping[str, Any],
  92. node_id: str,
  93. node_data: GenericNodeData,
  94. ) -> Mapping[str, Sequence[str]]:
  95. """
  96. Extract variable selector to variable mapping
  97. :param graph_config: graph config
  98. :param node_id: node id
  99. :param node_data: node data
  100. :return:
  101. """
  102. return {}
  103. @classmethod
  104. def get_default_config(cls, filters: Optional[dict] = None) -> dict:
  105. """
  106. Get default config of node.
  107. :param filters: filter by node config parameters.
  108. :return:
  109. """
  110. return {}
  111. @property
  112. def node_type(self) -> NodeType:
  113. """
  114. Get node type
  115. :return:
  116. """
  117. return self._node_type
  118. @property
  119. def should_continue_on_error(self) -> bool:
  120. """judge if should continue on error
  121. Returns:
  122. bool: if should continue on error
  123. """
  124. return self.node_data.error_strategy is not None and self.node_type in CONTINUE_ON_ERROR_NODE_TYPE