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

Set-up · 15 minutes

Set up your lab for Securing LLM applications

After this lesson you can
  • Create the lab folder of the course
  • Confirm that the local model server and the model llama3.2:3b are ready
  • Prove with a check script that the lab is ready
Lab files of this lesson (1)

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. Type the code yourself first: you learn more.

What you need

  • The course "How LLMs and agents work". Finish its lesson 3 first. There you install the model server (Ollama) and the model llama3.2:3b. This course attacks and defends a small chatbot that runs on that model.
  • Python at the level of the course "Python for security work", lessons 1 to 8: functions, dictionaries, files and JSON, and a short class. Python 3.12 or later. Every program of this course uses the standard library only, so you install no package.
  • About 4 GB of free memory for the model, and no GPU. No account and no paid service.
  • Patience: a model on a CPU needs seconds for each answer, and some measurements in this course make dozens of calls. The "Your turn" tasks and their check answers never need the model, so you can finish all of them offline. The model is for the live measurements.

Everything runs on your own computer, in one folder: ~/krlab/securing-llm-apps. The model server listens on your own computer only (127.0.0.1). This course is defensive: the only application that you attack is the one that you build in the lab, and the only model is your local one.

The lab on your computer
Your computer onlyLab scriptsOllama serverModel llama3.21234Your computer onlyLab scriptsOllama serverModel llama3.21234
  1. Lab scripts → Ollama server: chat request to 127.0.0.1:11434
  2. Ollama server → Model llama3.2: the model reads the messages
  3. Model llama3.2 → Ollama server: the next words, one by one
  4. Ollama server → Lab scripts: the answer text

Set it up

1. Make the lab folder

mkdir -p (make directory, with its parents) creates the folder. cd (change directory) moves you into it. pwd (print working directory) shows where you are.

mkdir -p ~/krlab/securing-llm-apps
cd ~/krlab/securing-llm-apps
pwd
/home/you/krlab/securing-llm-apps

You can type every file of this course from the lessons. As a shortcut, the course page has a button "Lab files" for a zip. The zip keeps the files of each lesson in a folder of that lesson, and the course works in one flat folder, so the zip holds a script, kr-lab.sh. It copies the files of all lessons up to the lesson that you name, and the folder of a lesson has the name of its file without .md. The browser saves the zip as kalirange-securing-llm-apps.zip, usually in your Downloads folder. unzip opens it. Then go into the unzipped folder securing-llm-apps and run the script. This example builds the lab as it stands after lesson 5. If unzip is missing, replace its line with python3 -m zipfile -e kalirange-securing-llm-apps.zip ..

cd ~/Downloads
unzip kalirange-securing-llm-apps.zip
cd securing-llm-apps
sh kr-lab.sh 05-treat-model-output-as-untrusted ~/krlab/securing-llm-apps
cd ~/krlab/securing-llm-apps
lab ready in /home/you/krlab/securing-llm-apps (after 05-treat-model-output-as-untrusted)

2. Start the model server

If you did lesson 3 of "How LLMs and agents work", the server runs already as a service. Ask it for the list of models with curl (a program that sends a web request). The option -s (silent) hides the progress bar.

curl -s http://127.0.0.1:11434/api/tags

The reply is a block of JSON that holds the name llama3.2:3b. If you get no reply, start the server in another terminal with ollama serve, and if the name is missing, run ollama pull llama3.2:3b.

Check your lab

The script labcheck.py proves that the lab works. It checks five things and prints one line for each: the Python version, the folder, the model server, the model and one real answer from the model. Some words in the script are new. sys.version_info holds the version of Python as numbers, so (3, 12) means 3.12. Path.home() is your home folder. urllib.request.urlopen sends a web request, here to your own computer. try and except run a step that can fail and catch the failure instead of stopping the program. The last check asks the model to say "OK" in at most 5 tokens. The first call can take a minute, because the model must load into memory. sys.exit(1) ends the program with exit code 1, which means "failed".

Create labcheck.py in the lab folder.

labcheck.py

"""labcheck.py: prove that the lab of "Securing LLM applications" works. Standard library only."""
import json
import os
import sys
import urllib.request
from pathlib import Path

SERVER = os.environ.get("KR_OLLAMA", "http://127.0.0.1:11434")
MODEL = os.environ.get("KR_MODEL", "llama3.2:3b")
results = []


def line(name, ok, detail):
    """Print one line for one requirement and remember the result."""
    results.append(ok)
    print(("ok   " if ok else "FAIL ") + name.ljust(8) + detail)


v = sys.version_info
line("python", v >= (3, 12), f"{v.major}.{v.minor}.{v.micro}")

folder = Path.home() / "krlab" / "securing-llm-apps"
line("folder", folder.is_dir(), str(folder))

try:
    with urllib.request.urlopen(SERVER + "/api/tags", timeout=3) as reply:
        installed = [m["name"] for m in json.load(reply)["models"]]
    server = True
except (OSError, ValueError, KeyError):
    installed, server = [], False
line("server", server, "a model server answers" if server else "no answer from " + SERVER)
line("model", MODEL in installed, f"{MODEL} is installed" if MODEL in installed else f"{MODEL} is not installed")

answered = False
if MODEL in installed:
    body = {"model": MODEL, "messages": [{"role": "user", "content": "Say OK."}], "stream": False, "options": {"num_predict": 5}}
    req = urllib.request.Request(SERVER + "/api/chat", json.dumps(body).encode(), {"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=180) as reply:
            answered = bool(json.load(reply)["message"]["content"].strip())
    except (OSError, ValueError, KeyError):
        pass
line("chat", answered, "the model answered" if answered else "the model did not answer (out of memory? try a smaller model)")

print(f"lab ready: {sum(results)} of {len(results)}")
sys.exit(0 if all(results) else 1)
python3 labcheck.py
ok   python  3.14.4
ok   folder  /home/you/krlab/securing-llm-apps
ok   server  a model server answers
ok   model   llama3.2:3b is installed
ok   chat    the model answered
lab ready: 5 of 5

Your Python version and your folder can differ. The last line must be the same. Type the last line of your own output.

If it fails

Read the first line that starts with FAIL. Fix that one, then run python3 labcheck.py again. The script ends with exit code 1 when a requirement fails.

The script saysWhat it meansWhat to do
FAIL pythonPython is older than 3.12.Install Python 3.12 or later, then run the script with that python3.
FAIL folderThe folder does not exist, or you made it in another place.Run mkdir -p ~/krlab/securing-llm-apps again. The script looks in your home folder.
FAIL serverNo model server answers on 127.0.0.1:11434.Start it with ollama serve in another terminal. Do lesson 3 of "How LLMs and agents work" if you never installed it.
FAIL modelThe server runs, but it has no llama3.2:3b.Run ollama pull llama3.2:3b (a download of about 2 GB), then run the script again.
FAIL chatThe model is installed but gives no answer, often because the memory is too small.Close other programs, or use a smaller model (see below), then run the script again.
lab ready: 4 of 5One requirement failed.Read the FAIL line above it.

If your computer has too little memory for llama3.2:3b, the course "How LLMs and agents work" names a smaller model. The numbers in this course are for llama3.2:3b and will be different on another model.