Enforce token and dollar budgets on an agent run

MediumAgentsPro

Why it matters Agent platforms cap per-task spend so a confused agent cannot burn the budget.

Long agent runs need hard limits on tokens and spend.

Write budget_guard(steps, max_tokens, max_usd, price_in, price_out). steps is a list of (input_tokens, output_tokens). Prices are dollars per million tokens. Process steps in order, adding each step's tokens and cost. Return (steps_allowed, tokens_used, usd_used) where a step is allowed only if after adding it neither limit is exceeded; stop at the first step that would exceed a limit (do not count it).

Signaturedef budget_guard(steps, max_tokens, max_usd, price_in, price_out)

Example

budget_guard([(1000, 100), (1000, 100)], 1500, 10, 3, 15) allows 1 step with 1100 tokens and 0.0045 dollars.

Understand the idea

Long agent runs can quietly spend a lot of tokens and money. A budget guard adds up each step's tokens and cost and stops before a step that would break either limit. The check happens with the candidate step included, and a step that would exceed a limit is not counted. Worked example: steps [(2000, 500), (3000, 1000), (1000, 200)], max_tokens 10000, max_usd 0.02, price_in 3 and price_out 15 dollars per million tokens. Step 1: 2500 tokens; cost 2000 * 3 / 1e6 + 500 * 15 / 1e6 = 0.006 + 0.0075 = 0.0135. Step 2: tokens would be 6500, within limit, but its cost 0.009 + 0.015 = 0.024 would bring the total to 0.0375, over 0.02, so stop. Result (1, 2500, 0.0135). Step 3 is never reached, even though it is small. Rule: for each step, cost = in * price_in / 1e6 + out * price_out / 1e6; if tokens_used + in + out > max_tokens or usd_used + cost > max_usd, stop; else add and count the step. Check both limits. Used in: cost controls for autonomous agents and batch LLM jobs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplebudget_guard([(1000, 100), (1000, 100)], 1500, 10, 3, 15)
  • Sample 2: dollar limitbudget_guard([(100000, 20000)] * 5, 10 ** 7, 1.0, 3, 15)