iteration_budget.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """Per-agent iteration budget — thread-safe consume/refund counter.
  2. Each ``AIAgent`` (parent or subagent) holds its own :class:`IterationBudget`: the parent's
  3. cap is ``max_iterations`` (default 500), each subagent's ``delegation.max_iterations``
  4. (default 50), so total iterations across parent + subagents can exceed the parent's cap.
  5. """
  6. from __future__ import annotations
  7. import math
  8. import threading
  9. def normalize_budget_warning_ratio(value) -> float | None:
  10. """A finite ratio strictly between zero and one, or None (feature off)."""
  11. if value is None or isinstance(value, bool):
  12. return None
  13. try:
  14. ratio = float(value)
  15. except (TypeError, ValueError):
  16. return None
  17. return ratio if math.isfinite(ratio) and 0 < ratio < 1 else None
  18. class IterationBudget:
  19. """Thread-safe iteration counter; ``execute_code`` (programmatic tool calling)
  20. iterations are refunded via :meth:`refund` so they don't eat into the budget."""
  21. def __init__(self, max_total: int):
  22. self.max_total = max_total
  23. self._used = 0
  24. self._lock = threading.Lock()
  25. def consume(self) -> bool:
  26. """Try to consume one iteration. Returns True if allowed."""
  27. with self._lock:
  28. if self._used >= self.max_total:
  29. return False
  30. self._used += 1
  31. return True
  32. def refund(self) -> None:
  33. """Give back one iteration (e.g. for execute_code turns)."""
  34. with self._lock:
  35. if self._used > 0:
  36. self._used -= 1
  37. @property
  38. def used(self) -> int:
  39. with self._lock:
  40. return self._used
  41. @property
  42. def remaining(self) -> int:
  43. with self._lock:
  44. return max(0, self.max_total - self._used)
  45. __all__ = ["IterationBudget"]