Managing LLM API Limits and Budgets
Summary
Configuring protection against overspending and exceeding limits when working with paid LLM APIs: rate limiting, monitoring, and automatic alerts.
1. Defining Provider Limits
Before starting, I fix the limitations of a specific API. Each provider has its own parameters: requests per minute (RPM), tokens per minute (TPM), and daily maximum requests. These values are specified in the documentation or in the personal account.
| Provider | RPM | TPM | Daily Limit |
|---|---|---|---|
| Provider A | 60 | 100 000 | 1 000 000 tokens |
| Provider B | 120 | 200 000 | 5 000 000 tokens |
2. Implementing Rate Limiting on the Client Side
I use the ratelimit library in Python to limit the frequency of requests.
from ratelimit import limits, sleep_and_retry
import requests
@sleep_and_retry
@limits(calls=50, period=60)
def call_llm_api(prompt):
response = requests.post(
"https://api.example.com/v1/chat/completions",
json={"model": "model-name", "messages": [{"role": "user", "content": prompt}]},
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
return response.json()
3. Monitoring Expenses
I create a script that logs each request and calculates the cost based on the tariff.
import json
from datetime import datetime
cost_per_1k_tokens = 0.002 # example tariff
def log_request(model, prompt_tokens, completion_tokens):
cost = (prompt_tokens + completion_tokens) / 1000 * cost_per_1k_tokens
entry = {
"timestamp": datetime.utcnow().isoformat(),
"model": model,
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"cost": cost
}
with open("llm_usage.log", "a") as f:
f.write(json.dumps(entry) + "\n")
return cost
4. Automatic Budget Control
Before each request, I check the current daily expense and stop execution if the threshold is exceeded.
import os
DAILY_BUDGET = float(os.getenv("DAILY_BUDGET", "10.0"))
def get_daily_cost():
today = datetime.utcnow().date().isoformat()
total = 0.0
with open("llm_usage.log", "r") as f:
for line in f:
entry = json.loads(line)
if entry["timestamp"].startswith(today):
total += entry["cost"]
return total
def check_budget():
if get_daily_cost() >= DAILY_BUDGET:
raise RuntimeError("Daily budget exceeded")
5. Setting Up Alerts
I use a Telegram bot for notifications about exceeding thresholds.
import requests
def send_alert(message):
bot_token = os.getenv("TELEGRAM_BOT_TOKEN")
chat_id = os.getenv("TELEGRAM_CHAT_ID")
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
requests.post(url, json={"chat_id": chat_id, "text": message})
# In the request processing loop
if get_daily_cost() > DAILY_BUDGET * 0.8:
send_alert(f"Expense reached 80% of daily budget: {get_daily_cost():.2f} USD")
6. Handling Errors 429 and 429
When API limits are exceeded, it returns a code 429. I implement exponential backoff and retries.
import time
import random
def call_with_retry(prompt, max_retries=5):
for attempt in range(max_retries):
try:
return call_llm_api(prompt)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
wait = 2 ** attempt + random.uniform(0, 1)
time.sleep(wait)
else:
raise
raise RuntimeError("Max retries exceeded")
7. Caching Repeated Requests
To reduce expenses, I cache responses to identical requests. More details on caching strategies in the post about LLM caching.
import hashlib
import redis
cache = redis.Redis(host="localhost", port=6379, db=0)
def get_cached_response(prompt):
key = hashlib.sha256(prompt.encode()).hexdigest()
cached = cache.get(key)
if cached:
return json.loads(cached)
response = call_with_retry(prompt)
cache.setex(key, 3600, json.dumps(response))
return response
8. Final Diagram
graph TD
A[Request] --> B{Budget Check}
B -->|Exceeded| C[Reject + alert]
B -->|OK| D{Cache Check}
D -->|Yes| E[Response from cache]
D -->|No| F[Rate limiter]
F --> G[API call]
G --> H[Expense logging]
H --> I[Response]
After implementing this scheme, API expenses became predictable, and exceeding limits no longer led to emergency stops. Additionally, I recommend studying API protection from abuse and provider fallback configuration.