AiCredits
Token Budgeting

DeepSeek API Token Counting: How to Estimate Costs Before You Ship

Count DeepSeek API tokens before you ship: build a preflight estimator, reconcile it against real usage, and cap output so no request surprises you.

Published 2026-10-02 Updated 2026-10-02 7 min

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?

MethodGood forWhere it driftsNeeds network
tiktoken (cl100k_base)English prose, mixed textCJK, dense JSON, minified codeNo
Character/CJK heuristicFast guards inside CIAnything dense or structuredNo
Response usage fieldGround truth per requestNothing — it is measuredYes
Replayed production logsCalibrating your estimatorPrompt shapes absent from the sampleNo

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

Do I need tiktoken to count DeepSeek tokens?

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.

How do I estimate output tokens before the call?

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.

Does prompt caching change what I count?

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.

Can I use deepseek-v4-pro in the same harness?

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.

Where do I find current pricing?

aicreditsapi.com/pricing lists current rates and off-peak windows. Store them in configuration so a rate change never requires a code deploy.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer 🔢Word Counter

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×