metrics.py 1.3 KB

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