Guide · Agents
How to stop an AI agent loop from running up your API bill
Agents call models in a loop, and each step usually sends the whole growing context again. A bug that stops the loop from ending, or a retry storm against a failing tool, keeps spending until something stops it. Here are the guardrails that stop it.
Guardrails in code
- Cap the steps. Every agent loop needs a maximum number of iterations and a wall-clock timeout. Fail loudly when it hits either.
- Cap the output. Set
max_tokenson every call. An unbounded response on an expensive model is the easiest way to burn money. - Watch the context size. Cost grows with every step that resends the history. Summarize or trim old turns, and log tokens per step so you can see the curve.
- Back off on errors. Retries with exponential backoff and a retry limit. A tool that fails instantly in a tight loop turns into thousands of calls.
- Separate keys per workload. Give batch jobs and agents their own key or project. Then usage by key shows which one went wrong, and you can revoke it alone.
One alert outside the code
Guardrails only cover the code paths you thought about. A provider-side check covers everything that spends money on the account, including the cron job someone forgot, a teammate's experiment and a leaked key. Two layers work well together:
- The provider's own spend limit as a hard ceiling.
- A same-day anomaly alert ("today is 3× your normal day") so you hear about it long before the ceiling.
billshock does the second part. It runs hourly in GitHub Actions, reads daily costs from the OpenAI, Anthropic, Vercel and Cursor billing APIs, and posts to Slack or Discord when a day spikes or the month is on pace to exceed your budget. It only reads cost data; it never blocks requests.
npx billshock init creates the config and an hourly GitHub Actions workflow. Free and open source. Prefer a hosted version? Join the waitlist.