AiCredits
Billing Explained

Token Counting and Billing: How Providers Calculate What You Pay

Learn how token counting and billing really work: what counts as a token, why cache hits are cheaper, and runnable Python to audit your own API spend.

Published 2026-10-19 Updated 2026-10-19 7 min

Every surprising API invoice traces back to the same question: which tokens did the provider actually count? Most developers never look. They estimate with a characters-divided-by-four rule, compare that to the bill, shrug, and move on. That habit is expensive at scale and impossible to defend in a budget meeting.

Token counting and billing is not mysterious once you know the three moving parts: what the tokenizer produces, which of those tokens were served from cache, and how many the model generated back. Get those three numbers from the response itself instead of guessing, and your spend becomes a predictable input rather than a monthly surprise.

What actually counts as a token

A token is a chunk of text the tokenizer maps to an integer. It is not a word and it is not a character. Billing happens per token, and input and output are priced separately — output almost always costs more, because generating is the expensive direction of the computation.

The practical consequence is that two prompts of identical length can cost different amounts depending on what they contain. A short Chinese question, a block of minified JSON, and a paragraph of plain English can all be wildly different token counts.

  • English prose averages roughly four characters per token, but that rule collapses on Chinese, Japanese, Korean, emoji, and long hashed identifiers.

  • Code is token-dense: indentation, quotes, brackets, and punctuation each take their own slot. Minified payloads can genuinely be cheaper than pretty-printed ones.

  • Whitespace and newlines are tokens. A stray trailing newline repeated across a million requests is not free.

  • Chat requests carry template overhead — role markers and message separators the provider inserts around your content — which grows slightly with the number of messages you send.

The billing formula, minus the mystery

Nearly every provider computes the same shape: fresh input tokens at the input rate, cached input tokens at a reduced rate, and output tokens at the output rate, then sums them. The differences live in the details — how much of a prefix qualifies as cached, whether writing to the cache costs something extra, and whether retries are metered independently.

That last one catches people. If your client times out and you retry, the first attempt may still have been processed and counted. The fix is not to avoid retries; it is to log usage per attempt so you can see it happening.

Token typeWhat it coversHow it's billedMain lever
Fresh inputEvery prompt token not served from cache: system prompt, history, retrieved context, user messageAt the model's input rateTrim history, drop boilerplate, cache stable prefixes
Cached inputThe leading portion of the prompt that exactly matches an earlier requestAt a reduced input rate — cheaper than fresh inputKeep static text at the front and never edit it mid-prefix
OutputEverything the model generates in the completion, visible text plus any internal reasoning it emitsAt the output rate, which is higher than inputCap max_tokens, request terse formats, use the cheaper model tier
RetriesEach attempt is its own request with its own usageBilled separately; an attempt can be counted even if your client gave upFix timeouts before rerunning, and log usage per attempt

Read the usage object instead of guessing

Every chat completion returns a usage block. Log it on the first day of a project, not after the first invoice. The snippet below works as written against the AiCredits endpoint and prints the fields that matter, including the cache counters when the provider reports them.

import os
from openai import OpenAI

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

response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "Answer in one sentence."},
        {"role": "user", "content": "What is a token in an LLM?"},
    ],
    max_tokens=120,
)

u = response.usage
print("prompt_tokens:     ", u.prompt_tokens)
print("completion_tokens: ", u.completion_tokens)
print("total_tokens:      ", u.total_tokens)
print("cache_hit_tokens:  ", getattr(u, "prompt_cache_hit_tokens", "not reported"))
print("cache_miss_tokens: ", getattr(u, "prompt_cache_miss_tokens", "not reported"))
print(response.choices[0].message.content)

Cache hits are the cheapest tokens you can buy

Prompt caching matches an exact prefix. Only the leading, unchanged portion of your messages qualifies — the moment you alter a character inside that prefix, everything after it is billed as fresh input again.

This is why the single most common caching mistake is a timestamp or a request ID at the top of the system prompt. It looks harmless and it invalidates the cache on every single call. Put dynamic values at the end of the message list, never at the start.

import os
from openai import OpenAI

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

# Long, static reference text: policies, schemas, or few-shot examples live here.
knowledge = "\n".join(
    f"Rule {i}: confirm the order ID before issuing a refund." for i in range(300)
)
PREFIX = "You answer support questions using the rules below.\n" + knowledge


def ask(question: str) -> None:
    r = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[
            {"role": "system", "content": PREFIX},
            {"role": "user", "content": question},
        ],
        max_tokens=80,
    )
    u = r.usage
    print(question)
    print(
        "  prompt:", u.prompt_tokens,
        "cached:", getattr(u, "prompt_cache_hit_tokens", "n/a"),
        "output:", u.completion_tokens,
    )


ask("Can I refund order A-100?")
ask("Can I refund order A-101?")

Keep a token ledger, not a vibe

Aggregate dashboards hide the calls that hurt. A per-call ledger shows you which prompt template, which feature, and which customer is responsible for the spend — and it lets you enforce a hard token ceiling before a batch job runs away.

import csv
import os
from openai import OpenAI

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

TOKEN_BUDGET = 50_000  # stop the batch once this many tokens are spent
spent = 0
rows = []

questions = [
    "Explain a prompt cache hit in one sentence.",
    "List three ways to cut output tokens in a chat app.",
    "Why does a characters-per-token rule fail for Chinese text?",
]

for q in questions:
    if spent >= TOKEN_BUDGET:
        break
    r = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[{"role": "user", "content": q}],
        max_tokens=200,
    )
    u = r.usage
    spent += u.total_tokens
    rows.append({
        "question": q[:40],
        "prompt_tokens": u.prompt_tokens,
        "completion_tokens": u.completion_tokens,
        "total_tokens": u.total_tokens,
        "running_total": spent,
    })

if rows:
    with open("token_ledger.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        writer.writeheader()
        writer.writerows(rows)

print(f"spent {spent} tokens across {len(rows)} calls")

Four levers that move the bill without hurting quality

  • Cap max_tokens on every call. Output is the expensive direction, and an uncapped response on a runaway generation is the classic budget incident.

  • Front-load static text. System prompt and reference docs first, user input last, so the cacheable prefix stays byte-identical across requests.

  • Choose the model per task, not per project. deepseek-v4-flash handles classification, extraction, summarisation, and drafting well; reserve deepseek-v4-pro for genuinely hard reasoning where a wrong answer costs more than the tokens do.

  • Compress conversation history. Summarise or drop old turns instead of shipping the full transcript on every message — history is billed on every single request, forever.

How this maps onto AiCredits

AiCredits bills per token from prepaid credits, using the same input/cached-input/output split described above, for both deepseek-v4-flash and deepseek-v4-pro. Cache hits cost less than fresh input, off-peak usage costs less than peak, and pro costs more than flash — the exact rates live at aicreditsapi.com/pricing, and the usage block in each response tells you precisely what a call consumed.

Sign-up is card or PayPal, with no Chinese phone number or bank account required, so the billing relationship is as simple as the API surface. If you would rather spend your audit time on code than on prompts, the same account also covers AiCredits' linting tools.

FAQ

Are tokens the same as words?

No. A token is whatever chunk the tokenizer produces, which can be a whole common word, a word fragment, a single punctuation mark, or several characters in scripts the tokenizer handles densely. That is why counting words under-estimates code, JSON, and CJK text.

Does streaming change what I pay?

No. Streaming affects how fast you receive the response, not how many tokens the model generated. The usage block at the end of a streamed response reports the same accounting you would get from a non-streamed call.

Why did a retried request cost me tokens twice?

Because each attempt is a separate request. If the first attempt reached the provider and was processed before your client timed out, its usage was counted. Log usage per attempt so retries show up in your ledger instead of silently doubling a line item.

Can I count tokens before sending a request?

Roughly, yes — but exact counting requires the provider's own tokenizer, and third-party tokenizers from other vendors will be off. The reliable approach is to measure with the usage block on real requests and use that data to set max_tokens and history limits conservatively.

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 ×