What You Will Build
Send a model the same request twice and you may get two different replies. For an agent that is not a curiosity: it means a test that passed once can fail the next time, and a single run proves little. In this lesson you set the options that control how a reply is generated, and you measure how much replies vary instead of guessing. You will:
- explain how temperature changes the choice of each token;
- measure how many different replies ten identical requests give at three settings, after predicting the answer;
- explain what a seed and temperature 0 do and do not guarantee;
- limit a reply's length with
num_predictand recognisedone_reasonlength; - choose
num_ctxdeliberately, and recognise thinking output from models that produce it.
Before you start, you need send-a-chat-request. Allow about 40 minutes.
The measurement sends thirty short requests: a few seconds with a GPU, up to
about twenty seconds without one.
How the Model Chooses Each Token
A model writes one token at a time. At each step it gives every possible next token a probability, then one token is chosen and the process repeats with that token added. Sampling is how the choice is made, and temperature controls it:
- At temperature 0, the most likely token is always chosen. Given the same conversation, the same model build and the same software, the reply is usually the same every time.
- At a higher temperature, less likely tokens get more of a chance. The probabilities are flattened: the favourite still leads, but by less.
- At a lower temperature above 0, the favourite's lead grows.

Real probabilities from granite4.1:3b for the first token of one reply,
rescaled for each temperature among the five most likely tokens.
These numbers were recorded with Ollama's logprobs option, which returns
the model's probabilities for the tokens it considered. For the first token
of a name for a camping stove, the model rated Camp most likely (0.37 of
all its probability), then Trail (0.13), then three tokens below 0.06; the
five together held 0.64. At temperature 0 Camp is chosen every time. At
0.8 it is chosen about two times in three among these five, and at 1.5 less
than half the time, so other names start appearing.
The first token matters more than it looks: once a different first token is chosen, everything after it is written to follow on from that token, so one early difference usually produces a whole different reply.
Ollama has other sampling options (top_k, top_p, min_p) that limit
which tokens can be chosen at all. The course leaves them at their defaults
and controls variation with temperature alone.
Seeds and Their Limits
Choosing "at random" in a computer means using a random number generator,
and a seed is the number it starts from. With the seed option set,
the same seed should produce the same sequence of choices, so the same reply,
for the same request. That is a hope, not a guarantee. The reply can still
change when the model build, Ollama's version, the hardware, or the way
requests are batched changes, and Ollama's documentation makes no promise
about determinism. Temperature 0 removes the random choice altogether, which
is why course exercises use it, but even then two computers can disagree
when their arithmetic rounds differently.
Step 1: Measure Variation
Create the exercise folder and activate the environment.
On macOS or Linux:
cd ~/agents-practice
source .venv/bin/activate
mkdir variation
cd variation
On Windows:
cd ~/agents-practice
.venv\Scripts\Activate.ps1
mkdir variation
cd variation
Save this as variation.py in ~/agents-practice/variation:
"""Send the same request ten times at three settings and count the different replies.
Before running, write down how many different replies you expect for each
setting. Usage: python variation.py
"""
import os
from collections import Counter
import httpx
HOST = os.environ.get("OLLAMA_HOST", "127.0.0.1:11434")
CHAT_URL = (HOST if HOST.startswith("http") else f"http://{HOST}") + "/api/chat"
MODEL = "granite4.1:3b"
PROMPT = "Suggest a two-word name for a camping stove. Reply with the name only."
RUNS = 10
SETTINGS = {
"temperature 0.8, seed 42": {"temperature": 0.8, "seed": 42},
"temperature 0.8, no seed": {"temperature": 0.8},
"temperature 0": {"temperature": 0},
}
def reply(options):
response = httpx.post(CHAT_URL, timeout=120, json={
"model": MODEL, "stream": False, "options": {**options, "num_ctx": 8192},
"messages": [{"role": "user", "content": PROMPT}]})
response.raise_for_status()
return response.json()["message"]["content"].strip()
for label, options in SETTINGS.items():
replies = Counter(reply(options) for _ in range(RUNS))
print(f"{label}: {len(replies)} different in {RUNS}")
for text, count in replies.most_common():
print(f" {count} x {text}")
PROMPTasks for something with many acceptable answers: a name for a camping stove. Questions with one right answer vary much less.SETTINGSare the three settings to compare: temperature 0.8 with a fixed seed, temperature 0.8 without one, and temperature 0.reply()sends one request with the given options plus the course's context size, and returns the stripped reply text.- The loop sends ten requests per setting and uses
Counterto count how often each distinct reply appeared.
Before you run it, write down how many different replies you expect out of ten for each setting. Then run it:
python variation.py
This was the first recorded run:
temperature 0.8, seed 42: 1 different in 10
10 x CamoStove
temperature 0.8, no seed: 3 different in 10
7 x CampStove
2 x Everest
1 x TrailMaster
temperature 0: 1 different in 10
10 x CampStove
Compare the counts with your predictions. The run above was recorded with Python 3.13. The same script, run again a few minutes later with Python 3.12, against the same server and model, printed this:
temperature 0.8, seed 42: 2 different in 10
9 x CamoStove
1 x Backpacker
temperature 0.8, no seed: 5 different in 10
6 x CampStove
1 x TrailMate
1 x Backpacker
1 x Firestove
1 x Everest
temperature 0: 1 different in 10
10 x CampStove
Temperature 0 gave one reply in both runs. Without a seed, temperature 0.8
gave three different replies in one run and five in the other. With seed 42,
it gave one reply in the first run, but two in the second, and the odd one
out, Backpacker, also appeared in an earlier test of the same request. So
a seed narrowed the variation without removing it, and a single run of ten
could not tell you which behaviour to expect. The interpreter did not cause
the difference: the script only sends requests, and the server and model
were the same.
Step 2: Limit the Length of a Reply
num_predict sets the most tokens the model may write. When it runs out,
the reply simply stops, mid-sentence if need be, and done_reason is
length instead of stop. Agents use a limit like this to keep a runaway
reply from costing time, but a limit that is too small silently cuts useful
output.
Save this as length.py in the same folder:
"""Ask for one sentence with a limit on the number of tokens the model may write.
Usage: python length.py 40 # allow at most 40 output tokens
"""
import os
import sys
import httpx
HOST = os.environ.get("OLLAMA_HOST", "127.0.0.1:11434")
CHAT_URL = (HOST if HOST.startswith("http") else f"http://{HOST}") + "/api/chat"
MODEL = "granite4.1:3b"
PROMPT = "In one sentence, explain why a tent needs a groundsheet."
limit = int(sys.argv[1]) if len(sys.argv) > 1 else 40
response = httpx.post(CHAT_URL, timeout=120, json={
"model": MODEL, "stream": False, "options": {"temperature": 0, "num_ctx": 8192, "num_predict": limit},
"messages": [{"role": "user", "content": PROMPT}]})
response.raise_for_status()
data = response.json()
print(f"num_predict {limit}: done_reason {data['done_reason']}, eval_count {data['eval_count']}")
print(data["message"]["content"])
Run it with a few limits:
python length.py 5
python length.py 20
python length.py 40
num_predict 5: done_reason length, eval_count 5
A groundsheet prevents water
num_predict 20: done_reason length, eval_count 20
A groundsheet prevents water, dirt, and moisture from seeping up into the tent from the ground
num_predict 40: done_reason stop, eval_count 29
A groundsheet prevents water, dirt, and moisture from seeping up into the tent from the ground, maintaining a dry and comfortable interior.
At 5 and 20 tokens the reply stopped mid-sentence with done_reason
length. At 40 the model finished on its own after 29 tokens: done_reason
is stop, and the limit was never reached.
A reply that ends with done_reason length is incomplete, whatever it
looks like. Programs must check done_reason, not the text.
Choosing num_ctx
num_ctx sets the context window: the most tokens the conversation and the
reply may use together. A larger window lets a request hold more, but the
server reserves memory for all of it. On the author's computer Ollama
reported 2.8 GB in use for this model at 8,192 tokens, 4.9 GB at 32,768 and
7.7 GB at 65,536. Ollama's documentation suggests at least 64,000 tokens for
agents; on an 8 GB laptop that would not fit, and the course's tasks need far
less, so lessons use 8,192. The danger of a window that is too small is that
Ollama cuts the conversation silently: the request succeeds and the
answer is simply worse. A later lesson measures this and shows how to detect
it.
Thinking Output
Some models can write out intermediate reasoning, "thinking", before their
answer. In Ollama you ask for it with the request field "think": true, and
it comes back in a separate field of the message, message.thinking, beside
message.content; when streaming, thinking chunks arrive before answer
chunks. Ollama's documentation shows this with models built for it.
/api/show reports whether a model supports thinking.
The course model has no thinking mode. Asking for it is an error:
$ curl http://127.0.0.1:11434/api/chat -d '{"model":"granite4.1:3b","stream":false,"think":true,"messages":[{"role":"user","content":"hi"}]}'
{"error":"\"granite4.1:3b\" does not support thinking"}
The status code is 400, Bad Request: the request asked for something this model cannot do.
If you later use a model that thinks, two habits from this course carry
over: keep message.thinking out of anything you show users or resend
without reason, because it can be long, and judge the model by its answer and
its tool calls, not by how convincing its reasoning reads.
When the Result Differs
| What you see | Likely cause | Next check |
|---|---|---|
| More than one reply at temperature 0 | Possible, though rare in the recording | Run again; compare the replies; this is why one run proves little |
| Exactly the same counts as the recording | Also possible: same model build, same settings | Not a guarantee for any other computer |
| The seeded setting gives ten identical replies | Your run started from the same state each time | Compare with the unseeded count; the seed still narrowed the variation |
length.py 40 ends with length | Your build writes longer sentences | Try 60; then shorten the prompt's request |
HTTPStatusError 500 mentioning an option | A string where a number belongs, such as "0.8" | Use numbers in options |
Your Turn: Find the Smallest Useful Limit
Find the smallest num_predict for which length.py still returns a
complete one-sentence answer, ending with done_reason stop. Then explain:
- why the reply at a smaller limit can look like a finished sentence but
still be marked
length; - what an agent should do when a reply it needs ends with
length.
Success means you report the limit, the eval_count at that limit, and
both explanations.
Clean Up
Remove the exercise folder, and only that folder. On macOS or Linux:
cd ~/agents-practice
[ "$(pwd)" = "$HOME/agents-practice" ] && rm -r variation
On Windows:
cd ~/agents-practice
if ((Get-Location).Path -eq (Join-Path $HOME 'agents-practice')) { Remove-Item -Recurse variation }
Check Your Understanding
- In the recording, ten requests at temperature 0.8 with seed 42 gave two different replies, and the first reply was the odd one out. How can the same seed and settings give a different first reply?
- Given that replies vary, what does this course do so that its exercises and tests still mean something?
Answer and Reasoning
Your turn
In the recorded run the reply was complete at 30 tokens: 29 were used and
done_reason was stop. At 25 it ended "maintaining a dry and", marked
length. Your number may differ by a few tokens.
- A limit can fall just after a full stop, or at the end of a clause that
reads like a sentence, so the text looks finished while the model still had
more to write. Only
done_reasonsays whether the model stopped by itself. - Treat the reply as incomplete: either ask again with a higher limit, or
ask for a shorter reply, and never act on the cut-off text as if it were
the whole answer. The second API format, later in the course, reports
the same thing as
stop_reasonmax_tokens.
Check your understanding
- The seed fixes where the random choices start, but the result also depends on the state of the server: how it batches and caches requests, and tiny numerical differences in how the probabilities are computed. In the recordings the same seeded request gave one reply ten times in one run and two different replies in others. Ollama does not promise identical output, and a small difference in the first token changes the whole reply.
- The course uses temperature 0 for exercises, so runs usually agree; labels recorded model output as illustrative and states the model and version; tests agent code with a scripted stand-in model whose replies are fixed; and judges real model behaviour over repeated runs, reported with counts and, later, with uncertainty, never from a single run.
References
- Ollama API: Generate a chat message:
options(temperature,seed,num_predict,num_ctx,top_k,top_p,min_p),thinkandlogprobs. - Ollama API: Usage:
eval_countand the other usage fields. - Ollama: Context length: defaults, memory and the suggestion for agents.
- Ollama: Thinking: the
thinkfield,message.thinkingand/api/show. - HTTPX: Timeouts: used by the request helper.