Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

variable_factory.py 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. # Define the constant
  42. SEGMENT_TO_VARIABLE_MAP = {
  43. StringSegment: StringVariable,
  44. IntegerSegment: IntegerVariable,
  45. FloatSegment: FloatVariable,
  46. ObjectSegment: ObjectVariable,
  47. FileSegment: FileVariable,
  48. ArrayStringSegment: ArrayStringVariable,
  49. ArrayNumberSegment: ArrayNumberVariable,
  50. ArrayObjectSegment: ArrayObjectVariable,
  51. ArrayFileSegment: ArrayFileVariable,
  52. ArrayAnySegment: ArrayAnyVariable,
  53. NoneSegment: NoneVariable,
  54. }
  55. def build_conversation_variable_from_mapping(mapping: Mapping[str, Any], /) -> Variable:
  56. if not mapping.get("name"):
  57. raise VariableError("missing name")
  58. return _build_variable_from_mapping(mapping=mapping, selector=[CONVERSATION_VARIABLE_NODE_ID, mapping["name"]])
  59. def build_environment_variable_from_mapping(mapping: Mapping[str, Any], /) -> Variable:
  60. if not mapping.get("name"):
  61. raise VariableError("missing name")
  62. return _build_variable_from_mapping(mapping=mapping, selector=[ENVIRONMENT_VARIABLE_NODE_ID, mapping["name"]])
  63. def _build_variable_from_mapping(*, mapping: Mapping[str, Any], selector: Sequence[str]) -> Variable:
  64. """
  65. This factory function is used to create the environment variable or the conversation variable,
  66. not support the File type.
  67. """
  68. if (value_type := mapping.get("value_type")) is None:
  69. raise VariableError("missing value type")
  70. if (value := mapping.get("value")) is None:
  71. raise VariableError("missing value")
  72. result: Variable
  73. match value_type:
  74. case SegmentType.STRING:
  75. result = StringVariable.model_validate(mapping)
  76. case SegmentType.SECRET:
  77. result = SecretVariable.model_validate(mapping)
  78. case SegmentType.NUMBER if isinstance(value, int):
  79. result = IntegerVariable.model_validate(mapping)
  80. case SegmentType.NUMBER if isinstance(value, float):
  81. result = FloatVariable.model_validate(mapping)
  82. case SegmentType.NUMBER if not isinstance(value, float | int):
  83. raise VariableError(f"invalid number value {value}")
  84. case SegmentType.OBJECT if isinstance(value, dict):
  85. result = ObjectVariable.model_validate(mapping)
  86. case SegmentType.ARRAY_STRING if isinstance(value, list):
  87. result = ArrayStringVariable.model_validate(mapping)
  88. case SegmentType.ARRAY_NUMBER if isinstance(value, list):
  89. result = ArrayNumberVariable.model_validate(mapping)
  90. case SegmentType.ARRAY_OBJECT if isinstance(value, list):
  91. result = ArrayObjectVariable.model_validate(mapping)
  92. case _:
  93. raise VariableError(f"not supported value type {value_type}")
  94. if result.size > dify_config.MAX_VARIABLE_SIZE:
  95. raise VariableError(f"variable size {result.size} exceeds limit {dify_config.MAX_VARIABLE_SIZE}")
  96. if not result.selector:
  97. result = result.model_copy(update={"selector": selector})
  98. return cast(Variable, result)
  99. def build_segment(value: Any, /) -> Segment:
  100. if value is None:
  101. return NoneSegment()
  102. if isinstance(value, str):
  103. return StringSegment(value=value)
  104. if isinstance(value, int):
  105. return IntegerSegment(value=value)
  106. if isinstance(value, float):
  107. return FloatSegment(value=value)
  108. if isinstance(value, dict):
  109. return ObjectSegment(value=value)
  110. if isinstance(value, File):
  111. return FileSegment(value=value)
  112. if isinstance(value, list):
  113. items = [build_segment(item) for item in value]
  114. types = {item.value_type for item in items}
  115. if len(types) != 1 or all(isinstance(item, ArraySegment) for item in items):
  116. return ArrayAnySegment(value=value)
  117. match types.pop():
  118. case SegmentType.STRING:
  119. return ArrayStringSegment(value=value)
  120. case SegmentType.NUMBER:
  121. return ArrayNumberSegment(value=value)
  122. case SegmentType.OBJECT:
  123. return ArrayObjectSegment(value=value)
  124. case SegmentType.FILE:
  125. return ArrayFileSegment(value=value)
  126. case SegmentType.NONE:
  127. return ArrayAnySegment(value=value)
  128. case _:
  129. raise ValueError(f"not supported value {value}")
  130. raise ValueError(f"not supported value {value}")
  131. def segment_to_variable(
  132. *,
  133. segment: Segment,
  134. selector: Sequence[str],
  135. id: str | None = None,
  136. name: str | None = None,
  137. description: str = "",
  138. ) -> Variable:
  139. if isinstance(segment, Variable):
  140. return segment
  141. name = name or selector[-1]
  142. id = id or str(uuid4())
  143. segment_type = type(segment)
  144. if segment_type not in SEGMENT_TO_VARIABLE_MAP:
  145. raise UnsupportedSegmentTypeError(f"not supported segment type {segment_type}")
  146. variable_class = SEGMENT_TO_VARIABLE_MAP[segment_type]
  147. return cast(
  148. Variable,
  149. variable_class(
  150. id=id,
  151. name=name,
  152. description=description,
  153. value=segment.value,
  154. selector=selector,
  155. ),
  156. )