Put an LLM bot in a Discord server and sooner or later one person talks to it all day and eats your whole API budget. Not even on purpose, pasting long messages is enough.
Here are two ways to cap each user per day.
1. Count inside the bot
The simplest version: compute cost from the token counts the API returns, and add it up per user ID.
from collections import defaultdict
from datetime import date
PRICE_IN = 0.15 / 1_000_000 # gpt-4o-mini input, per token (USD)
PRICE_OUT = 0.60 / 1_000_000 # output
LIMIT_USD = 0.50 # $0.50 per user per day
spent = defaultdict(float)
today = date.today()
async def ask(user_id: int, messages):
global today
if date.today() != today:
spent.clear(); today = date.today()
if spent[user_id] >= LIMIT_USD:
return "That's it for today, see you tomorrow!"
r = client.chat.completions.create(model="gpt-4o-mini", messages=messages, max_tokens=500)
spent[user_id] += r.usage.prompt_tokens * PRICE_IN + r.usage.completion_tokens * PRICE_OUT
return r.choices[0].message.content
It has holes though:
- it counts after the call, so a burst of parallel messages can all get through past the limit
- a restart wipes the numbers (you'd need a DB)
- the bot holds your real API key, so a bug or a leak spends it directly
For a small private server it's probably fine.
2. Cap per user in a proxy
What I do: the bot never gets the real key, it gets a capped proxy key. The proxy is Saifuban, I made it, it's open source.
Send the user ID in an x-saifuban-user header and each user gets their own daily cap:
client = OpenAI(base_url="https://saifuban.saifuban-app.workers.dev/proxy/openai/v1", api_key="sbk_...")
r = client.chat.completions.create(
model="gpt-4o-mini", messages=messages,
extra_headers={"x-saifuban-user": f"discord:{message.author.id}"},
)
- the worst-case cost is reserved before the call, so parallel messages can't slip past
- a user over their cap gets a
429, everyone else keeps going - there's a separate daily budget for the whole bot on top
- you can see who spent what
Over the cap you get openai.RateLimitError, so catch it and reply "that's it for today".
Short version
- small private server: counting in the bot is enough
- public bot strangers can use: put the per-user cap before the call
Either way, decide "how much per person per day" before you put the bot out there.
Top comments (0)