Sub topic 7
Controlling output with temperature and max_tokens
This chapter assumes you can already send a chat completion to a local server using the OpenAI Python client, as covered in the earlier chapters. You should know how to set base_url and a placeholder api_key, and you should have at least one model downloaded. Examples use Ollama on port 11434 with llama3.2. Change the URL and model name for llama-server, LM Studio, or vLLM.
Why these two settings matter
A language model produces text one token at a time. A token is a chunk of text, often a word piece or a short word. At each step the model assigns a score to every token in its vocabulary. The server turns those scores into probabilities and picks one token. Two request parameters shape this process:
temperaturechanges how the next token is picked, which affects variety and predictability.max_tokenslimits how many tokens the model may generate, which affects length, cost, and latency.
Both are optional. If you leave them out, the server uses its own defaults. Those defaults differ between servers and between models, so a script that omits them can behave differently when you switch backends.
How temperature works
Before choosing a token, the server divides the model's raw scores by the temperature and then converts them to probabilities. A low temperature sharpens the distribution, so the most likely token wins most of the time. A high temperature flattens it, so less likely tokens get picked more often.
| Temperature | Behavior | Typical use |
|---|---|---|
| 0 | Nearly deterministic. The top token is chosen at each step. | Extraction, classification, code, tests |
| 0.1 to 0.5 | Focused, with small variations | Summaries, factual answers |
| 0.7 to 1.0 | Varied and more natural | Chat, brainstorming |
| Above 1.2 | Increasingly erratic | Rarely useful, can produce nonsense |
The hosted OpenAI API accepts values from 0 to 2. Local servers usually accept the same range, but the default is not always the same. Ollama's native default is 0.8, while many OpenAI-style servers default to 1.0. If reproducibility matters, always set the value yourself.
Temperature 0 is not a guarantee
Setting temperature=0 makes output close to repeatable, but not always identical. Floating-point math on GPUs can differ slightly between runs, batching can change the order of operations, and some servers treat 0 specially. If you need repeatable output, also send a seed where the server supports it, and test that it works before relying on it.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
def ask(prompt, temperature):
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
max_tokens=40,
)
return response.choices[0].message.content.strip()
prompt = "Name a color and one object that has that color."
for t in (0.0, 1.0):
print(f"--- temperature={t}")
for _ in range(3):
print(ask(prompt, t))At 0.0 the three answers should be the same or nearly the same. At 1.0 you should see more variety. The exact text depends on your model.
Related sampling parameters
top_p is another way to limit randomness. It restricts the choice to the smallest set of tokens whose probabilities add up to top_p. A value of 0.9 ignores the unlikely tail. The usual advice is to adjust either temperature or top_p, not both, so you can tell which one caused a change.
Other settings such as top_k, min_p, and repeat_penalty exist on many local servers, but they are not part of the standard OpenAI request. The Python client lets you send them through extra_body, and servers that do not recognize them may ignore them silently.
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Suggest a project name."}],
temperature=0.8,
extra_body={"top_k": 40},
)
print(response.choices[0].message.content)Whether top_k takes effect depends on the server. Check its documentation, or compare outputs with and without it.
How max_tokens works
max_tokens sets an upper bound on the number of tokens generated in the reply. It does not include your prompt. It is a ceiling, not a target. A model that finishes its answer in 20 tokens stops at 20 even if the limit is 500.
Three practical reasons to set it:
- It bounds response time. Generation speed on local hardware is often 5 to 60 tokens per second, so a 2,000-token reply can take a long time.
- It protects against runaway output, such as a model that repeats itself.
- It keeps replies short when you only need a short answer.
Newer versions of the hosted API prefer the name max_completion_tokens. Many local servers still read max_tokens only, and some read both. If a limit seems ignored, try the other name.
The context window limit
Every model has a context window, which is the maximum number of tokens it can handle in total. Your prompt tokens plus the generated tokens must fit inside it. If your prompt uses 3,900 tokens and the window is 4,096, the model can generate at most about 196 tokens, whatever max_tokens says.
Some servers allocate a small default window. Ollama, for example, has historically used a modest default context length unless you configure a larger one. A long prompt can then be truncated without an error, which is a hard failure to spot. If answers ignore the start of a long prompt, check the server's context setting.
Reading finish_reason
The response tells you why generation stopped. Read it from choices[0].finish_reason.
| Value | Meaning |
|---|---|
| `stop` | The model ended naturally, or hit a stop sequence |
| `length` | The `max_tokens` limit (or the context window) was reached |
| `tool_calls` | The model requested a tool call |
A length result means the reply may be cut off in the middle of a sentence. Your code should check for it rather than assume the text is complete. The usage field reports how many tokens were used, when the server provides it.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a context window is."},
],
temperature=0.2,
max_tokens=30,
)
choice = response.choices[0]
print(choice.message.content)
print("finish_reason:", choice.finish_reason)
if response.usage:
print("prompt tokens:", response.usage.prompt_tokens)
print("completion tokens:", response.usage.completion_tokens)
if choice.finish_reason == "length":
print("Warning: the reply was cut off. Raise max_tokens or shorten the request.")With max_tokens=30 the reply will almost certainly be truncated, so you should see finish_reason: length.
Stop sequences
The stop parameter takes a string or a list of up to a few strings. Generation ends as soon as one of them would appear, and the stop text itself is not included in the reply. This helps when you want exactly one line or one item.
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "List three fruits, one per line."}],
temperature=0,
max_tokens=60,
stop=["\n\n"],
)
print(response.choices[0].message.content)Support for stop is common, but the allowed number of sequences varies.
Choosing values for a task
Start from the task, not from a default.
- For extracting fields, labeling text, or writing code that must be correct, use a low temperature (0 to 0.2) and a
max_tokensjust above the longest expected answer. - For a chat assistant, use 0.5 to 0.8 and a generous
max_tokens, then watch forlengthfinish reasons. - For creative writing, use 0.8 to 1.0 and allow longer output.
Change one setting at a time and run the same prompt several times. A single run tells you little, because sampling is random.
Common errors
- Truncated answers. The reply ends mid-sentence. Check
finish_reason. Raisemax_tokens, but also check that the prompt plus reply fits in the context window. - Output different on every run despite a low temperature. Confirm that the setting reached the server. Some wrappers override it. Try
temperature=0and aseed. - Rambling or repeated text at high temperature. Lower the value, or reduce
max_tokensso the damage is limited. - Empty reply. Some reasoning models spend part of the token budget on hidden thinking text. A small
max_tokenscan be used up before any visible answer appears. Raise the limit. - A parameter that seems to have no effect. The server may ignore parameters it does not support without returning an error. Test by varying the value and observing the output.
Exercise
A request sets maxtokens=500 and the model's context window is 4,096 tokens. The prompt is 3,800 tokens. The reply ends mid-sentence and finishreason is "length". Why did it stop, and what are two ways to fix it?
Show answer
The prompt leaves only about 296 tokens of room in the context window (4,096 minus 3,800), so generation stopped there even though maxtokens allows 500. Fix it by shortening the prompt, or by configuring the server to use a larger context window (and a model that supports it). Raising maxtokens alone would not help.
Exercise
You are building a script that extracts a date from an email and must return the same answer each time you run it on the same input. Which settings would you send, and what should you check afterward?
Show answer
Send a low temperature, ideally 0, a small maxtokens that fits the expected date format, and a seed if the server supports it. Afterward, run the same input several times to confirm the output is identical, and check that finishreason is "stop" rather than "length".