AiCredits
Billing Audit

AI API Billing Transparency: Questions Every Developer Should Ask

Eight questions that reveal how an AI API actually bills — token counting, cache hits, failed requests, spend caps — plus scripts to audit your own usage.

Published 2026-10-08 Updated 2026-10-08 8 min

The per-token rate is the least useful number you can ask for

Most teams open a vendor conversation with "what does it cost per million tokens?" and stop there. That number is easy to publish and hard to act on, because it tells you nothing about which tokens get counted, which requests get billed, or what happens when your retry helper fires at 2 a.m.

A better framing: billing transparency is an observability problem. A transparent provider gives you answers you can verify against your own logs — the same requests, the same counts, the same timestamps. Here are the questions worth asking before you route production traffic, with runnable scripts so you can test the answers yourself.

Question 1: Which tokens are actually on the meter?

Ask for four numbers separately: input tokens, output tokens, cached input tokens, and any internal or reasoning tokens. Stronger models can spend invisible compute before producing an answer; if those tokens bill as output, your invoice will exceed what the visible answer suggests. Get a written answer on whether they are counted, excluded, or counted at a different rate.

Also ask about the floor: a per-request minimum hurts short calls — health checks, classification, routing — far more than long ones.

You can measure cache behaviour yourself in about thirty seconds. Send a long, identical system prefix twice and compare the cached token count reported on the second call.

import os
from openai import OpenAI

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

MODEL = "deepseek-v4-flash"

# A long, stable prefix. Repetition makes the cache effect obvious.
SYSTEM = "You are a terse API assistant. Answer in one sentence.\n" * 60


def probe(label):
    resp = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": "Name one HTTP status code for a rate limit."},
        ],
    )
    u = resp.usage
    details = getattr(u, "prompt_tokens_details", None)
    cached = getattr(details, "cached_tokens", 0) if details is not None else 0
    print(f"{label} prompt={u.prompt_tokens} output={u.completion_tokens} cached_prompt={cached}")


probe("first call: ")
probe("second call:")

If the second call shows a cached token count going up, the provider is caching and passing the benefit on. If both calls look identical, assume no cache discount will ever reach your invoice — size your prompts accordingly.

Question 2: What happens when a request fails?

This is where invoices diverge most from expectations. A flaky upstream, a client timeout, a dropped stream, a retry wrapper that fires three times — all of these can generate billed tokens for output nobody read.

  • Are 5xx responses billed? What about 429 rate-limit responses?

  • If I retry a failed request, do I pay for the first attempt?

  • Is a stream that dies mid-response billed for partial output, or for the whole max_tokens reservation?

  • Does cancelling client-side stop billing server-side?

  • Do provider-side errors get automatic reconciliation, or do I have to open a ticket?

Ask for one example invoice line where a failure was excluded. Vendors with real metering can produce it on the spot.

Question 3: Can I reconcile your meter against my logs?

The test of transparency is not a dashboard screenshot. It is whether you can export per-request usage and match it to your own records. Log every call, then compare totals. Small rounding differences are normal; the same prompt producing wildly different counts is not.

import json
import os
from openai import OpenAI

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

MODEL = "deepseek-v4-flash"
LOG = "usage_log.jsonl"


def rough_tokens(text):
    """Deliberately naive: ~4 characters per token. Only used to spot big gaps."""
    return max(1, len(text) // 4)


def ask(prompt):
    resp = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "user", "content": prompt}],
    )
    u = resp.usage
    answer = resp.choices[0].message.content or ""
    record = {
        "prompt": prompt,
        "prompt_tokens": u.prompt_tokens,
        "completion_tokens": u.completion_tokens,
        "total_tokens": u.total_tokens,
        "local_estimate": rough_tokens(prompt) + rough_tokens(answer),
    }
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(json.dumps(record) + "\n")
    return record


for p in ["List three HTTP methods.", "What does status code 429 mean?"]:
    ask(p)

totals = {"prompt_tokens": 0, "completion_tokens": 0, "local_estimate": 0}
with open(LOG, encoding="utf-8") as f:
    for line in f:
        row = json.loads(line)
        for key in totals:
            totals[key] += row[key]

print(totals)

Run this for a day and you own a baseline that survives a provider migration, a model swap, or a pricing change. It also catches the day someone edits a system prompt and quietly kills your cache hit rate.

Question 4: What controls exist before the invoice arrives?

Ask what you can do to stop a runaway agent loop without waiting on support.

ControlQuestion to askRed flag
Hard spend capCan I set a monthly cap per key that blocks requests, not just emails me?Alerts with no enforcement
Per-key attributionDoes usage break down by key, project and end user?One account-wide counter
Failure billingAre 5xx responses and client timeouts billed?Silence, or "contact support"
Cache termsHow long do cached prefixes live, and what invalidates them?Cache pricing you cannot measure
Cheaper lanesIs off-peak or batch pricing automatic or opt-in?Discounts mentioned only in marketing posts
Export granularityCan I pull per-request usage as JSON or CSV?Monthly PDF invoice only

Question 5: Is the published rate the rate you actually pay?

Discounts expire, off-peak lanes appear and vanish, and old blog posts describing last year's promotion keep ranking for years. Treat any rate you read outside the provider's own pricing page as a rumour.

Ask the boring details: do credits expire, is there a minimum top-up, which currencies can you pay in, and is off-peak or batch pricing automatic? The direction is stable — off-peak costs less than peak, cache hits cost less than fresh input, and a pro tier costs more than a flash tier — but the ratios move, so check current rates at aicreditsapi.com/pricing instead of trusting a number quoted in an article.

For developers outside China, payment rails matter as much as rates. AiCredits sells DeepSeek credits you can buy with a normal card or PayPal — no Chinese phone number, no Chinese bank account — on an OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1, which means the scripts above run unchanged.

Bonus: make streaming usage visible

Streaming hides token counts unless you explicitly request them. OpenAI-compatible gateways that support include_usage return a final chunk carrying the usage block; the code below falls back cleanly if yours does not.

import os
from openai import OpenAI

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

MODEL = "deepseek-v4-flash"


def stream_answer(prompt):
    kwargs = {
        "model": MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "stream": True,
    }
    try:
        stream = client.chat.completions.create(
            **kwargs, stream_options={"include_usage": True}
        )
    except Exception:
        # Gateway does not support stream_options; fall back to text only.
        stream = client.chat.completions.create(**kwargs)

    parts, usage = [], None
    for chunk in stream:
        if getattr(chunk, "usage", None) is not None:
            usage = chunk.usage
        choices = getattr(chunk, "choices", None) or []
        if choices and choices[0].delta and choices[0].delta.content:
            parts.append(choices[0].delta.content)
    return "".join(parts), usage


text, usage = stream_answer("Explain token accounting in two sentences.")
print(text)
if usage is None:
    print("No usage block returned. Bill from your own logs instead.")
else:
    print("prompt:", usage.prompt_tokens, "output:", usage.completion_tokens)

The 15-minute audit

  • Send the five questions to your provider and store the answers next to your model config in the repo.

  • Run the cache probe against your real system prompt and record the cached token count.

  • Log one day of traffic with the reconciliation script; keep the JSONL.

  • Set a hard spend cap per key if one exists. If it only alerts, add a client-side guard.

  • Pin model names explicitly — deepseek-v4-flash as the default, deepseek-v4-pro for tasks that fail your quality bar — instead of letting defaults drift underneath you.

  • Re-check the pricing page whenever you change models, cache strategy, or retry policy.

FAQ

Do failed requests really get billed?

It depends on the provider, which is exactly why you ask. Many bill only completed generations, but unlogged retries are the usual culprit — instrument the retry loop before blaming the vendor.

What is cached input and why should I care?

A stable prefix reused across calls — system prompt, tool definitions, few-shot examples — can bill at a lower rate than fresh input. Keep that block identical across requests to maximise hits.

Is DeepSeek cheaper than OpenAI or Claude?

Rate cards differ and change. The comparison that survives is cost per completed task on your own workload, measured with the logging script above rather than a quoted per-token figure.

Which model should I default to?

Use deepseek-v4-flash for nearly everything and escalate to deepseek-v4-pro only where output fails your checks. Route the escalation per task, not per application.

Where can I see current AiCredits rates?

aicreditsapi.com/pricing lists current rates. Credits are pay-as-you-go, purchasable with a card or PayPal.

Try Lint in 2 seconds

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

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

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

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

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