metrics.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. class Metrics:
  2. """Metrics class can record various metrics during running and evaluation.
  3. Currently, we define the following metrics:
  4. accumulated_cost: the total cost (USD $) of the current LLM.
  5. """
  6. def __init__(self) -> None:
  7. self._accumulated_cost: float = 0.0
  8. self._costs: list[float] = []
  9. @property
  10. def accumulated_cost(self) -> float:
  11. return self._accumulated_cost
  12. @accumulated_cost.setter
  13. def accumulated_cost(self, value: float) -> None:
  14. if value < 0:
  15. raise ValueError('Total cost cannot be negative.')
  16. self._accumulated_cost = value
  17. @property
  18. def costs(self) -> list:
  19. return self._costs
  20. def add_cost(self, value: float) -> None:
  21. if value < 0:
  22. raise ValueError('Added cost cannot be negative.')
  23. self._accumulated_cost += value
  24. self._costs.append(value)
  25. def merge(self, other: 'Metrics') -> None:
  26. self._accumulated_cost += other.accumulated_cost
  27. self._costs += other._costs
  28. def get(self):
  29. """Return the metrics in a dictionary."""
  30. return {'accumulated_cost': self._accumulated_cost, 'costs': self._costs}
  31. def log(self):
  32. """Log the metrics."""
  33. metrics = self.get()
  34. logs = ''
  35. for key, value in metrics.items():
  36. logs += f'{key}: {value}\n'
  37. return logs
  38. def __repr__(self):
  39. return f'Metrics({self.get()}'