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 RAG and data

After this lesson you can
  • Create the lab folder of the course and add the model helper
  • 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 (3)

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 lessons 3 and 6 first. Lesson 3 installs the model server (Ollama) and the model llama3.2:3b. Lesson 6 builds a small retrieval service with TF-IDF and cosine similarity. This course attacks and defends a service of that kind, and it does not teach retrieval again.
  • The course "Securing LLM applications". It teaches prompt injection, leaks from prompts and test suites. This course names those lessons and builds on them.
  • Python 3.12 or later. Every program of this course uses the standard library only, so you install no package and make no virtual environment.
  • 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. Most checks of this course do not call the model at all: the code decides them, so they give the same result on every machine.

Everything runs on your own computer, in one folder: ~/krlab/securing-rag. The model server listens on your own computer only (127.0.0.1). This course is defensive: the only service that you attack is the small one that you build in the lab, and the only model is your local one. The company in the course, Marlowe Outdoor, is invented.

The lab on your computer
krlab/securing-ragModel server 127.0.0.1Lesson scriptsllm.pyLocal modelOllama123krlab/securing-ragModel server 127.0.0.1Lesson scriptsllm.pyLocal modelOllama123
  1. Lesson scripts → llm.py: ask for an answer
  2. llm.py → Ollama: web request to port 11434
  3. Ollama → Local model: runs llama3.2:3b

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-rag
cd ~/krlab/securing-rag
pwd
/home/you/krlab/securing-rag

2. Check the model server

If you did lesson 3 of "How LLMs and agents work", the server runs already. 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. If the name is missing, run ollama pull llama3.2:3b.

3. Add the model helper

llm.py is a small file that sends messages to the Ollama server on your machine and returns the answer. It is the same file as in lesson 3 of "How LLMs and agents work": if you still have it, copy it here. It uses the standard library only.

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"]

4. Keep the catch-up script

Lessons 3 and 5 create some files with commands: approvals.json, promo.json and the index files. A reader who starts at a later lesson does not have them. That reader unzips the Lab files zip and runs sh kr-lab.sh 06-keep-private-data-out-of-prompts-logs-and-stores ~/krlab/securing-rag, which builds the lab folder as it stands after lesson 6. Save catchup.sh, a shell script that makes the missing files. Run it only then, in that folder. bash catchup.sh runs the script with the shell bash.

catchup.sh

#!/bin/bash
# catchup.sh: make the files that lessons 3 and 5 create with commands. Run it in ~/krlab/securing-rag.
set -e
python3 provenance.py approve kb.json approvals.json all
python3 stuff.py > /dev/null
python3 peek.py > /dev/null
python3 partition.py > /dev/null
echo "catch-up done"

Check your lab

The script labcheck.py proves that the lab works. It checks six things and prints one line for each: the Python version, the folder, the helper, the model server, the model and the hash function. 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.
  • sys.path is the list of folders where Python looks for the files that you import.
  • 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.
  • hashlib.sha256 makes a SHA-256 hash, a fixed-length fingerprint of a text. Lesson 3 uses it.
  • 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 RAG and data" works. Standard library only."""
import hashlib
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-rag"
line("folder", folder.is_dir(), str(folder))

try:
    sys.path.insert(0, str(folder))
    from llm import chat
    helper = callable(chat)
except Exception:    # a missing file or an error in it
    helper = False
line("helper", helper, "llm.py gives chat()" if helper else "llm.py is missing in the lab 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")

line("hash", hashlib.sha256(b"abc").hexdigest().startswith("ba7816bf"), "sha256 works")

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-rag
ok   helper  llm.py gives chat()
ok   server  a model server answers
ok   model   llama3.2:3b is installed
ok   hash    sha256 works
lab ready: 6 of 6

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-rag again. The script looks in your home folder.
FAIL helperllm.py is not in the lab folder, or it has an error.Save llm.py again from step 3 and run the check in the lab 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 hashThe Python build has no working hashlib.Install a normal Python 3.12 or later from your system's own repository.
lab ready: 5 of 6One 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. Pull it, and set its name before you run the check: export KR_MODEL=<name> (export makes the variable visible to the programs that you start). labcheck.py and llm.py read KR_MODEL, so FAIL model goes away. The model answers in this course will then differ, but the checks do not depend on them.