Track Cumulative Agent Dollar Budget Cap

Basics
BasicsGuardrailsCost ControlOpenAIAnthropicGoogle

Problem

Given a list of sequential LLM call costs (in USD) and a hard cap max_usd, implement apply_budget_cap(costs, max_usd) that approves calls in order, stops immediately before the first call that would push cumulative spend above max_usd, and returns (num_approved_calls, total_spent).

Why It Matters: Dollar circuit breakers are mandatory in production agent harnesses to guarantee a runaway loop can never exceed per-session cost limits.

Function Signature

def apply_budget_cap(costs: list[float], max_usd: float) -> tuple[int, float]:
    """Approve sequential costs until the next call would exceed max_usd."""

Sample Input & Output

Example 1: Stops Before Exceeding Cap

Input:

costs = [0.10, 0.25, 0.20, 0.05], max_usd = 0.40

Expected Output:

(2, 0.35)

Explanation: Calls 1 and 2 total $0.35 <= $0.40; call 3 would reach $0.55 > $0.40, so execution halts at 2 calls.

Example 2: First Call Exceeds Cap & Exact Cap Hit

Input:

apply_budget_cap([0.50, 0.10], 0.25)  |  apply_budget_cap([0.10, 0.20], 0.30)

Expected Output:

(0, 0.0)  |  (2, 0.3)

Explanation: Stops immediately at 0 if even the first call exceeds budget; handles floating-point rounding (0.1 + 0.2 ≈ 0.3) cleanly.

Constraints & Edge Cases

  • Return (approved_count, total_spent).
  • Use a small floating-point tolerance (spent + c > max_usd + 1e-9) so 0.1 + 0.2 doesn't falsely exceed 0.3.
  • Stop at the first over-budget call—do not skip ahead to smaller later calls.

Constraints & Evaluation Criteria

  • Return `(approved_count, total_spent)`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[0.10, 0.12, 0.05], cap=0.25
Expected Output / Criteria
(2, 0.22)