variables.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import json
  2. from collections.abc import Mapping, Sequence
  3. from pydantic import Field
  4. from core.file.file_obj import FileVar
  5. from core.helper import encrypter
  6. from .segments import Segment, StringSegment
  7. from .types import SegmentType
  8. class Variable(Segment):
  9. """
  10. A variable is a segment that has a name.
  11. """
  12. id: str = Field(
  13. default='',
  14. description="Unique identity for variable. It's only used by environment variables now.",
  15. )
  16. name: str
  17. class StringVariable(StringSegment, Variable):
  18. pass
  19. class FloatVariable(Variable):
  20. value_type: SegmentType = SegmentType.NUMBER
  21. value: float
  22. class IntegerVariable(Variable):
  23. value_type: SegmentType = SegmentType.NUMBER
  24. value: int
  25. class ObjectVariable(Variable):
  26. value_type: SegmentType = SegmentType.OBJECT
  27. value: Mapping[str, Variable]
  28. @property
  29. def text(self) -> str:
  30. # TODO: Process variables.
  31. return json.dumps(self.model_dump()['value'], ensure_ascii=False)
  32. @property
  33. def log(self) -> str:
  34. # TODO: Process variables.
  35. return json.dumps(self.model_dump()['value'], ensure_ascii=False, indent=2)
  36. @property
  37. def markdown(self) -> str:
  38. # TODO: Use markdown code block
  39. return json.dumps(self.model_dump()['value'], ensure_ascii=False, indent=2)
  40. class ArrayVariable(Variable):
  41. value_type: SegmentType = SegmentType.ARRAY
  42. value: Sequence[Variable]
  43. @property
  44. def markdown(self) -> str:
  45. return '\n'.join(['- ' + item.markdown for item in self.value])
  46. class FileVariable(Variable):
  47. value_type: SegmentType = SegmentType.FILE
  48. # TODO: embed FileVar in this model.
  49. value: FileVar
  50. @property
  51. def markdown(self) -> str:
  52. return self.value.to_markdown()
  53. class SecretVariable(StringVariable):
  54. value_type: SegmentType = SegmentType.SECRET
  55. @property
  56. def log(self) -> str:
  57. return encrypter.obfuscated_token(self.value)