How do you count exact input and output tokens locally using tiktoken before sending a prompt to the API? | A1Lab@HamzaM to AI & LLMEnglish • 5 days ago

How do you count exact input and output tokens locally using tiktoken before sending a prompt to the API?

message-square
0

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 content alone 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_tokens or estimate it, then count the actual returned text with len(enc.encode(output_text)) once received.

Steps to Count Input and Output Tokens

  1. Pick the right encoding for your model: Use tiktoken.encoding_for_model(model) (falling back to o200k_base or cl100k_base if a newer model name is not mapped yet).
  2. Count input tokens before sending: Encode your prompt or chat messages and add message framing tokens so you stay safely under the context window.
  3. 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_window before 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 tiktoken count against usage returned by the API helps verify your message-framing math on your exact payloads.