segments.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from typing import Any
  2. from pydantic import BaseModel, ConfigDict, field_validator
  3. from .types import SegmentType
  4. class Segment(BaseModel):
  5. model_config = ConfigDict(frozen=True)
  6. value_type: SegmentType
  7. value: Any
  8. @field_validator('value_type')
  9. def validate_value_type(cls, value):
  10. """
  11. This validator checks if the provided value is equal to the default value of the 'value_type' field.
  12. If the value is different, a ValueError is raised.
  13. """
  14. if value != cls.model_fields['value_type'].default:
  15. raise ValueError("Cannot modify 'value_type'")
  16. return value
  17. @property
  18. def text(self) -> str:
  19. return str(self.value)
  20. @property
  21. def log(self) -> str:
  22. return str(self.value)
  23. @property
  24. def markdown(self) -> str:
  25. return str(self.value)
  26. def to_object(self) -> Any:
  27. if isinstance(self.value, Segment):
  28. return self.value.to_object()
  29. if isinstance(self.value, list):
  30. return [v.to_object() for v in self.value]
  31. if isinstance(self.value, dict):
  32. return {k: v.to_object() for k, v in self.value.items()}
  33. return self.value
  34. class NoneSegment(Segment):
  35. value_type: SegmentType = SegmentType.NONE
  36. value: None = None
  37. @property
  38. def text(self) -> str:
  39. return 'null'
  40. @property
  41. def log(self) -> str:
  42. return 'null'
  43. @property
  44. def markdown(self) -> str:
  45. return 'null'
  46. class StringSegment(Segment):
  47. value_type: SegmentType = SegmentType.STRING
  48. value: str