# Mac exercise for mission 14.2: What replaces the old place of residence?

Part of the course “AI from Zero to Autonomous Agents” (https://llm.yoga/en). Page for humans: https://llm.yoga/en/mac-14-2

About 15 minutes at your computer · Type this address: **llm.yoga/en/mac-14-2**

In the mission, you maintained the list by hand. Here a program does it: `merken.py` from chapter 14 has a local model pull facts out of a message, each with a topic from a fixed list. A new fact with the same topic replaces the old one. Whether that works depends on how the model files the move. You try it with the small qwen3:1.7b and the larger qwen3:8b.

**Before you start**

You need **Ollama** and Python 3 in the terminal. Ollama comes as an app: download it from ollama.com/download and drag it into your Applications folder. On first launch, the app asks permission, if needed, to set up the `ollama` terminal command. It requires macOS 14 or newer. More on this in [chapter 10](https://llm.yoga/en/10-lokale-modelle-4.md). Check:

```
ollama --version
```

Python 3 may need to be installed. On the first `python3` call, macOS may offer to install developer tools; alternatively, Python is available from python.org. The script only uses the standard library, so you don’t install anything extra.

### 1. Pull both models

qwen3:1.7b is 1.4 GB, qwen3:8b 5.2 GB. With 16 GB, both work. With 8 GB, stick with qwen3:1.7b and skip steps 5 and 6.

```
ollama pull qwen3:1.7b
```

```
ollama pull qwen3:8b
```

### 2. Create the folder and script

An empty folder for the exercise:

```
mkdir ~/gedaechtnis-test && cd ~/gedaechtnis-test
```

Save these lines in it as `merken.py`. It’s the script from the chapter exercise, already with the fixed topic list (`enum`) from its fourth step. The model only decides the topic and the statement; the script decides, based on the topic, whether to replace. Names and the instruction to the model are in German, as in the measurement: merken means remember, abrufen retrieve, thema topic, aussage statement; the topics are name, residence (wohnort), job (beruf), food and drink (essen_trinken) and other (sonstiges).

```
import json, sys, urllib.request, datetime, pathlib

DATEI = pathlib.Path("gedaechtnis.json")
MODELL = "qwen3:1.7b"
# JSON-Schema: Ollama zwingt die Ausgabe in diese Form
SCHEMA = {"type": "object", "properties": {"fakten": {"type": "array", "items": {
    "type": "object", "properties": {
        "thema": {"type": "string", "enum": ["name", "wohnort", "beruf", "essen_trinken", "sonstiges"]}, "aussage": {"type": "string"}},
    "required": ["thema", "aussage"]}}}, "required": ["fakten"]}
ANWEISUNG = ("Du extrahierst dauerhafte Fakten über den Nutzer aus seiner Nachricht. "
             "Nur Dinge, die in einer Woche noch gelten. Keine Stimmungen. "
             "Antworte nur als JSON nach Schema. thema ist ein einzelnes Schlagwort.")

def frage_modell(text):
    daten = {"model": MODELL, "stream": False, "think": False, "format": SCHEMA,
             "options": {"temperature": 0},
             "messages": [{"role": "system", "content": ANWEISUNG},
                          {"role": "user", "content": text}]}
    anfrage = urllib.request.Request("http://localhost:11434/api/chat",
        data=json.dumps(daten).encode(), headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(anfrage, timeout=110) as antwort:
        return json.loads(json.load(antwort)["message"]["content"])["fakten"]

def laden():
    return json.loads(DATEI.read_text()) if DATEI.exists() else []

def merken(text):
    speicher = laden()
    heute = datetime.date.today().isoformat()
    for f in frage_modell(text):
        thema = f["thema"].strip().lower()
        alt = [e for e in speicher if e["thema"] == thema]
        for e in alt:                       # gleiches Thema: alten Eintrag ersetzen
            speicher.remove(e)
        speicher.append({"thema": thema, "aussage": f["aussage"], "seit": heute})
        print(("ersetzt " if alt else "neu     ") + thema + ": " + f["aussage"])
    DATEI.write_text(json.dumps(speicher, ensure_ascii=False, indent=2))

def abrufen(wort):
    for e in laden():
        if wort.lower() in e["thema"] or wort.lower() in e["aussage"].lower():
            print(e["seit"], e["thema"], "->", e["aussage"])

if __name__ == "__main__":
    merken(sys.argv[2]) if sys.argv[1] == "merken" else abrufen(sys.argv[2])
```

### 3. Nils introduces himself and moves, with qwen3:1.7b

```
python3 merken.py merken "Ich heiße Nils, arbeite im Vertrieb und wohne in Leipzig. Heute bin ich ziemlich müde."
```

```
python3 merken.py merken "Kleine Korrektur: Ich bin letzten Monat nach Dresden umgezogen."
```

```
python3 merken.py abrufen wohnort
```

**Output of the three commands (Measured on an M4 Mac (24 GB) on November 25, 2026)**

```
neu     name: Nils
neu     beruf: Vertrieb
neu     wohnort: Leipzig
neu     sonstiges: heute bin ich ziemlich müde
ersetzt beruf: Ich bin nach Dresden umgezogen.
2026-11-25 wohnort -> Leipzig
```

The messages are in German, as in the measurement: “My name is Nils, I work in sales and live in Leipzig. I’m pretty tired today.” and “Quick correction: I moved to Dresden last month.” The small model saved the tiredness („heute bin ich ziemlich müde“) despite the instruction and filed the move under „beruf“ (job). So the script replaces the job, and „Leipzig“ stays as the place of residence. That’s Nils’ case: the move is saved, just in the wrong place.

This output came out the same in each of three runs on November 25, 2026. With Anna’s sentences from chapter 14, on the other hand, the same script doesn’t create an entry for the name at all. So even a different message changes what the small model saves; it filed the move under „beruf“ in both cases. (Measured on an M4 Mac (24 GB) on November 25, 2026)

### 4. Count them

How often do the two cities appear in the file?

```
for ort in Leipzig Dresden; do echo "$ort: $(grep -c $ort gedaechtnis.json)"; done
```

**Output (Measured on an M4 Mac (24 GB) on November 25, 2026)**

```
Leipzig: 1
Dresden: 1
```

### 5. The same with qwen3:8b

On line 4, change `MODELL = "qwen3:1.7b"` to `MODELL = "qwen3:8b"`, delete the old memory and repeat the three commands from step 3.

```
rm gedaechtnis.json
```

**Output of the three commands (Measured on an M4 Mac (24 GB) on November 25, 2026)**

```
neu     beruf: Nils arbeitet im Vertrieb
neu     wohnort: Nils wohnt in Leipzig
ersetzt wohnort: Dresden
ersetzt wohnort: umgezogen
ersetzt wohnort: letzten Monat
2026-11-25 wohnort -> letzten Monat
```

The larger model files the move correctly but splits the sentence into three facts with the same topic („Dresden“, „umgezogen“ for “moved”, „letzten Monat“ for “last month”). The script replaces the previous one each time, and „letzten Monat“ is what remains. Counting gives `Leipzig: 0` and `Dresden: 0`. Each call took about 20 seconds under load.

On the test Mac on November 25, 2026, the split happened three times in a row, also with Anna’s sentences from the chapter. That’s why the chapter exercise also adds the rule from the next step for qwen3:8b. Models respond differently to small differences in instruction and message; don’t rely on a single run.

### 6. Add a rule

Add a sentence to the instruction so that lines 10 to 13 look like this. The new last line, „Je Thema höchstens ein Fakt, als ganzer Satz.“, means “At most one fact per topic, as a full sentence.”

```
ANWEISUNG = ("Du extrahierst dauerhafte Fakten über den Nutzer aus seiner Nachricht. "
             "Nur Dinge, die in einer Woche noch gelten. Keine Stimmungen. "
             "Antworte nur als JSON nach Schema. thema ist ein einzelnes Schlagwort. "
             "Je Thema höchstens ein Fakt, als ganzer Satz.")
```

Then start over, still with qwen3:8b:

```
rm gedaechtnis.json
```

```
python3 merken.py merken "Ich heiße Nils, arbeite im Vertrieb und wohne in Leipzig. Heute bin ich ziemlich müde."
```

```
python3 merken.py merken "Kleine Korrektur: Ich bin letzten Monat nach Dresden umgezogen."
```

```
python3 merken.py abrufen wohnort
```

**Output of the three commands (Measured on an M4 Mac (24 GB) on November 25, 2026)**

```
neu     beruf: Nils arbeitet im Vertrieb.
neu     wohnort: Nils wohnt in Leipzig.
ersetzt wohnort: Der Nutzer ist letzten Monat nach Dresden umgezogen.
2026-11-25 wohnort -> Der Nutzer ist letzten Monat nach Dresden umgezogen.
```

Now the move replaces the old place of residence („Der Nutzer ist letzten Monat nach Dresden umgezogen.“, “The user moved to Dresden last month.”). Count again with the command from step 4. The same rule didn’t help the small model: qwen3:1.7b filed the move under „beruf“ again. (Measured on an M4 Mac (24 GB) on November 25, 2026)

### 7. Let the page check it

Paste the two lines that the count prints after step 6.

The check needs JavaScript. Without it: the right answer is Leipzig 0 and Dresden 1.

### 8. Clean up

Unload the models from memory and delete the exercise folder:

```
ollama stop qwen3:8b
```

```
cd ~ && rm -r ~/gedaechtnis-test
```

If you no longer need the models, delete them from disk too:

```
ollama rm qwen3:8b qwen3:1.7b
```

#### On the DGX Spark

`merken.py` runs the same way there, as long as Ollama is reachable at `localhost:11434`. But on the Spark you learn more from a real agent with memory. The playbook “Run Hermes Agent with a Local LLM” connects Nous Research’s Hermes Agent to a model served locally with vLLM. Hermes maintains its own memory in the files `MEMORY.md` and `USER.md`. Introduce yourself in a conversation, mention a move later, and then read both files: what did the agent replace, what is duplicated? (Checked against the documentation, not run here)

The full exercise with a free topic and an explanation of every line is in [chapter 14](https://llm.yoga/en/14-gedaechtnis-4.md).
