|
| 1 | +import dataclasses |
| 2 | +import sys |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from typing import Any, Dict, Optional |
| 5 | + |
| 6 | +from .serializable_data_class import SerializableDataClass |
| 7 | + |
| 8 | + |
| 9 | +@dataclasses.dataclass |
| 10 | +class Score(SerializableDataClass): |
| 11 | + """A score for an evaluation. The score is a float between 0 and 1.""" |
| 12 | + |
| 13 | + name: str |
| 14 | + """The name of the score. This should be a unique name for the scorer.""" |
| 15 | + |
| 16 | + score: Optional[float] = None |
| 17 | + """The score for the evaluation. This should be a float between 0 and 1. If the score is None, the evaluation is considered to be skipped.""" |
| 18 | + |
| 19 | + metadata: Dict[str, Any] = dataclasses.field(default_factory=dict) |
| 20 | + """Metadata for the score. This can be used to store additional information about the score.""" |
| 21 | + |
| 22 | + # DEPRECATION_NOTICE: this field is deprecated, as errors are propagated up to the caller. |
| 23 | + error: Optional[Exception] = None |
| 24 | + """Deprecated: The error field is deprecated, as errors are now propagated to the caller. The field will be removed in a future version of the library.""" |
| 25 | + |
| 26 | + def as_dict(self): |
| 27 | + return { |
| 28 | + "score": self.score, |
| 29 | + "metadata": self.metadata, |
| 30 | + } |
| 31 | + |
| 32 | + def __post_init__(self): |
| 33 | + if self.score is not None and (self.score < 0 or self.score > 1): |
| 34 | + raise ValueError(f"score ({self.score}) must be between 0 and 1") |
| 35 | + if self.error is not None: |
| 36 | + print( |
| 37 | + "The error field is deprecated, as errors are now propagated to the caller. The field will be removed in a future version of the library", |
| 38 | + sys.stderr, |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +class Scorer(ABC): |
| 43 | + async def eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score: |
| 44 | + return await self._run_eval_async(output, expected, **kwargs) |
| 45 | + |
| 46 | + def eval(self, output: Any, expected: Any = None, **kwargs: Any) -> Score: |
| 47 | + return self._run_eval_sync(output, expected, **kwargs) |
| 48 | + |
| 49 | + def __call__(self, output: Any, expected: Any = None, **kwargs: Any) -> Score: |
| 50 | + return self.eval(output, expected, **kwargs) |
| 51 | + |
| 52 | + async def _run_eval_async(self, output: Any, expected: Any = None, **kwargs: Any) -> Score: |
| 53 | + # By default we just run the sync version in a thread |
| 54 | + return self._run_eval_sync(output, expected, **kwargs) |
| 55 | + |
| 56 | + def _name(self) -> str: |
| 57 | + return self.__class__.__name__ |
| 58 | + |
| 59 | + @abstractmethod |
| 60 | + def _run_eval_sync(self, output: Any, expected: Any = None, **kwargs: Any) -> Score: |
| 61 | + ... |
| 62 | + |
| 63 | + |
| 64 | +__all__ = ["Score", "Scorer"] |
0 commit comments