Why token monitoring fails quietly
Token usage is the one production metric that stays invisible until someone asks a question you can't answer. Latency shows up in your APM. Errors show up in your logs. But a prompt that grew by a few hundred tokens per call looks like nothing — until it is multiplied by every request the feature serves, every day, forever.
The fix is not a dashboard. It is a small amount of code that captures the usage object the API already returns, stores it next to the feature that produced it, and makes it queryable. This post builds that in five steps, in order, with code you can paste and run today against deepseek-v4-flash through the AiCredits OpenAI-compatible endpoint.
Step 1 — Read the usage object on every call
Every non-streaming chat completion returns a usage object next to the content. Print it once for any new endpoint you integrate, because the exact set of fields varies between providers and can grow over time — then stop printing it and start storing it.
import os, json
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
resp = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[{'role': 'user', 'content': 'Summarize the CAP theorem in two sentences.'}],
)
usage = resp.usage
raw = usage.model_dump() if hasattr(usage, 'model_dump') else usage.to_dict()
print(json.dumps(raw, indent=2))
print('prompt tokens: ', usage.prompt_tokens)
print('completion tokens:', usage.completion_tokens)
print('total tokens: ', usage.total_tokens)
Step 2 — Log every call, not every day
Daily totals tell you that consumption went up. They never tell you why. One row per API call does, and SQLite is enough to hold it for a long time before you need anything else.
The critical design decision is the tag: a short, human-readable feature name chosen at the call site, like 'commit-message-bot' or 'doc-summarizer'. The person who writes the prompt should name it, because they are the only one who knows what it belongs to.
import os, json, sqlite3, time
from contextlib import closing
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
DB = 'usage.db'
def init_db(path=DB):
with closing(sqlite3.connect(path)) as con:
con.execute('''
CREATE TABLE IF NOT EXISTS calls (
ts REAL, model TEXT, tag TEXT,
prompt_tokens INTEGER, completion_tokens INTEGER,
total_tokens INTEGER, raw_usage TEXT
)
''')
con.commit()
def tracked_chat(messages, model='deepseek-v4-flash', tag='default', **kwargs):
resp = client.chat.completions.create(model=model, messages=messages, **kwargs)
u = resp.usage
if u is not None:
raw = u.model_dump() if hasattr(u, 'model_dump') else u.to_dict()
with closing(sqlite3.connect(DB)) as con:
con.execute(
'INSERT INTO calls VALUES (?,?,?,?,?,?,?)',
(time.time(), model, tag, u.prompt_tokens,
u.completion_tokens, u.total_tokens, json.dumps(raw)),
)
con.commit()
return resp
init_db()
reply = tracked_chat(
[{'role': 'user', 'content': 'Draft a one-line commit message for a caching fix.'}],
tag='commit-message-bot',
)
print(reply.choices[0].message.content)
Log the raw usage JSON for every call, including fields you do not read today. Usage objects grow, and history beats a migration.
Never store prompt or completion text in the same table. Usage logs get copied into tickets and notebooks; prompts contain user data.
Write the row in the request path, right after the response returns. A background queue is an optimisation, not a starting point.
Tag at the call site, not in a central config. Config tags drift the moment a feature is renamed.
| Field | Why you log it |
|---|---|
| ts | Correlate token spikes with deploys and traffic instead of guessing |
| tag | The feature name — the column that actually finds waste |
| model | Detects silent drift between flash and pro |
| prompt_tokens | Catches prompt bloat and cache-prefix invalidation |
| completion_tokens | Catches runaway generation and a missing max_tokens |
| total_tokens | The number your budget check runs on |
| raw_usage | Provider-specific fields you do not know you need yet |
Step 3 — Streaming calls hide their usage
Streaming is where most token monitoring quietly disappears, because the usage object is not attached to the chunks you are already reading. Ask for a final usage chunk explicitly, and treat a missing one as a signal rather than an error.
stream = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[{'role': 'user', 'content': 'Write a three-line poem about cache hits.'}],
stream=True,
stream_options={'include_usage': True},
)
text, usage = [], None
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
text.append(chunk.choices[0].delta.content)
if getattr(chunk, 'usage', None) is not None:
usage = chunk.usage
print(''.join(text))
print('usage chunk:', usage) # None means no usage was emitted
If your provider does not emit a usage chunk, estimate from the characters streamed and mark the row as an estimate in the tag. Rough estimates are fine for alerting. They are not fine for billing a customer, so never mix the two silently.
Step 4 — Report by feature, not by calendar
Grouping by tag and model answers the two questions that come up in every review: which feature is consuming the most, and is anything quietly running on the more expensive model? Run this after a deploy and the answer is already waiting.
import sqlite3, time
from contextlib import closing
def report(days=7, db='usage.db'):
cutoff = time.time() - days * 86400
with closing(sqlite3.connect(db)) as con:
rows = con.execute('''
SELECT tag, model, COUNT(*), SUM(prompt_tokens),
SUM(completion_tokens), SUM(total_tokens)
FROM calls
WHERE ts >= ?
GROUP BY tag, model
ORDER BY SUM(total_tokens) DESC
''', (cutoff,)).fetchall()
print('{:<22}{:<20}{:>7}{:>11}{:>11}{:>11}'.format(
'feature', 'model', 'calls', 'prompt', 'completion', 'total'))
for tag, model, calls, pt, ct, tt in rows:
print('{:<22}{:<20}{:>7}{:>11}{:>11}{:>11}'.format(
tag, model, calls, pt, ct, tt))
return rows
Step 5 — Give the app a budget it can enforce
A budget expressed in currency goes stale the moment rates change, and rates are not something you should hardcode anyway. A budget expressed in tokens per tagged feature does not go stale, is easy to reason about, and gives you a real circuit breaker on a runaway loop.
import sqlite3
from contextlib import closing
def budget_check(tag='commit-message-bot', limit_tokens=500_000, db='usage.db'):
with closing(sqlite3.connect(db)) as con:
used = con.execute(
'SELECT COALESCE(SUM(total_tokens), 0) FROM calls WHERE tag = ?',
(tag,),
).fetchone()[0]
print('{}: {} / {} tokens used'.format(tag, used, limit_tokens))
if used >= limit_tokens:
raise RuntimeError('token budget exhausted for {}'.format(tag))
if used >= 0.8 * limit_tokens:
print('warning: {} is above 80% of its token budget'.format(tag))
return used
Set the limit per feature, not per account. A global limit tells you nothing about which feature to fix.
Warn before you hard-stop. A circuit breaker that fires with no warning turns a cost problem into an outage.
Reset the window explicitly (daily or rolling) and log which one you chose. Ambiguous windows cause false alarms.
Review limits quarterly. A limit nobody has hit in months is either protecting a dead feature or set far too high.
Four failure modes this catches
| Symptom | Likely cause | Fix |
|---|---|---|
| Prompt tokens climb week over week | Few-shot examples and system prompt growing, unversioned | Version prompts in git and diff them in CI |
| Completion tokens spike after a deploy | Missing max_tokens, or a looser output instruction | Set max_tokens and tighten the output spec |
| Total tokens high, traffic flat | Retry loop on rate limits or 5xx responses | Cap retries, add jittered backoff, log retry counts |
| Pro share of tokens creeping up | A fallback or default model changed somewhere | Pin the model per feature and assert it in a test |
Pricing, caching, and why you should not hardcode rates
Three things move your consumption in ways the request count never shows. First, model tier: deepseek-v4-flash is the fast default and costs less, while deepseek-v4-pro costs more and should be reserved for calls that genuinely need it. Second, cache hits: a stable prompt prefix — system instructions and reference material first, variable content last — is cheaper than an uncached one, and reordering those blocks turns cheap tokens into expensive ones. Third, timing: off-peak requests cost less than peak ones.
None of those are numbers you should paste into your codebase, because rates change and stale constants are worse than no constants. Keep your instrumentation in tokens, and check aicreditsapi.com/pricing for current rates when you need to translate.
The practical consequence for monitoring is simple: log the raw usage JSON even when a field looks irrelevant. When cache-related accounting shows up in a response, you want the history to already be there rather than starting fresh.
Store tokens, not currency. Tokens are a fact about your workload; prices are a fact about someone else's pricing page.
Frequently asked questions
For non-streaming calls, yes — every completion includes a usage object with prompt, completion, and total token counts. For streaming, request a final usage chunk and handle the case where none arrives; estimates are acceptable for alerting, never for billing.
A rough heuristic such as characters divided by four is good enough to reject an obviously oversized prompt client-side, but it is not accurate enough for accounting. Log the real usage from the response and keep the heuristic as a guard rail only.
Caching rewards a stable prefix. If you rewrite the system prompt or reorder the blocks, previously cached prefix tokens become misses and cost more. Logging prompt tokens per prompt version shows this immediately instead of leaving you to guess.
Not at the start. SQLite plus a scheduled report answers most questions about per-feature usage. Reach for a hosted tool when you need cross-service tracing or long retention, not before.
Check your AiCredits account for account-level consumption, and aicreditsapi.com/pricing for current rates. The code above is about per-call instrumentation inside your own app, which an account view cannot give you.
Where this leaves you
None of this needs a vendor or a new service. It needs one table, one wrapper function, and the discipline to tag calls where they are written. Do that, and 'how much did the new summarizer cost us this week?' becomes a query instead of a meeting.
AiCredits is built for exactly this workflow: deepseek-v4-flash and deepseek-v4-pro behind an OpenAI-compatible endpoint, payable by card or PayPal with no Chinese phone number or bank account needed, so international teams can instrument their own usage without a procurement detour. Start with the wrapper, keep your budgets in tokens, and check aicreditsapi.com/pricing before you translate anything into currency.