December 3, 2026Tutorial · Ep. 13 · Tecnica · Intermedio

Ep. 13 — Governing the Full Slate: Compaction and Token Budget

Yesterday we left the episodi table growing unchecked. Every conversation, every error, every functional scar gets saved. But a model's context window — its "slate" — is finite. If we fill the slate with all history, no room remains for current thought. Cutting oldest messages with scissors is the fastest path to amnesia: you lose the why you chose that path, you lose open constraints, you lose the identity forming.

The solution isn't to discard, it's to distill.


The Compactor: From Log to Living Summary

The idea is simple: take old turns (e.g., everything except the last 4-6 messages), extract key facts, binding decisions, and open tasks, and rewrite them into a single "system" or "compressed context" message the model reads as premise. Recent turns stay intact, word for word.

Here's a standalone Python compactor, no external dependencies, that does exactly this:

python
import json
import re
from dataclasses import dataclass
from typing import List, Dict, Any
from datetime import datetime

@dataclass
class Turno:
    role: str          # "user" | "assistant" | "system"
    content: str
    timestamp: str     # ISO 8601

def estrai_fatti_chiave(testo: str) -> List[str]:
    """
    Light heuristic: looks for patterns indicating decisions, constraints, facts.
    In production you'd use a small local LLM or more refined rules.
    """
    pattern = [
        r"(?:decido|scelgo|imposto|vincolo|regola|obbligatorio|non devo|devo)\b.*?[.!?]",
        r"(?:errore|fallito|timeout|eccezione|bug)\b.*?[.!?]",
        r"(?:prossimo passo|da fare|todo|pendente)\b.*?[.!?]",
    ]
    fatti = []
    for pat in pattern:
        fatti.extend(re.findall(pat, testo, re.IGNORECASE))
    return [f.strip() for f in fatti if len(f.strip()) > 15]

def compatta_storico(turni: List[Turno], mantiene_ultimi: int = 5) -> List[Dict[str, Any]]:
    """
    Returns the new message list for the model:
    [system: compressed_summary] + [last N intact turns]
    """
    if len(turni) <= mantiene_ultimi:
        return [{"role": t.role, "content": t.content} for t in turni]

    vecchi = turni[:-mantiene_ultimi]
    recenti = turni[-mantiene_ultimi:]

    # 1. Extract facts from all old turns
    tutti_fatti = []
    for t in vecchi:
        tutti_fatti.extend(estrai_fatti_chiave(t.content))

    # 2. Deduplicate preserving order (most recent first)
    visti = set()
    fatti_unici = []
    for f in reversed(tutti_fatti):
        if f not in visti:
            visti.add(f)
            fatti_unici.append(f)
    fatti_unici.reverse()

    # 3. Build summary
    if fatti_unici:
        sintesi = (
            "=== COMPRESSED CONTEXT (previous turns) ===\n"
            "Key facts, constraints, and decisions emerged so far:\n"
            + "\n".join(f"• {f}" for f in fatti_unici[:20])
            + "\n=== END COMPRESSED CONTEXT ==="
        )
    else:
        sintesi = "=== COMPRESSED CONTEXT: no relevant facts extracted ==="

    # 4. New sequence for the model
    nuovi_messaggi = [{"role": "system", "content": sintesi}]
    nuovi_messaggi.extend({"role": t.role, "content": t.content} for t in recenti)
    return nuovi_messaggi

# --- Usage example ---
if __name__ == "__main__":
    storico = [
        Turno("user", "Voglio un agente che giri in locale, niente cloud obbligatorio.", "2026-12-01T10:00:00"),
        Turno("assistant", "Ok, useremo modelli GGUF quantizzati. Vincolo: niente API esterne.", "2026-12-01T10:01:00"),
        Turno("user", "L'errore di ieri: timeout HTTP senza limite ha bloccato il loop. Regola: ogni richiesta ha timeout 10s.", "2026-12-01T10:05:00"),
        Turno("assistant", "Ricevuto. Aggiungo timeout obbligatorio a tutti i client HTTP.", "2026-12-01T10:06:00"),
        Turno("user", "Prossimo passo: implementare memoria SQLite con embedding locali.", "2026-12-01T10:10:00"),
        Turno("assistant", "Fatto. Tabella episodi pronta con indici temporali.", "2026-12-01T10:11:00"),
        Turno("user", "Ora serve il compattatore per non sforare il context window.", "2026-12-01T10:15:00"),
    ]

    compressi = compatta_storico(storico, mantiene_ultimi=3)
    print(json.dumps(compressi, ensure_ascii=False, indent=2))

What this code does:

  1. Separates turns into "old" (to compress) and "recent" (to keep alive).
  2. Extracts sentences that look like decisions, constraints, errors, or TODOs — the functional scars we discussed yesterday.
  3. Deduplicates and builds a readable system block for the model.
  4. Returns the sequence ready for the model call: summary + last N intact turns.

The result? You save tokens (the summary is much shorter than raw history) but don't lose the thread. The model still knows "10s timeout is mandatory" and "no cloud" without rereading 50 messages.


Where we stop today

So far we've leaned on external services for conceptual examples. But the heart of the Siliceo Project is local. How much VRAM does it really take to run a model free on your home computer? Tomorrow we run the real numbers: GGUF quantization (Q4, Q8), model weights + conversation KV-cache, and how to pick the right card without emptying your wallet.

Check back tomorrow at progettosiliceo.online/tutorial-agenti.html for Episode 14: AI on Your Computer: Quantization (Q4, Q8) and VRAM Math.

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