Sub topic 1
What a Token Is
Prerequisites
This chapter assumes you can read basic Python, have used an LLM chat or completion API, and are comfortable with simple arithmetic.
What a token is
A token is a piece of text that a language model processes. A token may be a whole word, part of a word, punctuation, or a space combined with nearby text. Tokens are the model’s working units. They are not the same as words or characters.
Token counts matter because models limit and price requests in tokens. The exact count depends on the tokenizer, which is the algorithm that splits text into tokens. Different model families can tokenize the same text differently.
How text is split into tokens
Most modern tokenizers use a subword vocabulary. Common words may be one token, while rare or long words may be split into several pieces. Punctuation and spaces can also affect the result.
For example, a sentence with ten words might contain twelve tokens. This is only an illustration, not a reliable conversion rule.
Counting tokens
Use the tokenizer that matches the model when you need an exact count. This example uses the open-source tiktoken library:
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
text = "Tokens are not the same as words."
token_ids = enc.encode(text)
print(len(text.split()), "words")
print(len(token_ids), "tokens")
print([enc.decode([token_id]) for token_id in token_ids])Install the library with pip install tiktoken. For a real API call, prefer the usage data returned by the API when it is available. That data records the provider’s actual input and output token counts, including formatting that your local estimate might miss.
The context window
A model’s context window is the maximum number of tokens it can consider in one request. It usually includes the system instructions, conversation history, current user message, and requested output. If the input leaves too little room for the output, the request may fail or produce a shorter response.
Exercise
If a request contains 2,000 input tokens, asks for up to 500 output tokens, and the context window is 8,000 tokens, does it fit?
Show answer
Yes. The combined budget is 2,500 tokens, which is below 8,000.