Sub topic 2
Tokens and the Context Window
Assume you know basic Python, JSON, HTTP status codes, and environment variables. This chapter uses the chat-completions request shape. Providers may use different field names.
Tokens and the context window
A token is a small piece of text that a model reads or generates. A token may be a whole word, part of a word, punctuation, or whitespace. Token counts are therefore different from character and word counts.
The context window is the maximum number of input and output tokens a model can process in one request. It includes system messages, conversation history, the current prompt, and the generated reply.
If the input is too large, the provider may reject the request or require you to remove older messages. Set an output limit so the reply also has room within the window.
Controlling output
Sampling settings affect how the model chooses its next token.
temperaturecontrols randomness. Lower values usually produce more consistent text. Higher values allow more variety.max_tokenslimits the generated output. Providers may call this parametermax_output_tokens.stopsupplies one or more sequences that tell the model to stop generating.
These settings do not guarantee exact length or correctness. A low temperature does not make factual errors impossible.
import json
payload = {
"model": "your-model",
"messages": [
{"role": "system", "content": "Answer briefly."},
{"role": "user", "content": "Explain context windows."},
],
"temperature": 0.2,
"max_tokens": 100,
"stop": ["\n\n"],
}
print(json.dumps(payload, indent=2))Multi-turn conversations
The API is usually stateless. Your program maintains the history and sends it again:
- Append the user's message.
- Send the complete message list.
- Append the assistant's reply.
- Repeat.
Long histories consume tokens. Summarize or remove old messages when the context budget becomes small.
Errors and rate limits
A 400 response usually means the request is invalid, such as an unsupported parameter or an oversized context. A 401 indicates authentication failure. A 429 means a rate limit or quota limit was reached. 500-series responses indicate a provider-side failure.
Retry timeouts, 429, and temporary 500-series errors with bounded exponential backoff. Do not blindly retry permanent 400 or 401 errors.
Exercise
Why can adding an assistant's previous answer cause a later request to fail?
Show answer
The answer becomes part of the resent history, increasing input tokens until the context window or token budget is exceeded.