node.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 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. self.node_data: GenericNodeData = cast(GenericNodeData, self._node_data_cls(**config.get("data", {})))
  49. @abstractmethod
  50. def _run(self) -> NodeRunResult | Generator[Union[NodeEvent, "InNodeEvent"], None, None]:
  51. """
  52. Run node
  53. :return:
  54. """
  55. raise NotImplementedError
  56. def run(self) -> Generator[Union[NodeEvent, "InNodeEvent"], None, None]:
  57. try:
  58. result = self._run()
  59. except Exception as e:
  60. logger.exception(f"Node {self.node_id} failed to run: {e}")
  61. result = NodeRunResult(
  62. status=WorkflowNodeExecutionStatus.FAILED,
  63. error=str(e),
  64. )
  65. if isinstance(result, NodeRunResult):
  66. yield RunCompletedEvent(run_result=result)
  67. else:
  68. yield from result
  69. @classmethod
  70. def extract_variable_selector_to_variable_mapping(
  71. cls,
  72. *,
  73. graph_config: Mapping[str, Any],
  74. config: Mapping[str, Any],
  75. ) -> Mapping[str, Sequence[str]]:
  76. """
  77. Extract variable selector to variable mapping
  78. :param graph_config: graph config
  79. :param config: node config
  80. :return:
  81. """
  82. node_id = config.get("id")
  83. if not node_id:
  84. raise ValueError("Node ID is required when extracting variable selector to variable mapping.")
  85. node_data = cls._node_data_cls(**config.get("data", {}))
  86. return cls._extract_variable_selector_to_variable_mapping(
  87. graph_config=graph_config, node_id=node_id, node_data=cast(GenericNodeData, node_data)
  88. )
  89. @classmethod
  90. def _extract_variable_selector_to_variable_mapping(
  91. cls,
  92. *,
  93. graph_config: Mapping[str, Any],
  94. node_id: str,
  95. node_data: GenericNodeData,
  96. ) -> Mapping[str, Sequence[str]]:
  97. """
  98. Extract variable selector to variable mapping
  99. :param graph_config: graph config
  100. :param node_id: node id
  101. :param node_data: node data
  102. :return:
  103. """
  104. return {}
  105. @classmethod
  106. def get_default_config(cls, filters: Optional[dict] = None) -> dict:
  107. """
  108. Get default config of node.
  109. :param filters: filter by node config parameters.
  110. :return:
  111. """
  112. return {}
  113. @property
  114. def node_type(self) -> NodeType:
  115. """
  116. Get node type
  117. :return:
  118. """
  119. return self._node_type