Why Token Counting Belongs Before the Ship, Not After
Every DeepSeek call has two halves: an input you control completely and an output you can only bound. Most teams discover this after launch, when a support bot's system prompt plus twenty turns of history gets resent on every single request. By then the prompt is in production and nobody wants to touch it.
Preflight token counting fixes that. Estimate the input locally, cap the output explicitly, then reconcile both against the usage block the API returns with every response. You end up with a number you can budget against rather than a guess you defend in a retro.
What Actually Counts Toward a DeepSeek Call
System prompt — resent on every call, so it is usually the largest recurring line item. A few hundred tokens of instruction is a few hundred tokens multiplied by every request you will ever make.
Conversation history — each turn resends the whole thread. A twenty-turn chat re-embeds nineteen old turns the user has already read.
Few-shot examples — valuable while you are stabilising an output format, dead weight once the schema holds reliably.
Tool and function schemas — counted as input on every request, even when no tool is ever invoked.
Retrieved context — in RAG, the number of chunks is your real cost dial, not chunk length. Four tight chunks often beat one long one.
max_tokens — the only hard ceiling on generation. Leave it unset or enormous and you have no upper bound at all.
Step 1 — A Token Estimator That Never Breaks Your Build
Save this as token_estimator.py. tiktoken is optional: if the import fails, the code falls back to a character heuristic that counts CJK characters separately, because Chinese, Japanese, and Korean text produce far more tokens per character than English. If you ship internationally, that fallback is not a nicety — it is the difference between an estimate and a fantasy.
try:
import tiktoken
_ENC = tiktoken.get_encoding('cl100k_base')
except ImportError:
_ENC = None
def count_tokens(text: str) -> int:
"""Best-effort count: exact for tiktoken, approximate otherwise."""
if _ENC is not None:
return len(_ENC.encode(text))
cjk = sum(1 for ch in text if '\u4e00' <= ch <= '\u9fff')
return cjk + max(1, round((len(text) - cjk) / 4))
def count_messages(messages: list) -> int:
total = 0
for message in messages:
total += count_tokens(str(message.get('content') or '')) + 4
return total + 2
tiktoken does not ship DeepSeek's tokenizer, so treat its counts as directional. For plain English it lands close; for CJK, dense JSON, and minified code it drifts. That is exactly why the reconciliation step exists.
Step 2 — Preflight, Call, Reconcile
import json
import os
from openai import OpenAI
from token_estimator import count_messages
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
LEDGER = []
def ask(messages, max_output_tokens=512, token_budget=20000):
estimated_input = count_messages(messages)
worst_case = estimated_input + max_output_tokens
if worst_case > token_budget:
raise ValueError(
f'Preflight blocked: {worst_case} tokens > {token_budget} budget'
)
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages,
max_tokens=max_output_tokens,
)
usage = response.model_dump().get('usage') or {}
LEDGER.append({
'estimated_input': estimated_input,
'prompt_tokens': usage.get('prompt_tokens'),
'completion_tokens': usage.get('completion_tokens'),
'cache_hit_tokens': usage.get('prompt_cache_hit_tokens'),
'cache_miss_tokens': usage.get('prompt_cache_miss_tokens'),
})
return response.choices[0].message.content
if __name__ == '__main__':
reply = ask([{'role': 'user', 'content': 'Give me three uses for a token ledger.'}])
print(reply)
print(json.dumps(LEDGER[-1], indent=2))
The guard raises before the request leaves your process, so an oversized prompt becomes an exception in a log rather than a surprise on a statement. The ledger row stores your estimate beside the truth the API returns. The cache fields are optional — if they are not reported for a given request, they come back as None — so read them defensively rather than assuming their shape.
After a few hundred real requests, compute the median ratio of prompt_tokens to estimated_input for each prompt family and language, then fold that correction factor into count_messages. A rough estimator that self-corrects beats an accurate one nobody ever calibrates.
Your average request does not set your budget. Your worst request does.
Step 3 — Rank Your Worst-Case Requests Before Launch
from token_estimator import count_messages
PROMPTS = [
'Explain idempotency keys to a junior developer in one paragraph.',
'Rewrite this changelog entry for a non-technical audience: <paste here>.',
'Summarise this support thread into a reproducible bug report: <paste here>.',
]
def build_messages(prompt: str):
return [
{'role': 'system', 'content': 'You are a concise technical assistant.'},
{'role': 'user', 'content': prompt},
]
def estimate_batch(prompts, builder, max_output_tokens=512):
rows = []
for prompt in prompts:
estimated_input = count_messages(builder(prompt))
rows.append({
'prompt': prompt[:48],
'estimated_input': estimated_input,
'worst_case_total': estimated_input + max_output_tokens,
})
return sorted(rows, key=lambda r: r['worst_case_total'], reverse=True)
for row in estimate_batch(PROMPTS, build_messages, max_output_tokens=400)[:10]:
print(row)
Run your real templates through this once, before launch, and read the top of the list. Those requests set your headroom: the long RAG prompt, the one with six few-shot examples, the batch job that fans out to ten thousand rows. Trim there first — a token removed from the top of the list is worth more than a token removed from the middle.
How Accurate Is Each Estimation Method?
| Method | Good for | Where it drifts | Needs network |
|---|---|---|---|
| tiktoken (cl100k_base) | English prose, mixed text | CJK, dense JSON, minified code | No |
| Character/CJK heuristic | Fast guards inside CI | Anything dense or structured | No |
| Response usage field | Ground truth per request | Nothing — it is measured | Yes |
| Replayed production logs | Calibrating your estimator | Prompt shapes absent from the sample | No |
Use two of them, always: a local estimator for preflight and the response usage field for truth. If your local estimator is the only source of truth, you are budgeting with fiction.
Three Levers That Lower the Bill Without Lowering Quality
Cap output from data. Once you have a week of traffic, set max_tokens near the high percentile of observed completion_tokens instead of leaving a large default. You lose nothing except runaway generations.
Keep the prompt prefix byte-stable. When the system prompt, tool schemas, and few-shot block sit at the front and never change between calls, repeated traffic can hit the prompt cache. The same tokens cost less on a hit than on a miss.
Move non-interactive work off-peak. Backfills, nightly enrichment, and evaluation runs do not need peak capacity, and off-peak requests cost less — so schedule them there.
Why This Discipline Pays Off With Prepaid Credits
AiCredits sells DeepSeek API access as prepaid credits you top up with a card or PayPal — no Chinese phone number or bank account required — and every response carries the same usage fields this article reconciles against. That alignment is the point: the numbers you preflight are the numbers your balance moves on, so a runaway loop shows up as a visible dip rather than an invoice three weeks later.
Grab a key, save the estimator as token_estimator.py, and wire the guard into whichever service makes the first call. Ten lines now is cheaper than explaining a spike later. Current rates and off-peak windows live at aicreditsapi.com/pricing — keep them in config, never hardcoded.
FAQ
No, and it would not be exact anyway — tiktoken does not ship DeepSeek's tokenizer. The estimator falls back to a character heuristic with separate CJK handling if the import fails, and the response usage field is what you reconcile against.
You cannot know them in advance, so bound them instead. Set max_tokens explicitly, then once you have real traffic tighten the cap toward the high percentile of your observed completion_tokens rather than leaving a generous default.
The tokens are still counted; a cache hit simply costs less than a miss. Log prompt_cache_hit_tokens and prompt_cache_miss_tokens separately to see the split, and keep the system prompt and tool schemas byte-stable at the front of the request so hits are even possible.
Yes. Swap the model string in the call and keep the rest identical. Pro costs more than flash, so the same token budget translates into a larger spend — the preflight guard is what keeps that from surprising you.
aicreditsapi.com/pricing lists current rates and off-peak windows. Store them in configuration so a rate change never requires a code deploy.