How to Set an AI API Spending Limit: Four Layers of Protection
Setting a spending limit on an AI API takes more than one switch. The safer approach has four layers: keep only a balance you can afford to lose in the account, set budgets and alerts in the console, give each project its own key, and add a cap in your own code. The entry points and capabilities of the first three layers differ by platform, so check the official docs. The fourth layer is entirely under your control, and it is your last line of defense.
One thing up front: on some platforms a "budget" is only an alert and does not necessarily hard-stop requests, and usage numbers can lag. "I set a budget, so I'm safe" is a common misconception.
How does an API account get drained overnight?
There are only a few common causes:
- A leaked key that someone else uses to flood requests.
- A script or agent stuck in a loop, calling repeatedly, with the context getting longer each time.
- Retry logic that is wrong and retries forever after failures.
- You meant to use a cheap model but actually called an expensive one, or forgot to cap output length.
The first two are handled by platform-side isolation and revocation. The last two are handled by limits in your code. The layers below cover each in turn.
Layer 1: the balance you fund is the most you can lose
If the platform supports prepaid billing (top up first, then spend), the balance itself is the hardest cap. When the balance runs out, requests fail instead of piling up debt. If your account is billed after use and settled at month end, you need the other layers even more.
Advice for beginners: top up a small amount first, get the workflow running, then adjust to your actual usage. Whether your platform is prepaid or postpaid is stated in its official billing documentation.
Layer 2: how do you set budgets and alerts in the console?
Most consoles have a "monthly budget," "usage alert," or similar feature. Names and locations change with redesigns, so this article doesn't give menu paths. Look in the official docs or the console for pages like billing, usage, or limits. When setting them, keep these points in mind:
- Set both a soft limit (alert) and a hard limit (if the platform offers one). Put the alert threshold at 50% to 80% of the hard limit so you have time to react.
- Use an alert email address you check every day, not an idle one you used at signup.
- Know that usage reporting is delayed. The numbers in the console may trail actual consumption, so don't set the limit exactly at the most you can bear.
- Anthropic and Chinese model platforms each have different entry points. For getting a key, see How to get a Claude API key: the official Anthropic Console flow. Limit settings follow each vendor's official docs. For OpenAI specifically, see our other article: How to set a spending limit and usage alerts on the OpenAI API. OpenAI's usage tiers also affect quotas and rate limits; see OpenAI API usage tiers explained and how to upgrade.
Layer 3: why use project-level key isolation?
With one key for the whole account, you can't tell which program is burning money when something goes wrong, and the only option is to revoke everything. A better approach:
- Use a separate key for each project and each environment (development, testing, production).
- If the platform supports project-level permissions or limits, set a cap per project. For OpenAI, see How to use OpenAI project API keys: permissions and limits per project.
- Keep keys only in environment variables or a secrets manager. Never commit them to a repository or paste them into a chat group.
- If you suspect a leak, revoke the key and check usage right away. The steps are in Your OpenAI API key leaked: revoke it, check usage, prevent a repeat.
Layer 4: add a cap in your code
You can't control the details of the platform's limits, but you can control your own code. Here is a minimal example built on three ideas: limit the length of each output, accumulate usage, and stop when the budget is exceeded.
import os
from openai import OpenAI
client = OpenAI() # The key is read from the environment
# The prices below are placeholders; fill them in from the model's official price page (CNY per million tokens)
PRICE_IN = float(os.environ.get("PRICE_IN", "0"))
PRICE_OUT = float(os.environ.get("PRICE_OUT", "0"))
BUDGET = 20.0 # Budget cap for this run (CNY)
spent = 0.0
def ask(messages, model):
global spent
if spent >= BUDGET:
raise RuntimeError(f"已达到预算上限 {BUDGET},停止调用")
resp = client.chat.completions.create(
model=model,
messages=messages,
max_tokens=1024, # Limit each output
)
u = resp.usage
spent += (u.prompt_tokens * PRICE_IN + u.completion_tokens * PRICE_OUT) / 1_000_000
return resp.choices[0].message.content
A few notes:
- The name of the
max_tokensparameter may differ across APIs and models. Follow the official docs for the API you use. - The returned
usagefield contains input and output token counts, which you can use to accumulate cost. For streaming calls, usage is obtained differently; follow the official docs. - Add a maximum number of rounds to any loop. For agent tasks, limit both the maximum number of steps and the maximum cumulative tokens.
- Retries need a cap on attempts and a backoff interval. Never retry forever. Also tell the causes of a 429 apart, insufficient quota versus rate limiting; see OpenAI 429 errors: telling insufficient_quota from rate_limit_exceeded and how to handle each.
How do you estimate a reasonable limit before setting it?
Estimate first, then set. Multiply (input tokens + output tokens per request) by the unit price, then by the expected number of requests, to get a baseline. Set the limit at 1.5 to 2 times the baseline. Agent tasks consume more erratically; see AI agent tasks burn a lot of tokens: how to estimate cost and pick a plan.
Pre-launch checklist
| Check | Done? |
|---|---|
| Account balance or credit line kept within what you can afford | |
| Budget and alerts set in the console, and someone reads the email | |
| A separate key for each project and each environment | |
| Keys do not appear in the repository, logs, or screenshots | |
| Code has max_tokens, a max step count, and a cumulative budget | |
| Retries have an attempt limit | |
| You know where to revoke a key if it leaks |
For more predictable costs, consider a subscription
The risk of pay-as-you-go billing is not knowing how much you will spend. If your usage is fairly steady, a subscription has a fixed monthly fee, and when the quota runs out you decide whether to buy more, so there is much less variance. To choose between the two, see AI API subscription or pay-as-you-go? Work it out with your own usage.
AGI Plan is cdnping's commercial partner. AGI Plan is a multi-provider LLM aggregation gateway sold as a monthly subscription, billed in RMB, with no overseas credit card needed. One subscription works across several capability groups, such as frontier reasoning, balanced general-purpose, Chinese flagship models, and fast lightweight models. Tools like Claude Code and Codex connect by changing a single endpoint URL. To be clear, the service itself states that it is not an officially authorized channel, and some models are marked "overseas only." See the models page for specifics. Plan prices are on the pricing page, and setup steps are in the quick start.
Whichever provider you use, the four layers above apply, especially the cap in your code.
Two more useful tools
Price or model changes directly affect your budget. Site changes tracks additions and removals on vendors' pricing pages and changelogs, and Model watch tracks models being listed, delisted, or repriced.
Next steps
- Do two things today: split your existing keys by project, and turn on usage alerts in the console.
- Add the code-level cap above to the script you run most often, starting with a small budget.
- After a week, compare against actual usage in the console and adjust the limits.
- If this is your first time with APIs, read What is an AI API: a one-page explainer for beginners first.