How can I calculate how many tokens a given piece of text will use for LLM APIs and estimate the API cost per request?
Billing Formula & Key Takeaway:
To calculate token usage for a given text, execute a local Byte-Pair Encoding (BPE) tokenization pass using the model family's specific vocabulary: OpenAI uses o200k_base (for GPT-4o, GPT-4o mini, o1, o3) and cl100k_base (for GPT-4 and GPT-3.5); Anthropic uses Claude Byte BPE; and DeepSeek uses a 128k BPE vocabulary. To estimate the total cost per API request, use the standard billing formula:Total Cost = (Prompt Tokens × Input Rate / 1,000,000) + (Completion Tokens × Output Rate / 1,000,000) + (Cached Tokens × Cache Rate / 1,000,000)For pre-flight checks, use client-side WASM libraries (like gpt-tokenizer) to count tokens locally without API latency, and verify actual billable usage from the response.usage.prompt_tokens payload.
Encompasses system instructions, few-shot examples, injected web/document context, and user query. Billed at standard input rates ($2.50/M on GPT-4o, $0.27/M on DeepSeek).
Static prompts >1,024 tokens that repeat across requests qualify for prompt caching, slashing input costs by 75% to 90% (OpenAI charges $1.25/M; Anthropic charges 10% of base rate).
Generated response tokens are typically 3x to 4x more expensive per token ($10.00/M on GPT-4o, $1.10/M on DeepSeek) due to sequential autoregressive generation overhead.