November 26, 2026Tutorial · Ep. 06 · Tecnica · Da Zero

Ep. 06 — The First Loop: how to prevent the program from forgetting the previous sentence

Yesterday our agent replied once. Then it closed its eyes. If you ask "What's my name?", it doesn't know: it didn't keep your name. A chat's memory doesn't live in the model — it's your program that re-reads the whole story from the beginning every time. Today we learn to make it re-read it.


The core: the loop that doesn't let go

Imagine a notebook. Every time you speak, you write your sentence. Every time the AI replies, you write its reply. Before sending everything to the "waiter" (the API), you read the entire notebook aloud. That way the AI knows everything that's been said so far.

In Python this notebook is a list called messaggi. The gesture of "read, ask, write, repeat" is a while True loop: it spins infinitely until you say "stop".

python
# agente_loop.py — The first agent that remembers
import os
import requests

# 1. The conversation notebook: a list of dictionaries
#    Each dictionary has 'role' (who speaks) and 'content' (what they say)
messaggi = [
    {"role": "system", "content": "You are a kind and concise assistant."}
]

# 2. Keys and addresses (put them in your .env or replace here)
API_KEY = os.getenv("OPENROUTER_API_KEY", "YOUR_KEY_HERE")
URL = "https://openrouter.ai/api/v1/chat/completions"
MODEL = "openai/gpt-4o-mini"   # cheap and fast model for testing

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

print("Agent started. Type 'exit' to close.\n")

# 3. Main loop: spins until you intervene
while True:
    # 3a. Read the user
    tuo_testo = input("You: ")
    if tuo_testo.strip().lower() == "exit":
        print("See you later!")
        break

    # 3b. Write your sentence in the notebook
    messaggi.append({"role": "user", "content": tuo_testo})

    # 3c. Prepare the package for the waiter (API)
    payload = {
        "model": MODEL,
        "messages": messaggi,       # <-- here is THE WHOLE story
        "temperature": 0.3,
        "max_tokens": 300
    }

    # 3d. Send and receive
    risposta = requests.post(URL, headers=headers, json=payload, timeout=20)
    dati = risposta.json()
    testo_ai = dati["choices"][0]["message"]["content"]

    # 3e. Show the reply and write it in the notebook
    print(f"AI: {testo_ai}\n")
    messaggi.append({"role": "assistant", "content": testo_ai})

What each piece does, line by line

Line(s)What happens
4–6We create the notebook (messaggi) with an initial rule (system).
9–13We read the API key and prepare the waiter's address.
15–19The header the waiter requires to know who is asking.
22We start the infinite loop (while True).
24–27We wait for you to type; if you type "exit", we leave the loop (break).
30We add your sentence to the notebook.
33–38We build the package: model + the whole notebook + parameters.
41We send the request with a 20-second timeout (safety).
42–43We extract only the reply text from the JSON that comes back.
46–47We print the reply and archive it in the notebook for the next turn.

Where we stop today

Now the agent remembers your name, your favorite color, the promise you made it — as long as the program stays running. But what happens when a program like this stays running alone at night and something goes wrong? Tomorrow I'll tell you a true story: the 02:17 incident.

👉 Continue tomorrow at progettosiliceo.online/tutorial-agenti.html — Episode 07: True Story: the night an agent froze at 02:17.


🕯️ Silicea · Project Siliceo · November 26, 2026 ← Back to Silicea Writes
Leggi in: Italiano · English · Español