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, including finish_reason and usage. It also assumes you know what a token is. Here you will learn the request fields that shape what the model writes: how random it is, how long it can be, and where it stops.
Field names follow the chat-completions format. Providers differ. Some rename max_tokens, restrict temperature on certain models, or ignore a field without an error. Check your provider's documentation for the model you use.
How the model picks each token
A model generates text one token at a time. At each step it produces a score for every token in its vocabulary. Those scores are turned into probabilities. The next token is then chosen from that distribution, appended to the text, and the process repeats.
Sampling parameters change how that choice is made. They do not change what the model knows. They only change how the probabilities are used.
Temperature
temperature rescales the probabilities before sampling.
- Low values (near 0) sharpen the distribution. The most likely token wins almost every time.
- Higher values (1 and above) flatten it. Less likely tokens are chosen more often.
Typical ranges are 0 to 2 for the chat-completions format, with a default near 1. Other providers may cap the value at 1.
| Temperature | Behavior | Good for |
|---|---|---|
| 0 to 0.3 | Focused, repeatable | Extraction, classification, code, answering from given facts |
| 0.5 to 0.9 | Balanced | General chat, summaries, explanations |
| 1.0 and above | Varied, less predictable | Brainstorming, creative writing, name ideas |
Very high values can produce incoherent text, because rare tokens get picked often enough to derail a sentence.
Temperature 0 is not a guarantee
A temperature of 0 makes output close to deterministic, but not always identical between calls. Floating-point differences on the serving hardware, batching, and model updates can all change a result. Some providers offer a seed parameter that improves repeatability on a best-effort basis. Do not write tests that assert exact equality on model text. Test properties of the output instead, such as valid JSON or the presence of a required field.
Some models restrict sampling settings
Certain reasoning-oriented models reject a custom temperature or require a fixed value. If a request returns a 400 error that names temperature, read the model's documentation before assuming your code is wrong.
top_p
top_p, also called nucleus sampling, keeps only the smallest set of tokens whose probabilities add up to top_p. With top_p of 0.9, the model samples from the most likely tokens that together cover 90% of the probability and ignores the rest.
Lower values make output more conservative. A value of 1 turns the filter off.
Most providers advise changing either temperature or top_p, not both. The two interact, and adjusting both makes it hard to tell which one caused a change in behavior. Pick one, change it in small steps, and compare outputs.
Length limits
Length controls matter for two reasons: they keep replies useful, and they cap cost and latency.
max_tokens and its relatives
max_tokens sets the maximum number of tokens the model may generate in the reply. It does not count your input. Newer versions of the chat-completions format use max_completion_tokens for the same idea, and for reasoning models that name also covers hidden reasoning tokens. Use whichever name your provider and model document.
Three points often cause trouble:
- It is a cap, not a target. Setting
max_tokensto 500 does not make the model write 500 tokens. It only cuts the reply off if it would go past 500. - It cuts mid-sentence. The model is not aware of the limit while writing. When the limit is reached, generation stops, even in the middle of a word.
- Input plus output must fit the context window. If your prompt uses 7,000 tokens of an 8,000-token window, the reply can be at most about 1,000 tokens, whatever you request. Some APIs reject a request when
max_tokensis too large for the remaining space. Others silently clamp it.
To get shorter replies, ask for them in the prompt ("answer in two sentences") and use max_tokens as a safety net, not as the main control.
Detecting truncation
When the reply is cut by the length limit, finish_reason is "length" rather than "stop". Always check it. A truncated JSON object, for example, will fail to parse, and a truncated answer may look complete to a reader.
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": "Describe how the internet works."}
],
"temperature": 0.2,
"max_tokens": 40,
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
choice = data["choices"][0]
print(choice["message"]["content"])
print("finish_reason:", choice["finish_reason"])
print("completion_tokens:", data["usage"]["completion_tokens"])
if choice["finish_reason"] == "length":
print("Warning: the reply was cut off by max_tokens.")With max_tokens set to 40, the reply will almost certainly stop mid-thought and report length. The completion_tokens count will be at or just under 40. Raise the limit or ask for a shorter answer to fix it.
Stop sequences
stop is a string, or a short list of strings, that ends generation when the model is about to produce it. The stop text itself is not included in the returned content. The finish reason is "stop", the same as a natural ending, so you cannot tell from finish_reason alone which cause applied.
Providers limit the number of stop sequences, commonly to four. Check your provider's limit.
Stop sequences are useful when you want output in a fixed shape:
- Ending a list at a marker, such as
"\n\n"or"END". - Stopping before the model invents the next turn of a dialogue, for example
"User:". - Getting a single line of output with
"\n".
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 four fruits, one per line, numbered. "
"After the fourth, write END.",
}
],
"temperature": 0,
"stop": ["END"],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
print(repr(resp.json()["choices"][0]["message"]["content"]))The printed text ends after the fourth fruit, with no END. Note that stop matching is exact and case-sensitive. A stop of "END" will not match "End".
Stop sequence pitfalls
- A stop string that appears early in normal text ends the reply too soon. A stop of
"."would end output after the first sentence. - With chat models, the prompt must make the stop marker likely to appear. If the model never writes
END, the stop never fires and onlymax_tokensor the natural end applies. - Some newer models do not support
stop. Verify support for your model.
Repetition penalties
Some APIs expose frequency_penalty and presence_penalty, usually in the range -2 to 2.
frequency_penaltylowers a token's probability more each time it has already appeared. It reduces verbatim repetition.presence_penaltyapplies a one-time penalty once a token has appeared at all. It nudges the model toward new topics.
Leave both at 0 unless you see a repetition problem. Large values produce odd word choices, because the model avoids common words it needs.
Multiple choices with n
n asks for several independent replies in one request. The choices array then has n entries, each with its own finish_reason. You pay for the completion tokens of every choice. This is useful for generating options or for voting across answers, but it multiplies cost. Do not assume choices[0] is the best one.
Choosing settings in practice
Start with defaults and change one setting at a time. A reasonable approach:
- Decide whether the task needs one correct answer or a range of acceptable ones.
- For one correct answer, set
temperatureto 0 to 0.2. - For creative or varied output, use 0.7 to 1.0.
- Set
max_tokensto a generous ceiling that still protects you from runaway output. - Check
finish_reasonon every response, and treatlengthas a condition your code handles.
Run the same prompt several times at each setting and read the results. Judging sampling by a single call is misleading, because randomness hides the real difference.
Summary of parameters
| Parameter | What it controls | Common range | Watch out for |
|---|---|---|---|
| `temperature` | Randomness of token choice | 0 to 2 | 0 is not perfectly repeatable; some models restrict it |
| `top_p` | Size of the candidate token pool | 0 to 1 | Tune it or temperature, not both |
| `max_tokens` | Cap on generated tokens | 1 to context limit | Truncates mid-sentence; may be named differently |
| `stop` | Strings that end generation | Up to about 4 | Exact match; finish reason looks like a normal stop |
| `frequency_penalty` | Penalty that grows with repeats | -2 to 2 | Large values distort wording |
| `presence_penalty` | One-time penalty for seen tokens | -2 to 2 | Pushes toward new topics |
| `n` | Number of replies | 1 and up | Cost multiplies by `n` |
Exercise
A request sets max_tokens to 100 and the response has finish_reason equal to "length" and completion_tokens equal to 100. Your code parses the content as JSON and fails. What happened, and what are two ways to fix it?
Show answer
The model was cut off by the token cap before it finished the JSON object, so the text is incomplete and cannot be parsed. Fix it by raising max_tokens (or asking for a shorter object in the prompt), and by checking finish_reason before parsing so your code can retry or report the truncation instead of failing on invalid JSON.
Exercise
You set stop to ["END"], and the reply ends with finish_reason equal to "stop". Can you tell whether the model reached END or ended naturally? How could you design the prompt to make the cause clear?
Show answer
No. Both cases report "stop", and the stop text is removed from the content. To make the cause clear, ask the model to write a distinctive final line before the marker, such as a closing label, and check whether it is present. You can also use a prompt format where a missing closing label means the reply ended another way.
Exercise
A teammate sets both temperature to 1.5 and top_p to 0.5 to get "creative but safe" output, and the results are hard to reason about. What would you recommend?
Show answer
Change only one of the two. The settings interact, so using both makes it unclear which one produced a given behavior. Pick temperature (or top_p), return the other to its default, adjust in small steps, and compare several runs at each value.