Sub topic 5
Tokens and the Context Window
This chapter assumes you can send a chat request and read the response, as covered in the earlier chapters. You should also be comfortable reading the usage object in a response.
What a token is
A model does not read characters or words. It reads tokens, which are chunks of text produced by a tokenizer. A token can be a whole common word, part of a rare word, a punctuation mark, or a space plus a few letters.
For English text, a rough rule is that one token is about four characters, or three quarters of a word. Treat this as an estimate only. Code, non-English text, and unusual strings such as IDs often split into many more tokens. Each model family has its own tokenizer, so the same text can have different counts on different models.
Tokens matter for three reasons:
- Providers bill by tokens, not by words or requests.
- Each model has a hard limit on how many tokens it can handle at once.
- Generation time grows with the number of tokens produced.
Input tokens and output tokens
Every request has two token counts. Prompt tokens (input) are everything you send: system message, history, and the new user message. Completion tokens (output) are what the model generates. The response reports both.
usage = {"prompt_tokens": 42, "completion_tokens": 18, "total_tokens": 60}
print(usage["prompt_tokens"] + usage["completion_tokens"] == usage["total_tokens"])Field names follow the chat-completions shape. Other providers use different names, so check your provider's documentation.
The context window
The context window is the maximum number of tokens a model can consider in one request. It covers the input and the output together. If a model has a 16,000-token window and your prompt uses 15,000 tokens, only about 1,000 tokens remain for the reply.
Many models also set a separate cap on output length, which is lower than the window. Your provider's model page lists both numbers.
Counting tokens before you send
The usage field only tells you the count after the call. To check size beforehand, use a tokenizer library. For OpenAI-style models, the tiktoken package is one option.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
text = "Explain what a token is in one sentence."
print(len(enc.encode(text)))The encoding name must match your model. A mismatched tokenizer gives a count that is close but not exact, so leave a safety margin. Chat requests also add a few tokens of overhead per message for role markers.
Common errors
- Context length exceeded. The API returns a 400 error when prompt plus requested output cannot fit. Retrying will not help. Shorten the input or lower the output limit.
- Truncated replies. If the
finish_reasonislength, the reply stopped at a token limit and may be cut mid-sentence. - Growing history. In a multi-turn chat, you resend all earlier messages, so the prompt grows every turn. Cost and the risk of hitting the limit grow with it.
- Assuming words equal tokens. Budgeting by word count underestimates code and non-English text.
Staying within the limit
When input is too large, you have a few options:
- Remove the oldest turns of a conversation, but keep the system message.
- Summarize older turns into a short message.
- Send only the relevant parts of a document instead of the whole file.
- Reduce the maximum output tokens so the reply fits.
Exercise
A model has an 8,000-token context window. Your prompt is 7,200 tokens, and you ask for up to 1,500 output tokens. What happens, and how do you fix it?
Show answer
The request needs 8,700 tokens, which exceeds the 8,000-token window, so the API will likely reject it with a context-length error (or the reply will be cut short). Retrying will not help. Fix it by shortening the prompt, for example by trimming old messages, or by lowering the output limit to 800 tokens or less.