What You Will Build
Every agent in this course is built from one operation: sending the model a conversation and reading its reply. In this lesson you send that request yourself, from Python, and account for every field that comes back. You will:
- send plain HTTP requests and read their status codes and bodies;
- write
request.py, which sends one chat request and explains each field of the response with its unit; - predict how a system message changes the number of tokens the model reads, and check the prediction;
- compute how fast the model wrote its reply, and tell from a response whether the model was already loaded.
Before you start, the readiness check from the previous lesson must pass. Allow about 40 minutes. Each request in this lesson takes a second or two with a GPU and a few seconds without one.
Model output shown in this lesson is illustrative: the author's runs
with granite4.1:3b on Ollama 0.40.7, with the settings in the code shown.
Your wording, ids and times can differ; the text after each output says
what should match.
Bridge: HTTP Requests and Responses
Your programs talk to Ollama with HTTP, the same protocol a web browser uses. A request has:
- a method:
GETto read something,POSTto send data for processing; - a URL: here
http://127.0.0.1:11434/api/version, which names the protocol (http), the computer (127.0.0.1, this one), the port (11434, Ollama's) and the path (/api/version, what you want); - optionally a body: for Ollama, a JSON document describing the request.
The server answers with a response:
- a status code:
200means success; codes from 400 to 499 mean the request was wrong (400 Bad Request,404 Not Found); codes from 500 to 599 mean the server failed to handle it; - headers, such as
content-type, which says what kind of body follows; - a body: for Ollama, normally JSON.
A client also decides how long to wait, its timeout. httpx waits at most five seconds for each step by default, which is too short for a model that may need longer to write a reply, so every course script sets its own.
Start with two requests that involve no model at all. Create the exercise folder and activate the environment.
On macOS or Linux:
cd ~/agents-practice
source .venv/bin/activate
mkdir first-request
cd first-request
On Windows:
cd ~/agents-practice
.venv\Scripts\Activate.ps1
mkdir first-request
cd first-request
Save this as http_basics.py in ~/agents-practice/first-request:
"""Two plain HTTP requests to the local Ollama server, before any model is involved."""
import os
import httpx
HOST = os.environ.get("OLLAMA_HOST", "127.0.0.1:11434")
BASE = HOST if HOST.startswith("http") else f"http://{HOST}"
for path in ("/api/version", "/api/no-such-page"):
response = httpx.get(BASE + path, timeout=10)
print(response.request.method, response.request.url)
print("status:", response.status_code, response.reason_phrase)
print("content type:", response.headers.get("content-type"))
print("body:", response.text)
print()
The address comes from OLLAMA_HOST if it is set, otherwise
127.0.0.1:11434, as in the setup lessons. The program sends a GET to two
paths and prints what came back. Run it with python http_basics.py. This
was the recorded output (the author's test server used another port):
GET http://127.0.0.1:11545/api/version
status: 200 OK
content type: application/json; charset=utf-8
body: {"version":"0.40.7"}
GET http://127.0.0.1:11545/api/no-such-page
status: 404 Not Found
content type: text/plain
body: 404 page not found
The first request succeeded: status 200, a JSON body. The second asked for
a path that does not exist and got 404 with a plain-text body. The server
answered both; the status code, not whether an answer arrived, says whether
the request worked. That is why course scripts call
response.raise_for_status(), which turns any 4xx or 5xx status into a
Python exception instead of letting the program carry on with an error body.
Bridge: Words for Model Requests
The chat request uses a few terms from the first lesson. Here is what each means in practice:
- Tokens. The model reads and writes tokens, pieces of text. In English a token is often a short word or part of one; the exact split depends on the model. The response counts them: tokens read and tokens written.
- Context window. The most tokens one request can hold, conversation and
reply together. You choose it with the
num_ctxoption; the course uses 8,192. A conversation that grows past it is cut, which a later lesson shows and measures. - System message. Standing instructions in a message with the role
system. It is text like any other, so it costs tokens on every request. - Sampling and temperature. The model writes one token at a time,
choosing from the tokens it rates as likely. Temperature controls how
adventurous that choice is; at
0it always takes the most likely token. Course exercises use0so runs usually agree; the next lesson measures what that does and does not guarantee. - Stop reason.
done_reasonsays why writing stopped:stopwhen the model finished,lengthwhen it hit a limit you set.
The model's reply is a prediction of likely text, made from patterns learned in training and the conversation you send. It is not looked up anywhere. That is why a reply can be fluent, confident and wrong.
Step 1: Send One Chat Request
Save this as request.py in the same folder:
"""Send one chat request to the local model and explain every field of the reply.
Usage:
python request.py # the question only
python request.py --system # the same question with a system message first
"""
import json
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"
OPTIONS = {"temperature": 0, "num_ctx": 8192}
SYSTEM = "You work at a camping-equipment rental desk. Answer in one short sentence."
QUESTION = "What should I bring to keep warm on a night in a tent?"
def chat(messages):
response = httpx.post(CHAT_URL, timeout=120, json={
"model": MODEL, "messages": messages, "stream": False, "options": OPTIONS})
response.raise_for_status()
return response.json()
def explain(data):
seconds = {name: data[name] / 1e9 for name in
("total_duration", "load_duration", "prompt_eval_duration", "eval_duration")}
rows = [
("model", data["model"], "the model that answered"),
("message.role", data["message"]["role"], "who wrote the reply"),
("message.content", data["message"]["content"], "the reply text"),
("done", data["done"], "true: this is the whole reply"),
("done_reason", data["done_reason"], "stop: finished; length: hit the num_predict limit"),
("prompt_eval_count", data["prompt_eval_count"], "tokens read from the conversation"),
("prompt_eval_cached_count", data.get("prompt_eval_cached_count", 0),
"of those, tokens reused from the previous request"),
("eval_count", data["eval_count"], "tokens written in the reply"),
("load_duration", f"{seconds['load_duration']:.3f} s", "loading the model into memory"),
("prompt_eval_duration", f"{seconds['prompt_eval_duration']:.3f} s", "reading the conversation"),
("eval_duration", f"{seconds['eval_duration']:.3f} s", "writing the reply"),
("total_duration", f"{seconds['total_duration']:.3f} s", "the whole request on the server"),
]
for name, value, meaning in rows:
print(f"{name:25} {value}")
print(f"{'':25} ({meaning})")
speed = data["eval_count"] / seconds["eval_duration"]
print(f"{'output speed':25} {speed:.1f} tokens/s (eval_count / eval_duration)")
def main():
messages = [{"role": "user", "content": QUESTION}]
if "--system" in sys.argv:
messages.insert(0, {"role": "system", "content": SYSTEM})
print("request messages:", json.dumps(messages))
explain(chat(messages))
if __name__ == "__main__":
main()
How the Program Works
chat()POSTs a JSON body to/api/chat: the model's name, the list of messages,"stream": falseand the options./api/chatstreams its reply as many small JSON objects unless you ask otherwise;"stream": falseasks for one complete object, which is easier to read. The options set temperature0and an 8,192-token context. The timeout is 120 seconds, because the first request may wait for the model to load.raise_for_status()stops the program with an exception if the server reports an error.explain()prints every field with a one-line meaning. Ollama reports durations in nanoseconds (billionths of a second), so the program divides by1e9to show seconds. The output speed is the number of tokens written divided by the time spent writing them.main()builds the conversation: the question alone, or, with--system, a system message first. It prints the messages it sends, then the explanation of the reply.
Run it:
python request.py
This was the recorded output; the wording of the reply, the counts and the timings on your computer will differ:
request messages: [{"role": "user", "content": "What should I bring to keep warm on a night in a tent?"}]
model granite4.1:3b
(the model that answered)
message.role assistant
(who wrote the reply)
message.content When spending a night in a tent, especially in cooler weather, it's essential to bring items that will help you stay warm and comfortable. Here are some recommendations:
1. **Insulating Sleeping Bag**: Choose a sleeping bag rated for the expected temperature range. A bag rated for at least 10-15 degrees Fahrenheit below the lowest temperature you expect to encounter will provide adequate warmth.
[... suggestions 2 to 4 shortened ...]
5. **Heating Devices**: Consider bringing a portable space heater designed for outdoor use (make sure it's safe for use in a tent and follow all manufacturer instructions). Alternatively, a chemical heat pack can provide localized warmth.
[... suggestions 6 to 10 and a closing paragraph shortened ...]
(the reply text)
done True
(true: this is the whole reply)
done_reason stop
(stop: finished; length: hit the num_predict limit)
prompt_eval_count 22
(tokens read from the conversation)
prompt_eval_cached_count 1
(of those, tokens reused from the previous request)
eval_count 422
(tokens written in the reply)
load_duration 0.002 s
(loading the model into memory)
prompt_eval_duration 0.135 s
(reading the conversation)
eval_duration 35.455 s
(writing the reply)
total_duration 35.615 s
(the whole request on the server)
output speed 11.9 tokens/s (eval_count / eval_duration)
Read it in groups:
- The reply:
message.roleisassistantandmessage.contentis the text.doneis true anddone_reasonisstop: the model finished on its own. - The token counts:
prompt_eval_countis 22, although the question has only 13 words: some words take more than one token, and Ollama wraps each message in markers that tell the model who is speaking, which count too.prompt_eval_cached_countis 1: almost nothing was reused from the previous request.eval_countis 422, a long reply, because nothing asked for a short one. - The timings:
load_durationis 0.002 seconds, so the model was already in memory. Reading 22 tokens took 0.135 seconds, and writing 422 took 35.5 seconds, 11.9 tokens per second. That is slow for this computer: other programs were keeping its processor very busy during the recording. The next request, a minute later, wrote 29 tokens per second. Timings tell you about one moment on one machine.
Read the content as well as the numbers. Suggestion 5 recommends a portable space heater in a tent, hedged with "make sure it's safe". Heaters inside tents are a known fire and carbon-monoxide risk, and a rental desk would not give that advice without checking it. The list is fluent, numbered and confident, and part of it is advice to question: that is what "a reply is a prediction, not a fact" means in practice.

Every field of one request and its response. The values are from the recorded run with a system message in Step 2.
Step 2: Add a System Message
Before you run the next command, predict two things and write them down:
- Will
prompt_eval_countgo up or down when a system message is added, and by roughly how much? The system message is "You work at a camping-equipment rental desk. Answer in one short sentence.", fourteen words. - How will the reply change?
Then run:
python request.py --system
request messages: [{"role": "system", "content": "You work at a camping-equipment rental desk. Answer in one short sentence."}, {"role": "user", "content": "What should I bring to keep warm on a night in a tent?"}]
model granite4.1:3b
(the model that answered)
message.role assistant
(who wrote the reply)
message.content Bring a sleeping bag, warm layers, and a blanket.
(the reply text)
done True
(true: this is the whole reply)
done_reason stop
(stop: finished; length: hit the num_predict limit)
prompt_eval_count 43
(tokens read from the conversation)
prompt_eval_cached_count 1
(of those, tokens reused from the previous request)
eval_count 13
(tokens written in the reply)
load_duration 0.005 s
(loading the model into memory)
prompt_eval_duration 0.367 s
(reading the conversation)
eval_duration 0.448 s
(writing the reply)
total_duration 0.842 s
(the whole request on the server)
output speed 29.0 tokens/s (eval_count / eval_duration)
prompt_eval_count rose from 22 to 43. The
fourteen-word system message added 21 tokens: its words plus the markers
around one more message. The reply changed far more: 13 tokens instead of
422, one sentence as instructed, and the whole request took 0.84 seconds
instead of 35.6. A system message costs a few tokens on every request and can
change both the content and the cost of the reply. If your prediction said
the count would rise by about the system message's length, it was right; the
exact number depends on how this model splits words into tokens.
When the Result Differs
| What you see | Likely cause | Next check |
|---|---|---|
httpx.ConnectError | Ollama is not running, or OLLAMA_HOST points elsewhere | ollama ps; check OLLAMA_HOST |
HTTPStatusError with 404 Not Found | The model is not pulled | ollama pull granite4.1:3b |
json.decoder.JSONDecodeError: Extra data | "stream": false is missing, so many JSON objects arrived | Check the request body in chat() |
KeyError: 'done_reason' or another field | A different Ollama version, or a streamed chunk read as a whole reply | ollama -v; check "stream": false |
load_duration of several seconds | The model was loaded for this request | Normal for the first request; run again within five minutes |
httpx.ReadTimeout | The reply took longer than 120 seconds | Check ollama ps for 100% CPU and close heavy programs |
| Very different token counts | Normal: different model builds split text differently | Compare differences between your own runs, not with the recording |
Your Turn: Add a Second Turn
A follow-up question such as "Which one of those matters most?" only makes
sense with the first answer in view. Write follow_up.py, which sends
QUESTION, adds the reply and the follow-up to the conversation, and sends
it again. Print prompt_eval_count for both requests and, for the second,
prompt_eval_cached_count.
Before running it, predict: will the second request's
prompt_eval_count be larger or smaller than the first's, and roughly by
how much? What might prompt_eval_cached_count show?
Success means the second reply answers the follow-up in the context of the first, and you can explain both counts. If you are stuck:
- Import
QUESTIONandchatfromrequest.pyinstead of copying them. chat()returns the whole response; the reply to append isresponse["message"].- The second conversation is the first question, the first reply, then the follow-up, in that order.
Clean Up
Remove the exercise folder, and only that folder. On macOS or Linux:
cd ~/agents-practice
[ "$(pwd)" = "$HOME/agents-practice" ] && rm -r first-request
On Windows:
cd ~/agents-practice
if ((Get-Location).Path -eq (Join-Path $HOME 'agents-practice')) { Remove-Item -Recurse first-request }
Check Your Understanding
- A recorded reply had
eval_count13 and aneval_durationof about 448,000,000. How fast did the model write, in tokens per second? - That reply's
load_durationwas about 5,000,000. A request sent straight after the model had been unloaded had aload_durationof about 1,600,000,000. What do the two values tell you, and what would you expect on a laptop without a GPU?
Answer and Reasoning
Your turn
Save this as follow_up.py to compare with your version:
"""Ask a question, then a follow-up that only makes sense with the first answer."""
from request import QUESTION, chat
FOLLOW_UP = "Which one of those matters most?"
messages = [{"role": "user", "content": QUESTION}]
first = chat(messages)
messages += [first["message"], {"role": "user", "content": FOLLOW_UP}]
second = chat(messages)
print("turn 1 prompt_eval_count:", first["prompt_eval_count"], " eval_count:", first["eval_count"])
print("turn 2 prompt_eval_count:", second["prompt_eval_count"],
" cached:", second.get("prompt_eval_cached_count", 0))
print("turn 2 reply:", second["message"]["content"])
It imports the question and chat() from request.py, so both programs
send identical requests. The second conversation holds the first question,
the first reply (first["message"], appended as it arrived) and the
follow-up. The recorded output, with the reply shortened:
turn 1 prompt_eval_count: 22 eval_count: 422
turn 2 prompt_eval_count: 460 cached: 443
turn 2 reply: The most critical item to bring to keep warm on a night in a tent is an **insulating sleeping bag** rated for the expected temperature range. A properly rated sleeping bag will provide the primary barrier against the cold ground and ambient temperature, significantly affecting your [...]
The second request read 460 tokens: the 22 of the first question, the 422 of
the first reply and the follow-up with its markers. It would have been much
slower to read, except that prompt_eval_cached_count is 443: Ollama still
held the first request's work, including the reply it had just written, so
only the new tokens at the end had to be processed. The cache helps only
while the start of the conversation is unchanged and the model is still
loaded. The reply named the sleeping bag, which makes sense only with the
first answer in view.
Check your understanding
- 448,000,000 nanoseconds is 0.448 seconds, so 13 / 0.448 is about 29 tokens per second.
- 5,000,000 nanoseconds is 0.005 seconds: the model was already in memory. 1,600,000,000 is 1.6 seconds spent loading it, on a computer with a GPU and a fast disk. On a laptop without a GPU, or after the model has been unloaded for longer, loading can take much longer, which is one reason course scripts allow 120 seconds.
References
- Ollama API: Generate a chat message: the request body,
stream,optionsand the response fields. - Ollama API: Usage: the token counts and durations, all in nanoseconds.
- HTTPX: Timeouts and Exceptions: the default five-second timeout and
raise_for_status(). - Granite 4.1 3B model card: what the model is for and its stated limitations.