AiCredits
Cost Control

Token Counting: Estimating API Costs Before You Make the Call

Learn how to count tokens and estimate DeepSeek API costs before sending a request, with runnable Python code and practical budgeting tips for developers.

Published 2026-11-17 Updated 2026-11-17 9 min

Why preflight token counting pays off

API pricing is metered by tokens, not requests. A single call with a long prompt and a generous output cap can cost many times more than a short one, and agent loops multiply that risk. Counting tokens before the call turns a surprise invoice into a budget decision.

A preflight estimate is not about predicting the bill to the cent. It is about catching the call that is ten or a hundred times more expensive than you intended before it runs. That matters most for batch jobs, recursive agents, and any feature where users can paste arbitrary text.

DeepSeek-v4-flash is the fast default for most workloads; deepseek-v4-pro costs more and is worth reserving for harder reasoning. Cache hits and off-peak usage cost less. Current rates are at aicreditsapi.com/pricing — plug those rates into your own estimator instead of hardcoding them.

What actually gets counted

Every message is serialized into tokens: the role, the content, and a small amount of framing. The model's reply is billed as output tokens even when you stream it. For planning, count both sides.

The same visible text can produce different token counts in different models. A prompt that fits comfortably in one model's context window may be tight in another. Counting also helps you avoid context-window errors, not just cost surprises.

  • Code, JSON, and whitespace-heavy text tokenize less efficiently than plain English.

  • Non-English text often uses more tokens per character; test with representative samples.

  • Long system prompts and tool schemas are easy to forget because they are not user-visible.

  • Output length is the biggest uncertainty; set max_tokens as a hard ceiling.

A runnable token counter

The snippet below uses tiktoken as a fast approximation. It is not DeepSeek's exact tokenizer, so treat the result as a planning estimate and reconcile it with the usage block returned by the API.

# pip install tiktoken
import os
import tiktoken

ENC = tiktoken.get_encoding('cl100k_base')  # approximation, not DeepSeek's exact tokenizer

def count_text_tokens(text: str) -> int:
    return len(ENC.encode(text or ''))

def count_message_tokens(messages: list[dict]) -> int:
    total = 0
    for m in messages:
        total += count_text_tokens(m.get('role', ''))
        content = m.get('content', '')
        if isinstance(content, str):
            total += count_text_tokens(content)
        elif isinstance(content, list):
            for part in content:
                if isinstance(part, dict) and part.get('type') == 'text':
                    total += count_text_tokens(part.get('text', ''))
    overhead = int(os.getenv('MESSAGE_FRAMING_OVERHEAD', '0'))
    return total + overhead * len(messages)

if __name__ == '__main__':
    messages = [
        {'role': 'system', 'content': 'You are a concise code reviewer.'},
        {'role': 'user', 'content': '''Find the bug:

def last_item(xs):
    return xs[len(xs)]'''},
    ]
    print('Estimated input tokens:', count_message_tokens(messages))

A budget guard around the real call

Convert the token estimate to money with the current rates from aicreditsapi.com/pricing. Store rates in environment variables so your code does not go stale. The guard below refuses to call the API if the worst-case estimate exceeds your per-call budget.

import os
import tiktoken
from openai import OpenAI

ENC = tiktoken.get_encoding('cl100k_base')

def count_text_tokens(text: str) -> int:
    return len(ENC.encode(text or ''))

def count_message_tokens(messages: list[dict]) -> int:
    total = 0
    for m in messages:
        total += count_text_tokens(m.get('role', ''))
        content = m.get('content', '')
        if isinstance(content, str):
            total += count_text_tokens(content)
        elif isinstance(content, list):
            for part in content:
                if isinstance(part, dict) and part.get('type') == 'text':
                    total += count_text_tokens(part.get('text', ''))
    overhead = int(os.getenv('MESSAGE_FRAMING_OVERHEAD', '0'))
    return total + overhead * len(messages)

client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
)

def estimate_cost(input_tokens: int, max_output_tokens: int) -> float:
    in_rate = float(os.environ['PRICE_INPUT_PER_MILLION'])
    out_rate = float(os.environ['PRICE_OUTPUT_PER_MILLION'])
    return (input_tokens / 1_000_000) * in_rate + (max_output_tokens / 1_000_000) * out_rate

def guarded_chat(messages: list[dict], max_output_tokens: int, budget: float) -> str:
    input_tokens = count_message_tokens(messages)
    worst_case = estimate_cost(input_tokens, max_output_tokens)
    if worst_case > budget:
        raise RuntimeError(
            f'Estimated worst-case cost {worst_case:.6f} exceeds budget {budget:.6f}'
        )
    resp = client.chat.completions.create(
        model='deepseek-v4-flash',
        messages=messages,
        max_tokens=max_output_tokens,
        temperature=0.2,
    )
    u = resp.usage
    print(f'usage: prompt={u.prompt_tokens} completion={u.completion_tokens} total={u.total_tokens}')
    return resp.choices[0].message.content

if __name__ == '__main__':
    budget = float(os.environ['MAX_CALL_BUDGET'])
    reply = guarded_chat(
        [{'role': 'user', 'content': 'Say hello in one short sentence.'}],
        max_output_tokens=50,
        budget=budget,
    )
    print(reply)

Bounding output without guesswork

Output tokens are harder to predict because the model decides when to stop. Make the ceiling explicit: set max_tokens, use stop sequences where appropriate, and ask for structured formats that make length predictable. For planning, log actual completion tokens from usage and use a high percentile (for example, the 90th) as your assumption.

If you cannot set max_tokens because the task needs long output, split it into stages. Summarize or extract first, then generate. Each stage has its own bounded output, which makes the total estimate far more reliable.

  • Set max_tokens on every production call.

  • Use stop sequences for extractive tasks that end at a delimiter.

  • Log usage.prompt_tokens and usage.completion_tokens to build your own estimates.

  • For batch jobs, estimate the full batch and compare it against a daily budget before starting.

Where estimates drift

Use more than one method. A fast character heuristic can gate UI warnings, while a tokenizer-based estimate can gate actual API calls. The max_tokens ceiling remains your final safety net.

MethodStrengthWeaknessBest use
Provider tokenizer or usage blockClosest to exactStill provider-specific; often only available after the callReconciliation and high-volume planning
tiktoken approximationFast and easyDrifts on non-English text, code, and JSONPreflight sanity checks
Character heuristicInstantVery rough; language-sensitiveUI counters and alerts
max_tokens ceilingGuarantees an upper boundCan overestimate short repliesBudget guards

Estimate with the tokenizer, cap with max_tokens, reconcile with usage.

A practical preflight checklist

Run this checklist for every new endpoint or prompt template. It takes a few minutes and prevents most cost surprises.

  • Count input tokens including the system prompt and any tool schemas.

  • Set max_tokens to your worst acceptable output.

  • Convert to cost using current rates from aicreditsapi.com/pricing.

  • Refuse or downsize the call if the estimate exceeds your budget.

  • Reconcile with the usage block after the call and update your estimator.

  • Use deepseek-v4-flash by default; reserve deepseek-v4-pro for cases where quality matters more than cost.

FAQ

Can I get an exact token count before calling the API?

Not reliably across providers. Use the closest tokenizer you have for an estimate, then reconcile with the usage block returned by the API. Exact pre-call counting is possible only when the provider publishes a matching tokenizer.

Does DeepSeek use the same tokenizer as OpenAI?

Tokenizers differ by provider and model family, so tiktoken is an approximation. Treat differences as a reason to leave headroom in your budget, not as a reason to skip estimation.

How do I estimate cost for streaming responses?

Streaming does not change the token count. Count the input, set max_tokens for the output ceiling, and use the final usage block if the API returns one. If usage is not available during streaming, log it from a non-streaming test call and use that as your baseline.

Why is my estimate consistently off?

Common causes are message framing overhead, non-English text, code or JSON payloads, and tokenizer version differences. Compare your estimate with actual usage over a sample of real requests and adjust a single correction factor.

Where do I find current DeepSeek rates?

See aicreditsapi.com/pricing for current rates. AiCredits also returns usage on each response, so you can reconcile estimates with actuals and refine your preflight checks. International developers can pay by card or PayPal without a Chinese phone or bank account.

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 ×