Sub topic 7
Controlling output with temperature and max_tokens
This chapter assumes you can already send a chat completion to a local server through the OpenAI Python client, with base_url set and a placeholder API key. Your server must be running with a model such as llama3.2 downloaded. Here you will learn the two settings that most change what comes back: temperature and max_tokens.
What the two parameters do
A model produces text one token at a time. A token is a chunk of text, often a word or part of a word. At each step the model assigns a probability to every possible next token, and the server picks one.
temperaturecontrols how that pick is made. Low values (near 0) favor the most likely token, so output is focused and repeatable. High values (1 and above) flatten the odds, so output is more varied and less predictable.max_tokenssets an upper limit on how many tokens the model may generate in the reply. It limits the output only. It does not count your prompt.
| Setting | Typical range | Low value | High value |
|---|---|---|---|
| `temperature` | 0 to 2 | Consistent, literal | Varied, creative, more errors |
| `max_tokens` | 1 up to the context limit | Short, may be cut off | Longer replies, slower |
Setting them in a request
Both are plain arguments to chat.completions.create.
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=200,
)
print(response.choices[0].message.content)With temperature=0.2, repeated runs give very similar answers. With max_tokens=200, the reply stops after at most 200 tokens, even in the middle of a sentence.
Detecting a truncated reply
When the limit cuts a reply short, the response tells you. Check finish_reason on the choice.
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": "user", "content": "Explain what a context window is."}],
max_tokens=20,
)
choice = response.choices[0]
print(choice.message.content)
print("finish_reason:", choice.finish_reason)A finish_reason of stop means the model ended on its own. A value of length means the limit was reached and the text is incomplete. Treat length as a signal to raise max_tokens or ask for a shorter answer.
Comparing temperatures
Run the same prompt several times at two settings to see the effect.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
prompt = "Suggest a name for a coffee shop. Reply with only the name."
for temp in (0.0, 1.2):
print(f"temperature={temp}")
for _ in range(3):
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": prompt}],
temperature=temp,
max_tokens=20,
)
print(" ", response.choices[0].message.content.strip())At 0.0 you should see the same name, or nearly so, each time. At 1.2 the names should differ.
Common errors
- Expecting identical output at temperature 0. Many servers are close to deterministic at 0, but batching and hardware details can still cause small differences. Some servers also ignore a value of exactly 0 or treat it differently, so test yours.
- Setting
max_tokenstoo low. The reply ends mid-sentence withfinish_reasonoflength. - Assuming
max_tokensextends the context. The prompt and the reply must together fit in the model's context window. Setting a largemax_tokensdoes not enlarge it. Local servers often load a smaller context than the model supports, so check your server's setting. - Raising temperature for factual tasks. Higher values increase the chance of invented details. Use low values for extraction, code, and answers that must be correct.
- Skipping
max_tokenson a slow machine. Local generation speed depends on your hardware. Without a cap, a long reply can take minutes, and the client may hit its timeout first.
Exercise
You call the server with max_tokens=50 and get a reply that ends in the middle of a sentence. What field would you check to confirm the cause, what value would you expect, and what are two ways to fix it?
Show answer
Check response.choices[0].finishreason. You would expect "length", which means the token limit was reached. Fix it by raising maxtokens, or by changing the prompt to ask for a shorter answer, for example by adding a system message such as "Answer in two sentences."
Exercise
A teammate sets temperature=1.5 for a script that extracts invoice numbers from text and sometimes gets wrong numbers. What would you change and why?
Show answer
Lower the temperature to 0 or close to it. High temperature makes the model pick less likely tokens, which raises the chance of errors in a task that needs exact, repeatable output.