Billing · Troubleshooting

Calculate AI API costs: Tikway token billing and error troubleshooting

Last updated:

Normalize billing units before comparing AI API prices, then recalculate using actual usage. This guide covers ordinary text costs, batch budgets, cache categories, 429 errors and failed streams across three protocols. The companion calculator performs local arithmetic only: it reads no key and sends no API requests.

1. Compare prices in the same unit

Use the free web cost calculator to choose a text model and enter input tokens, output tokens and request count. No account is needed to calculate or share a scenario. It estimates base text costs; caching, multimodal charges and account rules need separate checks.

Open the model in the catalog and check input/output prices, currency, billing unit and applicable extras. Per-thousand tokens, per-million tokens, per-image and per-second video prices are not directly comparable.

For one currency, 0.002 per thousand tokens = 2 per million tokens. For different currencies, specify an exchange rate and date; the calculator does not convert currencies.

Tokens are not characters. Input can include system instructions and conversation history, and output usage may include more than visible answer text. Estimate with a suitable tokenizer; check settlement against actual usage and account records.

2. Estimate a single request and a batch

All prices and usage in this section are hypothetical examples, not live Tikway quotes or actual call records. Suppose input costs USD 2 per million tokens and output USD 10 per million. One request uses 1,000 input and 500 output tokens:

text
Input cost = 1,000 / 1,000,000 × 2  = 0.002 USD
Output cost =   500 / 1,000,000 × 10 = 0.005 USD
Total per request = 0.007 USD
1,000 requests with identical usage = 7 USD

The companion calculator uses Python 3.10 or newer and only the standard library. Run in its directory:

bash
python token-cost.py --input-tokens 1000 --output-tokens 500 --input-price 2 --output-price 10 --requests 1000

The default price unit is 1,000,000 tokens. This estimates 0.007 per request and 7 for the batch, possibly displayed with trailing decimal zeros. Results use your input currency and do not automatically add taxes, exchange conversion or other charges.

For per-thousand prices, specify the unit:

bash
python token-cost.py --input-tokens 1000 --output-tokens 500 --input-price 0.002 --output-price 0.010 --price-unit-tokens 1000 --requests 1000

Both commands give the same estimate. Normalize currency and token units first. Request count and unit must be positive integers; token usage must be nonnegative integers and prices finite nonnegative numbers. --requests assumes identical usage repeated; real batches with varying lengths need individual calculations or a representative distribution.

3. Understand protocol-specific usage fields

Protocol Common fields Checks for recalculation
OpenAI Chat Completions usage.prompt_tokens, usage.completion_tokens Cache and reasoning details may already be included in totals; avoid adding them twice.
Anthropic Messages usage.input_tokens, usage.output_tokens cache_read_input_tokens and cache_creation_input_tokens may be separate and use different prices.
Gemini generateContent usageMetadata.promptTokenCount, candidatesTokenCount, totalTokenCount cachedContentTokenCount and thoughtsTokenCount may also be present; visible text is not all billable usage.

These are common fields, not a guarantee that every model returns every statistic. Cache counts can be part of totals or separate categories. Match the protocol’s definitions to bill items. Do not treat only visible Gemini candidate text as all output usage or multiply totalTokenCount by the input rate unconditionally.

4. Split cache costs without double counting

For another hypothetical example, regular input costs 2 per million tokens, cache reads 0.2 and output 10. The request contains 1,000 regular input + 3,000 cache-read + 500 output tokens, with no cache writes or extras:

text
Regular input = 1,000 / 1,000,000 × 2   = 0.002
Cache reads = 3,000 / 1,000,000 × 0.2 = 0.0006
Output   =   500 / 1,000,000 × 10  = 0.005
Total = 0.0076 (same currency)

The 4,000 total input tokens have already been split; do not bill another 4,000 as regular input. The companion calculator handles ordinary input/output only, so calculate cache categories separately and combine them.

Cache write/read charges and lifetimes depend on current model rules. Images may be priced per image or token, and video by duration and resolution. The text formula does not cover every multimodal task.

5. Record useful errors and distinguish 429 causes

Save HTTP status, protocol, model ID, time, error fields and x-request-id, when present. Remove keys, private prompts and user content before sharing.

OpenAI/Anthropic-style errors may use string error.code or error.type. Gemini commonly uses numeric error.code and string error.status; handle the relevant structure.

Result Response
Authentication failure / invalid_api_key Check key validity, whitespace and protocol headers.
Unsupported model or parameter Exact ID, protocol and parameter support; remove unnecessary optional fields first.
429 + insufficient_balance Check balance and charges; waiting or repeating calls usually cannot fix low balance.
429 + requests_per_minute_exceeded Reduce concurrency/frequency and follow account and response limits.
Gemini 429 + RESOURCE_EXHAUSTED Check message, balance and usage rate together; this status does not distinguish causes on its own.
Timeout or 5xx Inspect request ID, records and error details before choosing bounded retries.
Error after streamed text Keep partial output and errors, and mark the task incomplete. HTTP success is insufficient.

The strings identify common gateway errors; also read the actual message and error documentation, currently in Chinese. Do not retry authentication, parameter or balance errors indefinitely.

A client timeout does not prove the server did no work. Check request records before sending the same task again, and do not assume every failed request is unbilled.

6. Compare budgets with task quality

Use fixed task samples and record model, usage, completion and cost. Compare task success, truncation, average cost and longer answers; the shortest example can underestimate production usage.

Try reducing irrelevant history and repeated instructions, and set supported output limits. Recheck quality and parameter support after a model change; lower prices do not establish equivalent results.

Continue with coding model selection, model and billing verification and 401 troubleshooting.