Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions py/src/braintrust/score.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import dataclasses
import inspect
import math
import warnings
from abc import ABC, abstractmethod
from collections.abc import Mapping
Expand Down Expand Up @@ -45,8 +46,14 @@ def as_dict(self):
}

def __post_init__(self):
if self.score is not None and (self.score < 0 or self.score > 1):
raise ValueError(f"score ({self.score}) must be between 0 and 1")
if self.score is not None:
# bool is a supported scorer return (OneOrMoreScores includes bool), so
# it intentionally passes through here; only reject non-finite floats,
# which silently poison downstream averages.
if isinstance(self.score, float) and not math.isfinite(self.score):
raise ValueError(f"score ({self.score}) must be a finite number between 0 and 1")
if self.score < 0 or self.score > 1:
raise ValueError(f"score ({self.score}) must be between 0 and 1")
if self.error is not None:
warnings.warn(
"The error field is deprecated, as errors are now propagated to the caller."
Expand Down
16 changes: 16 additions & 0 deletions py/src/braintrust/test_score.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,5 +181,21 @@ def test_validation_requires_non_empty_id(self):
Classification(id="")


class TestScoreValidation(unittest.TestCase):
def test_rejects_non_finite_values(self):
for invalid in (float("nan"), float("inf"), -float("inf")):
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
Score(name="invalid", score=invalid)

def test_accepts_and_round_trips_valid_values(self):
# bool is a supported scorer return (OneOrMoreScores includes bool) and
# must keep working; the old range-only check accepted it.
for valid in (0, 1, 0.5, True, False):
with self.subTest(valid=valid):
score = Score(name="valid", score=valid)
self.assertEqual(score.as_dict()["score"], valid)
self.assertEqual(Score.from_dict(score.as_dict()).score, valid)


if __name__ == "__main__":
unittest.main()