Models see text as tokens, not words, and the only reliable way to know how many tokens a request will use is to count them with the same tokenizer the model uses. Tiktoken is a fast byte pair encoding tokenizer for OpenAI models, and it can return the encoding for a specific model. OpenAI gives a rough rule of thumb, one token is about 4 characters of English text, or about 75 words per 100 tokens, but a rule of thumb is not a count: measure before you send.
What you need
- The request text exactly as it will be sent
- The model name, so the right encoding is used
- The model context limit in tokens
Step 1: Load the encoding for your model
Use tiktoken encoding_for_model with the model name, for example gpt-4o, or get_encoding with the encoding name, for example cl100k_base for third-generation embedding models and o200k_base for newer models.
Step 2: Encode the exact request and count
Encode the full request text, including the system prompt, the conversation history and any tool definitions, and count the tokens. Tool definitions count against the context limit and are billed as input tokens.
Step 3: Compare with the limit and trim if needed
Compare the count with the context limit, leaving room for the expected output. If the request is too long, trim the history, shorten the context, or summarize, before sending, rather than after an error.
Worked example: synthetic token count for 4 prompts
The table below is a synthetic example. It shows the expected result of counting tokens; no API was called.
| Prompt | Characters | Tokens |
|---|---|---|
| Short question | 40 | About 10 |
| Long instruction | 4,000 | About 1,000 |
| Full conversation | 40,000 | About 10,000 |
| Conversation plus tools | 48,000 | About 12,000 |
Expected result (UNTESTED). the counts rise with the text, and the full conversation plus tools is the largest request. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- Tiktoken counts OpenAI model tokens; other providers use different tokenizers, so the count does not transfer.
- The rule of thumb, one token per 4 characters, is an average: code and non-English text tokenize differently.
- Counting the text is not the whole request: images, tool definitions and cached prefixes also use tokens.
- A token estimate does not guarantee the request meets every input limit, such as per-image patch limits.
