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.

variable_factory.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 UnsupportedSegmentTypeError(Exception):
  40. pass
  41. class TypeMismatchError(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. result: Variable
  75. match value_type:
  76. case SegmentType.STRING:
  77. result = StringVariable.model_validate(mapping)
  78. case SegmentType.SECRET:
  79. result = SecretVariable.model_validate(mapping)
  80. case SegmentType.NUMBER | SegmentType.INTEGER if isinstance(value, int):
  81. mapping = dict(mapping)
  82. mapping["value_type"] = SegmentType.INTEGER
  83. result = IntegerVariable.model_validate(mapping)
  84. case SegmentType.NUMBER | SegmentType.FLOAT if isinstance(value, float):
  85. mapping = dict(mapping)
  86. mapping["value_type"] = SegmentType.FLOAT
  87. result = FloatVariable.model_validate(mapping)
  88. case SegmentType.NUMBER if not isinstance(value, float | int):
  89. raise VariableError(f"invalid number value {value}")
  90. case SegmentType.OBJECT if isinstance(value, dict):
  91. result = ObjectVariable.model_validate(mapping)
  92. case SegmentType.ARRAY_STRING if isinstance(value, list):
  93. result = ArrayStringVariable.model_validate(mapping)
  94. case SegmentType.ARRAY_NUMBER if isinstance(value, list):
  95. result = ArrayNumberVariable.model_validate(mapping)
  96. case SegmentType.ARRAY_OBJECT if isinstance(value, list):
  97. result = ArrayObjectVariable.model_validate(mapping)
  98. case _:
  99. raise VariableError(f"not supported value type {value_type}")
  100. if result.size > dify_config.MAX_VARIABLE_SIZE:
  101. raise VariableError(f"variable size {result.size} exceeds limit {dify_config.MAX_VARIABLE_SIZE}")
  102. if not result.selector:
  103. result = result.model_copy(update={"selector": selector})
  104. return cast(Variable, result)
  105. def infer_segment_type_from_value(value: Any, /) -> SegmentType:
  106. return build_segment(value).value_type
  107. def build_segment(value: Any, /) -> Segment:
  108. # NOTE: If you have runtime type information available, consider using the `build_segment_with_type`
  109. # below
  110. if value is None:
  111. return NoneSegment()
  112. if isinstance(value, str):
  113. return StringSegment(value=value)
  114. if isinstance(value, int):
  115. return IntegerSegment(value=value)
  116. if isinstance(value, float):
  117. return FloatSegment(value=value)
  118. if isinstance(value, dict):
  119. return ObjectSegment(value=value)
  120. if isinstance(value, File):
  121. return FileSegment(value=value)
  122. if isinstance(value, list):
  123. items = [build_segment(item) for item in value]
  124. types = {item.value_type for item in items}
  125. if all(isinstance(item, ArraySegment) for item in items):
  126. return ArrayAnySegment(value=value)
  127. elif len(types) != 1:
  128. if types.issubset({SegmentType.NUMBER, SegmentType.INTEGER, SegmentType.FLOAT}):
  129. return ArrayNumberSegment(value=value)
  130. return ArrayAnySegment(value=value)
  131. match types.pop():
  132. case SegmentType.STRING:
  133. return ArrayStringSegment(value=value)
  134. case SegmentType.NUMBER | SegmentType.INTEGER | SegmentType.FLOAT:
  135. return ArrayNumberSegment(value=value)
  136. case SegmentType.OBJECT:
  137. return ArrayObjectSegment(value=value)
  138. case SegmentType.FILE:
  139. return ArrayFileSegment(value=value)
  140. case SegmentType.NONE:
  141. return ArrayAnySegment(value=value)
  142. case _:
  143. # This should be unreachable.
  144. raise ValueError(f"not supported value {value}")
  145. raise ValueError(f"not supported value {value}")
  146. _segment_factory: Mapping[SegmentType, type[Segment]] = {
  147. SegmentType.NONE: NoneSegment,
  148. SegmentType.STRING: StringSegment,
  149. SegmentType.INTEGER: IntegerSegment,
  150. SegmentType.FLOAT: FloatSegment,
  151. SegmentType.FILE: FileSegment,
  152. SegmentType.OBJECT: ObjectSegment,
  153. # Array types
  154. SegmentType.ARRAY_ANY: ArrayAnySegment,
  155. SegmentType.ARRAY_STRING: ArrayStringSegment,
  156. SegmentType.ARRAY_NUMBER: ArrayNumberSegment,
  157. SegmentType.ARRAY_OBJECT: ArrayObjectSegment,
  158. SegmentType.ARRAY_FILE: ArrayFileSegment,
  159. }
  160. def build_segment_with_type(segment_type: SegmentType, value: Any) -> Segment:
  161. """
  162. Build a segment with explicit type checking.
  163. This function creates a segment from a value while enforcing type compatibility
  164. with the specified segment_type. It provides stricter type validation compared
  165. to the standard build_segment function.
  166. Args:
  167. segment_type: The expected SegmentType for the resulting segment
  168. value: The value to be converted into a segment
  169. Returns:
  170. Segment: A segment instance of the appropriate type
  171. Raises:
  172. TypeMismatchError: If the value type doesn't match the expected segment_type
  173. Special Cases:
  174. - For empty list [] values, if segment_type is array[*], returns the corresponding array type
  175. - Type validation is performed before segment creation
  176. Examples:
  177. >>> build_segment_with_type(SegmentType.STRING, "hello")
  178. StringSegment(value="hello")
  179. >>> build_segment_with_type(SegmentType.ARRAY_STRING, [])
  180. ArrayStringSegment(value=[])
  181. >>> build_segment_with_type(SegmentType.STRING, 123)
  182. # Raises TypeMismatchError
  183. """
  184. # Handle None values
  185. if value is None:
  186. if segment_type == SegmentType.NONE:
  187. return NoneSegment()
  188. else:
  189. raise TypeMismatchError(f"Type mismatch: expected {segment_type}, but got None")
  190. # Handle empty list special case for array types
  191. if isinstance(value, list) and len(value) == 0:
  192. if segment_type == SegmentType.ARRAY_ANY:
  193. return ArrayAnySegment(value=value)
  194. elif segment_type == SegmentType.ARRAY_STRING:
  195. return ArrayStringSegment(value=value)
  196. elif segment_type == SegmentType.ARRAY_NUMBER:
  197. return ArrayNumberSegment(value=value)
  198. elif segment_type == SegmentType.ARRAY_OBJECT:
  199. return ArrayObjectSegment(value=value)
  200. elif segment_type == SegmentType.ARRAY_FILE:
  201. return ArrayFileSegment(value=value)
  202. else:
  203. raise TypeMismatchError(f"Type mismatch: expected {segment_type}, but got empty list")
  204. inferred_type = SegmentType.infer_segment_type(value)
  205. # Type compatibility checking
  206. if inferred_type is None:
  207. raise TypeMismatchError(
  208. f"Type mismatch: expected {segment_type}, but got python object, type={type(value)}, value={value}"
  209. )
  210. if inferred_type == segment_type:
  211. segment_class = _segment_factory[segment_type]
  212. return segment_class(value_type=segment_type, value=value)
  213. elif segment_type == SegmentType.NUMBER and inferred_type in (
  214. SegmentType.INTEGER,
  215. SegmentType.FLOAT,
  216. ):
  217. segment_class = _segment_factory[inferred_type]
  218. return segment_class(value_type=inferred_type, value=value)
  219. else:
  220. raise TypeMismatchError(f"Type mismatch: expected {segment_type}, but got {inferred_type}, value={value}")
  221. def segment_to_variable(
  222. *,
  223. segment: Segment,
  224. selector: Sequence[str],
  225. id: str | None = None,
  226. name: str | None = None,
  227. description: str = "",
  228. ) -> Variable:
  229. if isinstance(segment, Variable):
  230. return segment
  231. name = name or selector[-1]
  232. id = id or str(uuid4())
  233. segment_type = type(segment)
  234. if segment_type not in SEGMENT_TO_VARIABLE_MAP:
  235. raise UnsupportedSegmentTypeError(f"not supported segment type {segment_type}")
  236. variable_class = SEGMENT_TO_VARIABLE_MAP[segment_type]
  237. return cast(
  238. Variable,
  239. variable_class(
  240. id=id,
  241. name=name,
  242. description=description,
  243. value=segment.value,
  244. selector=list(selector),
  245. ),
  246. )