Are you tired of guessing prompt sizes with character math, only to hit unexpected API limit crashes in production?
Counting words with .split() fails badly on JSON payloads, source code, and non-English user messages. As explained in our complete LLM tokenization guide, measuring exact tokens locally before sending a network call prevents billing surprises and failed requests.
The good news is that checking exact token counts takes only five lines of Python. In this step-by-step tutorial, we will walk you through counting tokens using OpenAI tiktoken plus provider APIs (Method 1), and counting offline for open-weight models using Hugging Face transformers (Method 2).
Executive Summary
- Zero API Spend: Counting tokens locally with
tiktokenruns strictly on your CPU in microseconds without sending data over the internet. - Chat Message Overhead: Counting raw text misses hidden chat wrapper tokens (
role, message delimiters) added around every user and system turn. - Multi-Provider Support: Use
tiktokenfor OpenAI models, native freecount_tokenscalls for Gemini and Claude, andAutoTokenizerfor Llama or Qwen. - Pre-Flight Guardrails: Checking token totals before calling an LLM lets you truncate old chat turns cleanly instead of crashing.
Table of Contents
- Executive Summary
- Token Counting Tools by Model Family
- Method 1: Counting Tokens With Tiktoken and Native SDKs (Recommended)
- Method 2: Offline Token Counting for Open-Weight Models
- Common Troubleshooting Questions & How to Fix Them
- Frequently Asked Questions
- Final Thoughts & Next Steps
- Primary Sources & References
Token Counting Tools by Model Family
| Model Ecosystem | Recommended Python Tool | Runs Offline? | Tracks Chat Template Overhead? | Cost per Check |
|---|---|---|---|---|
| OpenAI (GPT-4o, o-series) | tiktoken (o200k_base) | Yes (100% local) | Yes (with 3-token turn wrapper) | Free |
| Google Gemini Models | google-genai count_tokens | No (lightweight API call) | Yes (exact server count) | Free |
| Anthropic Claude Models | anthropic messages.count_tokens | No (lightweight API call) | Yes (includes tools and images) | Free |
| Llama, Qwen, Mistral | transformers AutoTokenizer | Yes (downloads vocab once) | Yes (via apply_chat_template) | Free |
Method 1: Counting Tokens With Tiktoken and Native SDKs (Recommended)
For OpenAI models, tiktoken is the fastest local BPE tokenizer available in Python. Let us set it up properly so your counter accounts for full chat message arrays, not just plain strings.
Step 1: Install Tiktoken in Your Environment
First, open your terminal and install the official tiktoken package using pip.
pip install tiktokenStep 2: Load the Encoding and Count Single Strings
Next, load the model-specific encoding via encoding_for_model (or o200k_base directly for newer GPT families) and encode your prompt string into token IDs.
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
prompt_text = "Summarize this 10-page invoice into clean YAML fields."
token_ids = enc.encode(prompt_text)
print(f"Token count: {len(token_ids)}")Step 3: Count Full Chat Message Arrays Accurately
When calling chat completion endpoints, providers wrap every message dictionary in special start and stop tokens. Include those per-message overhead tokens in your helper function so your budget never drifts.
def count_chat_tokens(messages: list, model: str = "gpt-4o") -> int:
enc = tiktoken.encoding_for_model(model)
total = 3 # Every reply is primed with assistant header tokens
for msg in messages:
total += 3 # Per-message wrapper overhead
for key, value in msg.items():
total += len(enc.encode(str(value)))
if key == "name":
total += 1
return totalStep 4: Count Tokens for Gemini and Claude Free Endpoints
If your app routes calls to Gemini or Claude, avoid using OpenAI tiktoken as an estimate because their vocabularies differ significantly. Instead, call their built-in free counting methods.
# Google Gemini exact token check (free endpoint)
from google import genai
client = genai.Client()
resp = client.models.count_tokens(model="gemini-2.5-flash", contents="Count these exact tokens.")
print("Gemini tokens:", resp.total_tokens)Pro Tip: Before running your prompt through an expensive production pipeline, trim redundant filler words using our free client-side TeckScaler Prompt Optimizer to reduce input token length immediately.
Method 2: Offline Token Counting for Open-Weight Models
If you host open-weight models like Llama, Mistral, or Qwen locally, use Hugging Face AutoTokenizer with apply_chat_template so your local counts match vLLM or Ollama runtime behavior identically.
Step 1: Install Hugging Face Transformers
First, install transformers (or standalone tokenizers if you want a minimal dependency footprint without PyTorch).
pip install transformersStep 2: Load Model Tokenizer and Format Chat Turns
Next, download the tiny tokenizer.json configuration for your target model once, then pass your chat message list through apply_chat_template(tokenize=True).
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
messages = [
{"role": "system", "content": "Be brief and accurate."},
{"role": "user", "content": "Explain BPE tokenization in two sentences."}
]
token_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True)
print("Exact local tokens:", len(token_ids))Common Troubleshooting Questions & How to Fix Them
Even with clean scripts, developers run into a few common tokenizer snags in Python:
- Error:
KeyError: 'Could not automatically mapin' tiktoken. Older versions oftiktokenmay not recognize brand-new model aliases. Upgradetiktokenviapip install -U tiktoken, or fall back cleanly withtiktoken.get_encoding("o200k_base"). - Issue:
tiktokencrashes on first run in an air-gapped server. By default,tiktokendownloads its.tiktokenBPE vocabulary file on initial import. Pre-cache the file during Docker build time by runningtiktoken.get_encoding("o200k_base")inside yourDockerfile. - Issue: Tool schemas silently add thousands of tokens. Remember that JSON tool definitions and function descriptions count toward your input context limit. Check our review of 6 best LLM tokenizers compared to see which tools count nested tool schemas accurately.
Frequently Asked Questions
Is tiktoken accurate for Anthropic Claude or Google Gemini?
No. tiktoken is only exact for OpenAI models. Using it on Claude or Gemini can drift by 10% to 25% on code or multilingual inputs, so use each provider’s native free token counter instead.
How fast is tiktoken compared to pure Python splitters?
tiktoken is written in Rust under the hood and processes roughly 1 million to 3 million bytes per second per CPU thread, making it fast enough to run inline inside web API middleware.
Do output tokens and input tokens count differently toward limits?
Both input prompt tokens and generated output tokens share the same total context window ceiling, though providers bill output tokens at a higher rate per million tokens than input tokens.
Final Thoughts & Next Steps
We hope this tutorial helped you set up fast, exact token counting in Python before sending API requests.
Explore the next guides in our Tokenization cluster to keep your AI apps resilient:
- Seeing truncated JSON or context errors? Read How to Fix LLM Token Limit Errors and Context Truncation.
- Comparing Node.js and Python options? Browse 6 Best LLM Tokenizers and Token Calculators Compared.
- Want the full architecture map? Revisit The Ultimate Guide to LLM Tokenization and Cost Control.
Building custom high-volume AI services or tuning token costs? Talk with our software engineering team at teckscaler.com/contact/.
Published by the TeckScaler Editorial Team. Last updated November 25, 2026.



