The Complete Guide to AI Token Counting and Cost Optimization
Token counting is the foundation of AI cost management, but the details vary by modality. Learn how to measure, predict, and reduce token usage across text, embeddings, images, and audio.
Every AI request has a price tag, and that price tag is calculated in tokens. But token counting is not always intuitive: an image and a paragraph of text may cost dramatically different amounts, a cached prompt costs nothing, and a single malformed tool call can double your bill. Understanding how tokens are counted is the first step toward controlling inference costs.
What counts as a token?
A token is roughly four characters of text in English, or about three-quarters of a word. But tokenization is model-specific: the same sentence can produce a different token count on GPT, Claude, and Gemini.
Beyond text, providers bill for tokens in ways you might not expect. Images are split into patches and each patch costs a fixed number of tokens. Audio is transcribed into text and then tokenized. Embeddings are charged per input token, with no output cost.
note: Tokenization is not universal
Never assume that a token count from one provider applies to another. When comparing costs, normalize by your actual input and output patterns.
How providers bill by modality
Different modalities have different pricing models, and the cheapest option on one provider may be the most expensive on another. Here is how the major formats compare:
- Text (input/output): Token-per-token pricing. The most predictable modality, and the one most tools track.
- Embeddings: Input tokens only, no output charges. Typically cheaper per token than chat, making it attractive for batch processing.
- Images (generation): Fixed cost per image, sometimes with additional charges for high-resolution outputs.
- Images (understanding/vision): Token cost proportional to the number of image patches. A single high-res image can cost as much as a long document.
- Audio: Transcription and synthesis are billed per minute, not per token, with rates that vary dramatically.
The token waterfall of a real request
Every request passes through several cost stages before the final bill is calculated. Understanding this flow helps identify where savings are possible.
start(API request received)
parse:Parse request body
count:Count input tokens
check:Prompt in cache?
cache:Cache hit - free input
cache_no:Cache miss - billed input
generate:Generate output tokens
count2:Count output tokens
cache_out:Check for completion cache
end(Bill calculated)
start -> parse
parse -> count
count -> check
check(yes) -> cache -> generate
check(no) -> cache_no -> generate
generate -> count2
count2 -> cache_out -> endStrategies to reduce token usage
Token optimization is not just about shorter prompts. The most effective strategies address the entire request lifecycle: pre-processing, prompting, generation, and post-processing.
- Truncate context aggressively: Remove or summarize historical messages beyond the context window you actually need. Most conversations only rely on the last few exchanges.
- Use system prompt caching: When your system prompt is static, cache it so it is not re-tokenized on every request.
- Compress with summaries: Instead of passing full conversation history, pass a concise summary generated from earlier turns.
- Limit max_tokens: Set explicit upper bounds on output length. For classification or extraction tasks, 64 tokens is usually sufficient.
- Batch embeddings: Send multiple documents in a single embedding request to amortize API overhead.
tip: The 80/20 rule of token waste
In most applications, 80% of token spend comes from 20% of the conversation history. Focus your optimization efforts on the longest context windows first.
Measuring effective token cost
List price per token is not the same as cost per token. Failed requests still consume input tokens. Retries multiply the total. Cache hits cost nothing. The true cost is what you pay divided by what you successfully receive.
// Calculate effective cost per successful request
function effectiveCost(totalSpent, successfulTokens, failedAttempts) {
const effectiveTokenCount = successfulTokens * (1 + failedAttempts);
return totalSpent / effectiveTokenCount;
}
const cost = effectiveCost(
0.15, // total dollars spent
50000, // tokens in successful responses
0.2 // 20% of requests failed and were retried
); // $0.000003 per effective tokenToken budgeting by workload type
Different workloads have different token economics. Here is how to budget for each type:
start(Application type)
cond:Is this chat?
cond:Is this batch?
cond:Is this vision?
cond:Is this embedding?
chat:Use sliding window
batch:Use async, larger batches
vision:Compress images, fewer patches
embedding:Batch in groups
end(Set token budget)
start -> cond
cond(chat) -> chat -> end
cond(batch) -> batch -> end
cond(vision) -> vision -> end
cond(embedding) -> embedding -> endTools for token estimation
You do not need to guess. Several tools can estimate or measure token counts before you send a request to the provider:
- tiktoken (OpenAI): The official tokenizer library for GPT models. Supports batch encoding and custom tokenizers.
- Anthropic token counting API: An endpoint that returns exact token counts for a given prompt without generating output.
- Gemini tokenizer: Google provides a tokenizer endpoint for Gemini models with the same capabilities.
- Cisoma usage logs: Every request is logged with exact input and output token counts, giving you ground truth for cost analysis.
caution: Estimates are not guarantees
Token estimation libraries produce approximate counts. Only the provider knows the exact number used for billing.
A token budgeting framework
Instead of trying to minimize every token, set a budget and design your application around it. Allocate tokens by importance: system context, user query, conversation history, and output length. When you approach the budget, truncate or summarize rather than extending indefinitely.
- Set a per-request token budget. Decide on a maximum number of input and output tokens for your workload.
- Profile your current usage. Measure how many tokens your existing requests actually consume.
- Identify waste patterns. Find the request types that exceed the budget and determine the cause.
- Implement truncation. Add logic to truncate or summarize context when approaching the budget limit.
- Monitor and iterate. Track budget adherence in your logs and adjust the budget as your application evolves.