Context budgeting
Estimate whether a prompt plus its expected completion fits a model's context window.
AI & ML · Const
Tokenization divides text into tokens—commonly occurring character sequences that models process. Token count affects how much input and generated output can fit within a model’s context length.
Tokenization splits text into commonly occurring character sequences called tokens. Models process these tokens sequentially, and the tokenizer determines how much input and generated output fits within a model's context length.
from tiktoken import get_encoding
encoding = get_encoding("cl100k_base")
text = "ChatGPT is great!"
tokens = encoding.encode(text)
print(tokens)
print(len(tokens))This Python example encodes text with tiktoken and prints both its token IDs and token count.
Estimate whether a prompt plus its expected completion fits a model's context window.
Inspect how spaces, words, and punctuation are split before designing prompts.
Measure input size before sending embedding requests.
Tokens are chunks of commonly occurring character sequences rather than necessarily whole words. For example, a word may split into multiple tokens, while a short common word may remain one token.
Follow-up: How would you estimate token usage before making a request? Use a tokenizer for the target model; the English rule of thumb is about four characters or three-quarters of a word per token.
A practical English estimate is approximately four characters or 0.75 words per token. This is only a rough estimate, so exact budgeting should use the tokenizer.
Follow-up: Why can the estimate be inaccurate? Token boundaries depend on the actual character sequences, including spaces and uncommon text.
Token count matters because the input and generated output together must fit the model's maximum context length. Counting tokens helps determine whether a request can fit before sending it.
Follow-up: What changes for embeddings? Since embeddings models do not produce tokens, only the input must remain below their maximum context length.
Tokenizertiktokencontext lengthembeddings models