entities.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from collections.abc import Mapping
  2. from typing import Annotated, Any, Literal, Optional
  3. from pydantic import AfterValidator, BaseModel, Field
  4. from core.variables.types import SegmentType
  5. from core.workflow.nodes.base import BaseLoopNodeData, BaseLoopState, BaseNodeData
  6. from core.workflow.utils.condition.entities import Condition
  7. _VALID_VAR_TYPE = frozenset(
  8. [
  9. SegmentType.STRING,
  10. SegmentType.NUMBER,
  11. SegmentType.OBJECT,
  12. SegmentType.BOOLEAN,
  13. SegmentType.ARRAY_STRING,
  14. SegmentType.ARRAY_NUMBER,
  15. SegmentType.ARRAY_OBJECT,
  16. SegmentType.ARRAY_BOOLEAN,
  17. ]
  18. )
  19. def _is_valid_var_type(seg_type: SegmentType) -> SegmentType:
  20. if seg_type not in _VALID_VAR_TYPE:
  21. raise ValueError(...)
  22. return seg_type
  23. class LoopVariableData(BaseModel):
  24. """
  25. Loop Variable Data.
  26. """
  27. label: str
  28. var_type: Annotated[SegmentType, AfterValidator(_is_valid_var_type)]
  29. value_type: Literal["variable", "constant"]
  30. value: Optional[Any | list[str]] = None
  31. class LoopNodeData(BaseLoopNodeData):
  32. """
  33. Loop Node Data.
  34. """
  35. loop_count: int # Maximum number of loops
  36. break_conditions: list[Condition] # Conditions to break the loop
  37. logical_operator: Literal["and", "or"]
  38. loop_variables: Optional[list[LoopVariableData]] = Field(default_factory=list[LoopVariableData])
  39. outputs: Optional[Mapping[str, Any]] = None
  40. class LoopStartNodeData(BaseNodeData):
  41. """
  42. Loop Start Node Data.
  43. """
  44. pass
  45. class LoopEndNodeData(BaseNodeData):
  46. """
  47. Loop End Node Data.
  48. """
  49. pass
  50. class LoopState(BaseLoopState):
  51. """
  52. Loop State.
  53. """
  54. outputs: list[Any] = Field(default_factory=list)
  55. current_output: Optional[Any] = None
  56. class MetaData(BaseLoopState.MetaData):
  57. """
  58. Data.
  59. """
  60. loop_length: int
  61. def get_last_output(self) -> Optional[Any]:
  62. """
  63. Get last output.
  64. """
  65. if self.outputs:
  66. return self.outputs[-1]
  67. return None
  68. def get_current_output(self) -> Optional[Any]:
  69. """
  70. Get current output.
  71. """
  72. return self.current_output