Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 03 · 40 minutes

Run a language model on your own machine

After this lesson you can
  • Install Ollama the careful way and pull a small model that runs on a CPU
  • Send a chat to the model from Python and read the reply
  • Make a run repeatable and read the token counts and the speed
Lab files of this lesson (10)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Your company wants to test a chatbot model without sending customer text to a vendor. Your lead wants a test bench: a model on your laptop, a small program that talks to it, and numbers for speed and tokens. Every later lesson and the attack labs of the next courses use this bench. You build it and prove that it works.

Recall

What does temperature 0 do to the choice of the next token?

The program always takes the most likely token, so the output is the same on every run.

What happens to a message that does not fit in the context window?

It does not exist for the model. The program (or the service) drops it, usually the oldest one, and the model does not say so.

The idea

A language model is a big file of numbers (its weights). A runtime loads the file and runs the prediction loop of lesson 1. Ollama is a runtime with a small server. It listens on your own computer only, at http://127.0.0.1:11434, and answers in JSON (a text format for data).

The course model is llama3.2:3b: about 3 billion weights, stored with fewer bits for each number, so that the file is smaller (quantised): 2 GB. It runs on an ordinary CPU, slowly: a few to ten tokens per second. It is far weaker than the big services, so its mistakes are plain to see.

Your Python program talks to the server with plain HTTP. The helper llm.py hides it behind one function, chat.

What happens when you call chat()
Your scriptchat()Ollama serverModela list of messagesone JSON request to 127.0.0.1the prompt, as tokensthe answer, token by tokenreply, counts and timingthe text of the answerYour scriptchat()Ollama serverModel123456
  1. Your script → chat(): a list of messages
  2. chat() → Ollama server: one JSON request to 127.0.0.1
  3. Ollama server → Model: the prompt, as tokens
  4. Model → Ollama server: the answer, token by token
  5. Ollama server → chat(): reply, counts and timing
  6. chat() → Your script: the text of the answer
Option of chatMeaning
messagesThe conversation, a list of {"role": ..., "content": ...}.
temperatureRandomness of sampling (lesson 1). Default 0.
seedFixes the random draws. Default 1.
max_tokensThe most tokens in the answer. Default 300.
as_jsonAsk for an answer that is valid JSON. Lesson 4.
fullReturn the whole reply with counts and timing, not only the text.

Worked example

1. Install Ollama

This step needs root, so it is not tested here. Use the method for your system. Do not pipe a script from the web straight into a shell: you would run code that you have not read. On Linux, download the script to a file, read it, and then run it.

curl fetches a web address. The options are -f (fail on an HTTP error), -s (silent), -S (show errors), -L (follow redirects) and -o install.sh (write to this file). less shows a file page by page, and q quits.

mkdir -p ~/krlab/ollama-install
cd ~/krlab/ollama-install
curl -fsSL -o install.sh https://ollama.com/install.sh
less install.sh

Read it. When this lesson was written, the script downloaded the program archive from ollama.com, unpacked it under /usr/local, made a system user called ollama, wrote the service file /etc/systemd/system/ollama.service, and started that service, with sudo. Look for every address, every sudo line and every file. Your copy can differ. When you accept what it does, run it with sh (the shell). It asks for your password.

sh install.sh

On macOS and Windows, use the desktop application from ollama.com/download and open it once: it starts the server. If you run Python in WSL, install Ollama inside WSL with the Linux method, so that 127.0.0.1 is the same computer for both.

Then check that the program answers. ollama --version prints the version.

ollama --version
ollama version is 0.40.17

Your version number will be different. If the command says that it cannot connect to a server, see step 10.

2. Pull the model and list it

ollama pull downloads a model once. It takes minutes, because the file is 2 GB, and ends with the word success. ollama list shows the models on your machine, with an ID that is the digest of each file.

ollama pull llama3.2:3b
ollama list
pulling manifest
pulling dde5aa3fc5ff: 100% ▕██████████████████▏ 2.0 GB
...
verifying sha256 digest
writing manifest
success
NAME           ID              SIZE      MODIFIED
llama3.2:3b    a80c4f17acd5    2.0 GB    2 minutes ago

The output above comes from a machine that already had the model, shortened. With less than 8 GB of memory in total, pull llama3.2:1b (1.3 GB) and use it with export KR_MODEL=llama3.2:1b. export sets an environment variable (a named setting that programs can read).

3. Run the lab check again

In the set-up lesson the server lines were information. Now they are requirements. Run labcheck.py with --model.

cd ~/krlab/llms-and-agents
python3 labcheck.py --model
ok   python  3.14.4
ok   folder  /home/you/krlab/llms-and-agents
ok   server  a model server answers
ok   model   llama3.2:3b is installed
lab ready: 4 of 4

4. Create the helper

Create llm.py in the lab folder. Four things in it are new. os.environ.get("KR_MODEL", "llama3.2:3b") reads a setting and gives a default if it is not set. json.dumps turns Python data into JSON text, and json.load reads JSON back. urllib.request sends the HTTP request. The * in the first line of chat means that every option after it must be written with its name, as in chat(messages, seed=2).

llm.py

"""llm.py: talk to a model that runs on your own machine (Ollama). Standard library only.

    from llm import chat
    print(chat([{"role": "user", "content": "Say hello."}]))

KR_MODEL chooses the model (default llama3.2:3b). temperature 0 and a fixed seed make a run
repeatable; small differences between machines and versions are normal.
"""
import json
import os
import urllib.request

URL = os.environ.get("KR_OLLAMA", "http://127.0.0.1:11434") + "/api/chat"
MODEL = os.environ.get("KR_MODEL", "llama3.2:3b")


def chat(messages, *, model=None, temperature=0.0, seed=1, max_tokens=300, as_json=False, full=False):
    """Send the messages and return the text of the answer.

    as_json=True asks the model for a JSON object. full=True returns the whole reply (token counts, timing).
    """
    options = {"temperature": temperature, "seed": seed, "num_predict": max_tokens}
    if os.environ.get("KR_THREADS"):
        options["num_thread"] = int(os.environ["KR_THREADS"])
    body = {"model": model or MODEL, "messages": messages, "stream": False, "options": options}
    if as_json:
        body["format"] = "json"
    req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as resp:
        reply = json.load(resp)
    return reply if full else reply["message"]["content"]
The HTTP request that chat() sends
POSTthe HTTP methodhttp://127.0.0.1:11434your own computer only/api/chatthe chat endpoint{"model", "messages", "options"}the JSON bodyPOSTthe HTTP methodhttp://127.0.0.1:11434your own computer only/api/chatthe chat endpoint{"model", "messages", "options"}the JSON body

5. Send the first chat

Create first.py. The first call after a pause is slower, because the server loads the 2 GB file.

first.py

from llm import chat

answer = chat([{"role": "user", "content": "In one sentence, what is a firewall?"}])
print(answer)
python3 first.py
A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules, blocking or allowing access to specific devices, applications, or services.

Your wording can differ.

6. Make a run repeatable

Create repeat.py. It asks the same question three times with temperature 0, and three times with temperature 1.0 and a different seed each time.

repeat.py

from llm import chat

question = [{"role": "user", "content": "Name one common cause of a data breach. Answer in at most ten words."}]

print("temperature 0, seed 1, three runs:")
for _ in range(3):
    print("  ", chat(question, max_tokens=40))

print("temperature 1.0, seeds 1, 2, 3:")
for seed in (1, 2, 3):
    print("  ", chat(question, temperature=1.0, seed=seed, max_tokens=40))
python3 repeat.py
temperature 0, seed 1, three runs:
   Phishing attacks are a common cause of data breaches.
   Phishing attacks are a common cause of data breaches.
   Phishing attacks are a common cause of data breaches.
temperature 1.0, seeds 1, 2, 3:
   Human error, often due to phishing or lack of training.
   Phishing emails and social engineering tactics are common attackers.
   Phishing attacks are a common cause of data breaches.

Temperature 0 gives the same text every time. Temperature 1.0 gives a different text for each seed, and the same seed gives the same text again. For tests, fix both.

7. Read the token counts and the speed

full=True returns the whole reply as a dictionary, with counts and times. reply["eval_duration"] is the time of the answer in nanoseconds, and / 1e9 gives seconds. Create stats.py.

stats.py

from llm import chat

reply = chat([{"role": "user", "content": "List three Linux commands that show open network ports."}], full=True, max_tokens=60)

print(reply["message"]["content"])
print()
print("tokens in the prompt: ", reply["prompt_eval_count"])
print("tokens in the answer: ", reply["eval_count"])
seconds = reply["eval_duration"] / 1e9
print(f"answer time:           {seconds:.1f} s")
print(f"speed:                 {reply['eval_count'] / seconds:.1f} tokens per second")
print("why it stopped:       ", reply["done_reason"])
python3 stats.py
Here are three Linux commands that can help you show open network ports:

1. `netstat -tlnp`: This command displays active network connections, including open ports. The `-t` option shows only TCP connections, `-l` shows only listening sockets, and `-n` shows numerical addresses

tokens in the prompt:  35
tokens in the answer:  60
answer time:           9.7 s
speed:                 6.2 tokens per second
why it stopped:        length

The answer stops in the middle of a sentence because max_tokens was 60 and done_reason says length. When it says stop, the model ended on its own. The prompt is 35 tokens, although the question has only 9 words: the chat format adds a fixed header.

8. Count real tokens

Now compare words and real tokens, as lesson 2 promised. Create count.py. The function subtracts the count of an empty message to remove the fixed header, and it asks for one token of answer, so it is fast. The empty count is taken once, at the start.

count.py

from llm import chat


def count(text):
    return chat([{"role": "user", "content": text}], full=True, max_tokens=1)["prompt_eval_count"]


EMPTY = count("")   # the chat template adds a fixed overhead: this is its size


def tokens(text):
    """Real token count of a text, without the fixed overhead."""
    return count(text) - EMPTY


samples = {
    "plain prose": "The analyst reset the password. Then the analyst found an authentication error.",
    "numbers": "203.0.113.7 198.51.100.23 192.0.2.44 10.0.0.1 172.16.5.9",
    "random": "xqzv kjwp zzqx vbnm qwrt plmk",
    "base64": "VGhlIGFuYWx5c3QgcmVzZXQgdGhlIHBhc3N3b3Jk",
}
for name, text in samples.items():
    print(f"{name:12} {len(text.split()):3} words {len(text):3} characters {tokens(text):3} tokens")
python3 count.py
plain prose   12 words  79 characters  14 tokens
numbers        5 words  56 characters  39 tokens
random         6 words  29 characters  14 tokens
base64         1 words  40 characters  29 tokens
Real tokens of four short texts
Plain prose, 79 characters145 IP addresses, 56 characters39Random words, 29 characters14Base64, 40 characters29Plain prose, 79 characters145 IP addresses, 56 characters39Random words, 29 characters14Base64, 40 characters29

Prose costs about one token for each word. Code and data fill a window much faster.

9. Read the window that the server loaded

The model file allows far more tokens than your server may use. ollama ps lists the models in memory. Its column CONTEXT is the real window.

ollama ps
NAME           ID              SIZE      PROCESSOR    CONTEXT    UNTIL
llama3.2:3b    a80c4f17acd5    2.8 GB    100% CPU     4096       4 minutes from now

This is a sample: the machine that wrote this course showed 4096, not the 131,072 of the file, and your size and time differ. A longer prompt is cut with no error: the oldest text is dropped, and you cannot see what was lost. To change the window, use the option num_ctx; this course does not need it. The prompts of this course stay well below 4,096 tokens. When you add long documents, count their tokens first (step 8).

10. Fix a failure

What you seeWhat it meansWhat to do
urllib.error.URLError with Connection refused, or FAIL serverNo server listens at 127.0.0.1:11434.Open the Ollama app, or run ollama serve in another terminal (Linux with the service: systemctl status ollama).
Connection refused or a proxy error although the server runsYour shell has http_proxy set, and Python sends the request to 127.0.0.1 through the proxy.Set NO_PROXY=127.0.0.1 in the shell (export NO_PROXY=127.0.0.1) and run again.
ollama serve says the address is in useA server already runs on that port.Use it. Do not start a second one.
pull stops with an error about disk spaceThe disk is full.Free 3 GB and run ollama pull again. It continues where it stopped.
The server says that the model needs more memoryYour available memory is too small for the 3b model.Pull llama3.2:1b and set KR_MODEL=llama3.2:1b.
KeyError: 'prompt_eval_count'An older server leaves this field out when it holds the whole prompt in its cache. The server of this course returned it every time, also for the same text three times in a row.Update Ollama, or add a word that is new to the text and run again.
The first call times out after 300 sThe model is still loading, or the machine is slow.Run the program again, or use the 1b model.

Your turn

Use your bench on new data. You adapt count.py and stats.py. Importing count.py runs its demo and makes model calls: copy count and tokens into a new file, or import them and ignore the demo.

  1. Count the real tokens of these two texts with tokens:
    • ssh -p 2222 admin@198.51.100.7
    • 2026-11-21T08:14:03Z WARN auth failed user=root src=203.0.113.9
  2. Ask the model "List three common causes of slow Wi-Fi." with max_tokens=5, and read done_reason.
  3. Run python3 labcheck.py --model and type its last line.

Last, run the question of item 2 with max_tokens=60 and write down the speed in tokens per second, with the model name and its ID from ollama list. The page does not check it: your machine decides it.

Check yourself

Why does a run at temperature 0 with a fixed seed give the same text, and why can it still differ on another machine?

At temperature 0 there is no random choice, and the seed fixes any draw that remains. The calculation still uses floating-point numbers, and another CPU or runtime version can round in another way. A small change can move one token and then change all that follows.

`done_reason` is "length". What does that tell you about the answer?

The answer was cut at max_tokens, so it is probably incomplete. An incomplete answer fails when you parse it (for example as JSON). Check done_reason or raise the limit.

The server address is 127.0.0.1. Why is this a good default?

It accepts connections from your own computer only. Ollama has no login, so on all addresses anyone who can reach the port could use your model and your CPU.

Field notes

  • Pin the model. llama3.2:3b is a name that can point to a new build later. Record the digest from ollama list (the ID column) with your test results.
  • The Ollama server has no authentication. Bind it to 127.0.0.1, or put a reverse proxy with authentication in front of it. Never expose it to the internet.
  • Treat an installer and a model file like a program that you download: read a script before you run it, take the model from the publisher's registry and check the digest. Some model file formats (Python pickle) can run code when you load them; prefer GGUF or safetensors.
  • A model has a licence. Read it before you use a model at work. llama3.2 comes under the Llama 3.2 Community Licence of Meta and its acceptable use policy.
  • Small quantised models follow rules less well than big services. Test the model that you deploy.