How Local Token Counting Works with tiktoken
tiktoken runs locally in Python using OpenAI’s byte-pair encoding (BPE) rules without making any network call. You can count tokens before sending a request to check context limits and estimate costs.
- Input tokens are exact for text strings: Calling
len(enc.encode(text))gives the exact token count of a string for that model’s encoding. - Chat messages add small framing overhead: Each message in a chat array has extra structural tokens (such as role/message framing), so counting raw
contentalone can slightly undercount a full chat prompt. - Output tokens can only be counted after generation (or estimated): Before calling the API, you cannot know the exact model reply length in advance—you can only cap it with
max_tokens/max_completion_tokensor estimate it, then count the actual returned text withlen(enc.encode(output_text))once received.
Steps to Count Input and Output Tokens
- Pick the right encoding for your model: Use
tiktoken.encoding_for_model(model)(falling back tok_baseorcl100k_baseif a newer model name is not mapped yet). - Count input tokens before sending: Encode your prompt or chat messages and add message framing tokens so you stay safely under the context window.
- Count output tokens on the response text: Once you receive the completion text (or accumulate streamed chunks), run
len(enc.encode(response_text))locally to measure exact output tokens.
Python Example with tiktoken
import tiktoken
def get_encoder(model: str):
try:
return tiktoken.encoding_for_model(model)
except KeyError:
# Fallback for newer models not yet listed in tiktoken's model map
return tiktoken.get_encoding("o200k_base")
def count_text_tokens(text: str, model: str = "gpt-4o-mini") -> int:
enc = get_encoder(model)
return len(enc.encode(text))
def count_chat_input_tokens(messages: list[dict], model: str = "gpt-4o-mini") -> int:
enc = get_encoder(model)
tokens_per_message = 3
tokens_per_name = 1
total = 0
for message in messages:
total += tokens_per_message
for key, value in message.items():
if isinstance(value, str):
total += len(enc.encode(value))
if key == "name":
total += tokens_per_name
# Reply priming overhead
total += 3
return total
# 1. Before sending: count exact input tokens
messages = [
{"role": "system", "content": "You are a concise backend engineer."},
{"role": "user", "content": "Explain connection pooling in two short sentences."},
]
input_tokens = count_chat_input_tokens(messages, model="gpt-4o-mini")
print("Input tokens:", input_tokens)
# 2. After receiving model output: count exact output tokens locally
simulated_output = (
"Connection pooling reuses open database connections instead of creating a new one per request. "
"This lowers latency and prevents exhausting database connection limits under load."
)
output_tokens = count_text_tokens(simulated_output, model="gpt-4o-mini")
print("Output tokens:", output_tokens)
print("Total tokens:", input_tokens + output_tokens)
Helpful Tips
- Leave room for output tokens: Always check
input_tokens + max_output_budget <= context_windowbefore sending large prompts. - Include schemas and tools if used: Tool definitions, JSON schemas, and images add extra tokens beyond plain text messages, so keep a small safety buffer.
- Check API usage fields too: Comparing your local
tiktokencount againstusagereturned by the API helps verify your message-framing math on your exact payloads.
You must log in or register to comment.
