Coverage for mt_ai/budget.py: 100.00%

22 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 18:53 +0000

1"""Per-request work budget for one MT AI turn (SB-1143). 

2 

3Two limits, both deterministic: 

4 

5- `max_llm_calls` — enforced by ADK itself (`RunConfig.max_llm_calls`), which 

6 raises `LlmCallsLimitExceededError` before the call that would exceed it. 

7- `max_tool_calls` — enforced by `ToolCallGuard`, an ADK `before_tool_callback` 

8 that raises before the tool that would exceed it runs. 

9 

10Either way the run stops; nothing continues in the background. Token and cost 

11budgets, and per-user quotas, belong to later slices (mt2/ai-cost.md). 

12""" 

13 

14from dataclasses import dataclass 

15from typing import Any, Literal 

16 

17BudgetLimit = Literal["llm_calls", "tool_calls"] 

18 

19 

20@dataclass(frozen=True) 

21class Budget: 

22 max_llm_calls: int = 4 

23 max_tool_calls: int = 3 

24 

25 def __post_init__(self) -> None: 

26 if self.max_llm_calls < 1 or self.max_tool_calls < 0: 

27 raise ValueError("budget limits must be positive") 

28 

29 

30class BudgetExhaustedError(Exception): 

31 def __init__(self, limit: BudgetLimit) -> None: 

32 super().__init__(f"MT AI budget exhausted: {limit}") 

33 self.limit = limit 

34 

35 

36class ToolCallGuard: 

37 """Counts tool calls in one run and stops the run at the limit.""" 

38 

39 def __init__(self, max_tool_calls: int) -> None: 

40 self.max_tool_calls = max_tool_calls 

41 self.calls = 0 

42 

43 def before_tool(self, tool: Any, args: dict[str, Any], tool_context: Any) -> None: 

44 if self.calls >= self.max_tool_calls: 

45 raise BudgetExhaustedError("tool_calls") 

46 self.calls += 1