Sub topic 6
Controlling output: temperature, length limits and stop settings
This chapter assumes you can already send a chat request and read the response, as covered in earlier chapters. You should also know what a token is. Here you will change three kinds of settings that shape the reply: how random it is, how long it can be, and where it must stop.
Parameter names below follow the chat-completions shape. Some providers rename them or restrict them for certain models, so check your provider's documentation.
Temperature and top_p
A model picks each next token from a probability distribution. Temperature rescales that distribution before the pick.
- Low values (0 to 0.3) make the most likely token win almost every time. Output is focused and more repeatable.
- High values (0.8 and above) flatten the distribution. Output is more varied and more likely to wander.
top_p (nucleus sampling) is a second control. It limits the choice to the smallest set of tokens whose probabilities add up to p. A top_p of 0.1 keeps only the most likely tokens.
Change one of the two, not both. Their effects overlap, and tuning both makes results hard to explain.
A temperature of 0 is not a guarantee of identical output. Server-side details can still cause small differences between runs. Some models also fix these settings and reject changes, so a 400 error on temperature is a sign to check the model's documentation.
| Task | Typical temperature |
|---|---|
| Extraction, classification, code | 0 to 0.3 |
| Question answering, summaries | 0.3 to 0.7 |
| Brainstorming, creative writing | 0.8 to 1.0 |
Length limits
The reply length is capped by a maximum token setting. In chat completions the name is max_tokens on older models and max_completion_tokens on newer ones. The cap applies to output only, and the input plus the output must still fit in the context window.
When the cap is reached, the model stops mid-sentence. The response tells you this through finish_reason:
stop: the model finished naturally or hit a stop sequence.length: the reply was cut off by the token cap or the context window.
Always check this field. A reply that ends with length is incomplete, and treating it as complete is a common bug. Some models also count hidden reasoning tokens against the cap, so a small cap can leave you with little or no visible text.
Stop sequences
A stop sequence is a string that ends generation as soon as the model would produce it. The stop string itself is not included in the output. You can pass a single string or a short list (providers allow only a few).
This is useful when you want exactly one item from a pattern, such as a single line or a single answer block.
Putting it together
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [
{"role": "user", "content": "List three fruits, one per line, numbered. End with the line END."},
],
"temperature": 0.2,
"max_tokens": 60,
"stop": ["END"],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
choice = resp.json()["choices"][0]
print(choice["message"]["content"])
if choice["finish_reason"] == "length":
print("Warning: reply was truncated")If your model rejects max_tokens, replace it with max_completion_tokens.
Exercise
A request with max_tokens set to 50 returns text that ends mid-sentence. Which field confirms the cause, what value should it have, and what are two ways to fix it?
Show answer
The choice's finish_reason field should be "length". Fix it by raising the token cap (while staying inside the context window), or by asking for a shorter answer in the prompt so it fits within the cap.