variable_factory.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from collections.abc import Mapping, Sequence
  2. from typing import Any, cast
  3. from uuid import uuid4
  4. from configs import dify_config
  5. from core.file import File
  6. from core.variables.exc import VariableError
  7. from core.variables.segments import (
  8. ArrayAnySegment,
  9. ArrayFileSegment,
  10. ArrayNumberSegment,
  11. ArrayObjectSegment,
  12. ArraySegment,
  13. ArrayStringSegment,
  14. FileSegment,
  15. FloatSegment,
  16. IntegerSegment,
  17. NoneSegment,
  18. ObjectSegment,
  19. Segment,
  20. StringSegment,
  21. )
  22. from core.variables.types import SegmentType
  23. from core.variables.variables import (
  24. ArrayAnyVariable,
  25. ArrayFileVariable,
  26. ArrayNumberVariable,
  27. ArrayObjectVariable,
  28. ArrayStringVariable,
  29. FileVariable,
  30. FloatVariable,
  31. IntegerVariable,
  32. NoneVariable,
  33. ObjectVariable,
  34. SecretVariable,
  35. StringVariable,
  36. Variable,
  37. )
  38. from core.workflow.constants import CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID
  39. class InvalidSelectorError(ValueError):
  40. pass
  41. class UnsupportedSegmentTypeError(Exception):
  42. pass
  43. # Define the constant
  44. SEGMENT_TO_VARIABLE_MAP = {
  45. StringSegment: StringVariable,
  46. IntegerSegment: IntegerVariable,
  47. FloatSegment: FloatVariable,
  48. ObjectSegment: ObjectVariable,
  49. FileSegment: FileVariable,
  50. ArrayStringSegment: ArrayStringVariable,
  51. ArrayNumberSegment: ArrayNumberVariable,
  52. ArrayObjectSegment: ArrayObjectVariable,
  53. ArrayFileSegment: ArrayFileVariable,
  54. ArrayAnySegment: ArrayAnyVariable,
  55. NoneSegment: NoneVariable,
  56. }
  57. def build_conversation_variable_from_mapping(mapping: Mapping[str, Any], /) -> Variable:
  58. if not mapping.get("name"):
  59. raise VariableError("missing name")
  60. return _build_variable_from_mapping(mapping=mapping, selector=[CONVERSATION_VARIABLE_NODE_ID, mapping["name"]])
  61. def build_environment_variable_from_mapping(mapping: Mapping[str, Any], /) -> Variable:
  62. if not mapping.get("name"):
  63. raise VariableError("missing name")
  64. return _build_variable_from_mapping(mapping=mapping, selector=[ENVIRONMENT_VARIABLE_NODE_ID, mapping["name"]])
  65. def _build_variable_from_mapping(*, mapping: Mapping[str, Any], selector: Sequence[str]) -> Variable:
  66. """
  67. This factory function is used to create the environment variable or the conversation variable,
  68. not support the File type.
  69. """
  70. if (value_type := mapping.get("value_type")) is None:
  71. raise VariableError("missing value type")
  72. if (value := mapping.get("value")) is None:
  73. raise VariableError("missing value")
  74. # FIXME: using Any here, fix it later
  75. result: Any
  76. match value_type:
  77. case SegmentType.STRING:
  78. result = StringVariable.model_validate(mapping)
  79. case SegmentType.SECRET:
  80. result = SecretVariable.model_validate(mapping)
  81. case SegmentType.NUMBER if isinstance(value, int):
  82. result = IntegerVariable.model_validate(mapping)
  83. case SegmentType.NUMBER if isinstance(value, float):
  84. result = FloatVariable.model_validate(mapping)
  85. case SegmentType.NUMBER if not isinstance(value, float | int):
  86. raise VariableError(f"invalid number value {value}")
  87. case SegmentType.OBJECT if isinstance(value, dict):
  88. result = ObjectVariable.model_validate(mapping)
  89. case SegmentType.ARRAY_STRING if isinstance(value, list):
  90. result = ArrayStringVariable.model_validate(mapping)
  91. case SegmentType.ARRAY_NUMBER if isinstance(value, list):
  92. result = ArrayNumberVariable.model_validate(mapping)
  93. case SegmentType.ARRAY_OBJECT if isinstance(value, list):
  94. result = ArrayObjectVariable.model_validate(mapping)
  95. case _:
  96. raise VariableError(f"not supported value type {value_type}")
  97. if result.size > dify_config.MAX_VARIABLE_SIZE:
  98. raise VariableError(f"variable size {result.size} exceeds limit {dify_config.MAX_VARIABLE_SIZE}")
  99. if not result.selector:
  100. result = result.model_copy(update={"selector": selector})
  101. return cast(Variable, result)
  102. def build_segment(value: Any, /) -> Segment:
  103. if value is None:
  104. return NoneSegment()
  105. if isinstance(value, str):
  106. return StringSegment(value=value)
  107. if isinstance(value, int):
  108. return IntegerSegment(value=value)
  109. if isinstance(value, float):
  110. return FloatSegment(value=value)
  111. if isinstance(value, dict):
  112. return ObjectSegment(value=value)
  113. if isinstance(value, File):
  114. return FileSegment(value=value)
  115. if isinstance(value, list):
  116. items = [build_segment(item) for item in value]
  117. types = {item.value_type for item in items}
  118. if len(types) != 1 or all(isinstance(item, ArraySegment) for item in items):
  119. return ArrayAnySegment(value=value)
  120. match types.pop():
  121. case SegmentType.STRING:
  122. return ArrayStringSegment(value=value)
  123. case SegmentType.NUMBER:
  124. return ArrayNumberSegment(value=value)
  125. case SegmentType.OBJECT:
  126. return ArrayObjectSegment(value=value)
  127. case SegmentType.FILE:
  128. return ArrayFileSegment(value=value)
  129. case SegmentType.NONE:
  130. return ArrayAnySegment(value=value)
  131. case _:
  132. raise ValueError(f"not supported value {value}")
  133. raise ValueError(f"not supported value {value}")
  134. def segment_to_variable(
  135. *,
  136. segment: Segment,
  137. selector: Sequence[str],
  138. id: str | None = None,
  139. name: str | None = None,
  140. description: str = "",
  141. ) -> Variable:
  142. if isinstance(segment, Variable):
  143. return segment
  144. name = name or selector[-1]
  145. id = id or str(uuid4())
  146. segment_type = type(segment)
  147. if segment_type not in SEGMENT_TO_VARIABLE_MAP:
  148. raise UnsupportedSegmentTypeError(f"not supported segment type {segment_type}")
  149. variable_class = SEGMENT_TO_VARIABLE_MAP[segment_type]
  150. return cast(
  151. Variable,
  152. variable_class(
  153. id=id,
  154. name=name,
  155. description=description,
  156. value=segment.value,
  157. selector=selector,
  158. ),
  159. )