AI API Cost Tracker: Monitor Spend with Headers
You can build an ai api cost tracker in about fifty lines, because every response already tells you your remaining balance. This guide shows how to log spend per request, read the balance endpoints and raise an alert before credit runs out.


Key points
- Every response carries an X-Balance-USD header with your remaining credit.
- GET /v1/balance and the credit_grants endpoint return the balance on demand.
- Cost per call is (input x 0.15 + output x 0.50) / 1,000,000 dollars.
- Log to CSV, then alert when the balance drops under a threshold.
Where the numbers come from
Prepaid credit makes cost tracking simple, because the provider already keeps a running total. You get it in three places:
- The
X-Balance-USDresponse header on API calls, showing what is left after the request. GET /v1/balance, a plain balance lookup.GET /v1/dashboard/billing/credit_grants, the OpenAI-style route that tools such as dashboards and wrappers already know how to call.
Alongside those, each completion returns a usage object with prompt and completion token counts. Combine tokens with the prices ($0.15 per 1M input, $0.50 per 1M output) and you can compute the cost of any request yourself, then compare it with the drop in balance. The two should agree. If they do not, you have found something to investigate. Full parameter details are in the docs.
Read the header in one request
With curl, add -i and look at the headers:
curl -si https://api.uncensoredaiapis.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"uncensored","messages":[{"role":"user","content":"Say hi."}]}' \
| grep -i "x-balance-usd"
In Python, the OpenAI SDK exposes raw responses through with_raw_response, which gives you headers and the parsed object together:
from openai import OpenAI
client = OpenAI(base_url="https://api.uncensoredaiapis.com/v1", api_key="sk-your-key")
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "Say hi."}],
)
resp = raw.parse()
print(raw.headers.get("x-balance-usd"), resp.usage.total_tokens)A small logger that records every call
Wrap your calls in one function and write a CSV row each time. The row has the time, request ID, token counts, computed cost and balance.
import csv, time
from openai import OpenAI
client = OpenAI(base_url="https://api.uncensoredaiapis.com/v1", api_key="sk-your-key")
PRICE_IN, PRICE_OUT = 0.15, 0.50 # dollars per 1M tokens
LOG = "api_spend.csv"
def cost(usage):
return (usage.prompt_tokens * PRICE_IN + usage.completion_tokens * PRICE_OUT) / 1_000_000
def tracked_chat(messages, tag="default"):
raw = client.chat.completions.with_raw_response.create(
model="uncensored", messages=messages)
r = raw.parse()
row = [
time.strftime("%Y-%m-%d %H:%M:%S"),
raw.headers.get("x-request-id"),
tag,
r.usage.prompt_tokens,
r.usage.completion_tokens,
round(cost(r.usage), 6),
raw.headers.get("x-balance-usd"),
]
with open(LOG, "a", newline="") as f:
csv.writer(f).writerow(row)
return r, row
The tag argument is the trick that makes the log useful. Pass a feature name such as "summaries" or "chat", and later you can sum the cost by tag to see which part of the product spends the money. The request ID helps if you ever need to ask about a charge or report a problem, since it identifies the exact call.
Sanity-check the math
Take a call with 2,400 input tokens and 600 output tokens:
- Input: 2,400 x 0.15 / 1,000,000 = $0.00036
- Output: 600 x 0.50 / 1,000,000 = $0.00030
- Total: $0.00066
A thousand of those cost $0.66. If your CSV shows a balance falling much faster than the sum of the computed costs, check for retries that you did not log, background jobs using the same key, or streams you left open. Failed or refused requests are not charged, so errors should not move the balance at all. Compare totals over many calls, not single ones, so small rounding differences average out.
Streaming calls and usage
With stream: true, the usage numbers arrive at the end of the stream. Collect them from the final chunk, then log the row after the stream closes.
def tracked_stream(messages, tag="chat"):
usage = None
for chunk in client.chat.completions.create(
model="uncensored", messages=messages, stream=True):
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
usage = getattr(chunk, "usage", None) or usage
if usage:
with open(LOG, "a", newline="") as f:
csv.writer(f).writerow([time.strftime("%F %T"), "", tag,
usage.prompt_tokens, usage.completion_tokens, round(cost(usage), 6), ""])
If you only need the balance, call GET /v1/balance after the stream ends instead. It is a cheap request, and it works as a periodic check from a cron job too.
Summing spend by feature
The CSV is only useful if you read it. This short script totals cost by tag and shows the latest balance, with no extra packages.
import csv
from collections import defaultdict
totals, last_balance = defaultdict(float), None
with open("api_spend.csv") as f:
for row in csv.reader(f):
ts, req_id, tag, pin, pout, cost_usd, balance = row
totals[tag] += float(cost_usd)
last_balance = balance or last_balance
for tag, usd in sorted(totals.items(), key=lambda kv: -kv[1]):
print(f"{tag:15s} ${usd:.4f}")
print("latest balance:", last_balance)
Run it daily and paste the output into your team channel. Spend that was invisible becomes a number people can discuss, and a feature that costs ten times the others stands out at once. For a rough budget, multiply the daily total by 30 and add 20 percent of headroom.
Add a low-balance alert
Running out of credit mid-day takes a product offline, so alert early. A cron job that runs every 15 minutes is enough.
import requests
BASE = "https://api.uncensoredaiapis.com/v1"
THRESHOLD = 5.00 # dollars
r = requests.get(BASE + "/balance", headers={"Authorization": "Bearer sk-your-key"}, timeout=10)
print(r.status_code, r.text) # inspect the JSON once to see the field name
# After you know the field name, parse it and compare with THRESHOLD,
# then post to your chat webhook or send an email.
Print the raw JSON once and look at it before you write the parsing code. The real field name takes ten seconds to check, and guessing it from an article can break the alert silently. Pick a threshold that covers at least a day of normal spend, which the CSV tells you: sum yesterday's cost and use that as the minimum.
When the alert fires, top up. Any whole amount from $20 to $500 works, with +5% credit from $50, +10% from $100 and +15% from $200, and credit does not expire. To get a key for the tracker first, use the API key page.
Habits that keep spend predictable
- Use one key per environment so test traffic never hides in production numbers.
- Cap
max_tokenson endpoints where long answers are not needed. It is optional by default, so unbounded replies are possible. - Trim chat history. Input tokens are cheaper than output, but a long history repeated on every turn adds up.
- Review the weekly total by tag, and look for the one tag that is more than half the bill.
One more habit: store the request ID with every logged row. If a number looks wrong a month later, you can match it to a specific call instead of arguing from averages. Because failed requests are not billed, retries on errors do not add cost, but retries after a successful answer do, so make sure your retry logic only fires on real failures. A bug that resends a successful request in a loop is the most common cause of a surprise bill with any pay-per-token API.
More guides
Questions and answers
Does the balance header appear on every response?
The X-Balance-USD header is part of the response headers listed for this API. Read it from the raw response and treat a missing value as unknown.
Can I get cost without logging each request?
Yes. Poll GET /v1/balance on a schedule and compute the difference between readings.
Do failed requests change the balance?
No. Failed or refused requests are not charged.
Which endpoint should an existing OpenAI dashboard tool use?
Use the OpenAI-style GET /v1/dashboard/billing/credit_grants route, which many tools already support.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.