AI API Key Management for Teams and Bots
AI API key management is mostly bookkeeping: know where each key lives, who uses it, what it may spend and how to swap it. This guide gives you a working setup for a small team or a fleet of bots, with code that only needs the base URL changed.
Updated

Decide who owns a key and what it is for
Management starts before any code. Write a short table with one row per application: the name, the owner, where the key is stored, the expected daily spend and the date of the last rotation. A spreadsheet is enough. The rows force the question that causes most problems later, which is who is allowed to change this.
A few rules keep the table honest. A key belongs to a service, not to a person's laptop. Developers get access through the secret store, not by being sent the string in chat. When someone leaves the team, every key they could read goes on the rotation list. Whether you can hold several keys on one account depends on your account, so look at the API key page before you design around multiple keys, and ask support if you need a second one for a staging environment.
Understand what a key actually limits
The key is also the unit of limits. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. All bots that share a key share those numbers, so three busy bots can starve each other without any of them doing anything wrong.
The two error codes tell you which limit you hit. rate_limited means too many requests per minute. concurrency means too many at once. Both come back as HTTP 429. Temporary overload also returns 429, with a Retry-After: 5 header. Streaming matters here: a streamed request holds its concurrency slot until the stream ends, so a slow reader that never closes the connection quietly eats one of your eight slots.
Plan the budget of slots like you plan memory. For three bots on one key, a semaphore of 2 each uses 6 slots and leaves 2 for ad hoc scripts and the test console. The same arithmetic works for requests per minute: 300 divided between three bots is 100 each, or 5 requests every 3 seconds.
Store keys in one place and load them in one place
Pick a single store. For a small team that can be the secret manager of your host or CI system, with one variable per service. Name variables by purpose, for example STORYBOT_API_KEY and MODERATION_BOT_API_KEY, so a leaked name tells nobody which account it belongs to and a grep tells you which code uses which.
In code, load the key in exactly one module. Every other file imports a configured client from that module. This gives you a single place to add retries, logging and spend tracking, and a single line to change when a key moves.
# llm.py
import os
import threading
import time
from openai import OpenAI, RateLimitError # re-exported for callers
BASE_URL = "https://api.grokunrestricted.cc/v1"
MODEL = "uncensored"
IN_RATE, OUT_RATE = 0.15, 0.50 # dollars per 1M tokens
class Budget:
def __init__(self, daily_cap):
self.cap = daily_cap
self.spent = 0.0
self.day = time.strftime("%Y-%m-%d")
self.lock = threading.Lock()
def add(self, prompt_tokens, completion_tokens):
cost = prompt_tokens * IN_RATE / 1e6 + completion_tokens * OUT_RATE / 1e6
with self.lock:
today = time.strftime("%Y-%m-%d")
if today == self.day:
pass
else:
self.day, self.spent = today, 0.0
self.spent += cost
return cost
def ok(self):
return self.spent < self.cap
def make_bot(env_name, daily_cap, slots):
key = os.environ[env_name]
client = OpenAI(base_url=BASE_URL, api_key=key)
return client, Budget(daily_cap), threading.BoundedSemaphore(slots)Add spend caps you control
The service is prepaid, so your account balance is a hard ceiling, but it is a shared one. A bug in one bot can drain the credit meant for the others. A cap in the wrapper stops that bot first.
Pick the cap from real numbers. A bot that sends 1,000 requests a day at 1,500 input and 400 output tokens spends 1.5M x $0.15 + 0.4M x $0.50 = $0.225 + $0.20 = $0.425 per day. A cap of $1.00 gives it more than double the normal load before it stops, and a runaway loop is cut off after about a day of normal traffic. Set the cap per bot, log when it trips, and make the message go to a human.
Here is the call path that uses the module above, with a retry that respects Retry-After.
import time
from llm import make_bot, RateLimitError
client, budget, slots = make_bot("STORYBOT_API_KEY", daily_cap=1.00, slots=2)
def ask(messages, **kw):
if not budget.ok():
raise RuntimeError("daily cap reached")
for attempt in range(4):
with slots:
try:
r = client.chat.completions.create(
model="uncensored", messages=messages, **kw
)
budget.add(r.usage.prompt_tokens, r.usage.completion_tokens)
return r
except RateLimitError:
pass
time.sleep(5 * (attempt + 1))
raise RuntimeError("still rate limited after retries")
r = ask([{"role": "user", "content": "Give me three plot hooks for a harbor town mystery."}])
print(r.choices[0].message.content)
The semaphore is released before the sleep, so waiting bots do not hold a slot. Failed or refused requests are not charged, so failed attempts do not move the spend counter.
Streaming, tools and JSON mode through the same wrapper
Features should go through the wrapper too, so the budget sees them. The endpoint supports streaming over SSE, tool calling and JSON mode with the usual parameters. For streams, usage arrives at the end of the stream, so add it to the budget when the last chunk shows it.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write two sentences about rain."}],
stream=True,
)
with slots:
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
if getattr(chunk, "usage", None):
budget.add(chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
# JSON mode
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[{"role": "user", "content": "Return JSON with keys name and mood for a tavern keeper."}],
)
print(r.choices[0].message.content)
Tool calling follows the standard shape: pass tools and tool_choice, read tool_calls from the reply, run the function, and send the result back as a message with role: "tool". Each of those round trips is a separate request, billed on its own tokens, so count them in the cap. The docs show the request format for all three features.
Rotate keys without downtime
Rotate on a schedule, for example every 90 days, and immediately after a suspected leak or a team change. The order of operations matters more than the frequency.
- Obtain the new key and store it under a new variable name next to the old one.
- Deploy code that reads the new variable, one service at a time.
- Watch the logs for a successful call and a fresh
X-Request-Idfrom each service. - Retire the old key and delete its variable. If you need it disabled on the provider side, ask support.
- Update the row in your table with the date.
Never revoke before the new key is live everywhere. The most common outage in rotations is a forgotten cron job or a worker on a different host still holding the old string. A grep across your repositories and deployment configs for the old variable name finds these before they find you.
Monitor the balance and plan top-ups
Each response includes X-Balance-USD. Read it in the wrapper and push it to wherever you keep metrics. Alert when it drops below seven days of average spend, not at zero, because crypto top-ups need time to confirm. Funding runs in any whole amount from $20 to $500, paid in USDT on TRC20 or USDC on Base, with 5 percent extra from $50, 10 percent from $100 and 15 percent from $200.
For three bots at $0.425 per day each, total spend is $1.275 per day, so a $100 top-up, which arrives as $110, lasts about 86 days. Details of the bonus tiers are on the pricing page. If a key stops working or returns unexpected errors, the troubleshooting page lists the usual causes.
More guides
Questions and answers
How often should I rotate an AI API key?
A reasonable default is every 90 days, plus immediately after a leak, a contractor leaving or any staff change that gave someone access. Frequency matters less than a cutover order that never leaves production without a working key.
Can several bots share one key?
Yes, but they share one pool of 8 concurrent requests and 300 requests per minute on a full key. Give each bot a semaphore and a spend cap so one cannot starve or drain the others.
How do I set a spending limit?
Compute cost from the usage block in each response using $0.15 per 1M input and $0.50 per 1M output tokens, and stop the bot at a daily cap you choose. The prepaid balance is the final ceiling.
What is the difference between rate_limited and concurrency errors?
Both are HTTP 429. The code rate_limited means too many requests per minute, while concurrency means too many requests were in flight at the same moment.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Get API key