BonusLockSMith commited on
Commit
93dfcf3
·
verified ·
1 Parent(s): 127143c

Upload folder using huggingface_hub

Browse files
Files changed (8) hide show
  1. Dockerfile +10 -0
  2. POST.md +32 -0
  3. README.md +35 -4
  4. app.py +177 -0
  5. llm.py +58 -0
  6. requirements.txt +3 -0
  7. static/gritai.css +134 -0
  8. store.py +88 -0
Dockerfile ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+ WORKDIR /app
3
+ COPY requirements.txt .
4
+ RUN pip install --no-cache-dir -r requirements.txt
5
+ COPY . .
6
+ # Cloud demo narrates via Claude (can't reach a local fleet); ANTHROPIC_API_KEY is a Space secret.
7
+ # NOTE: memory.db lives in the container FS — persists within a run, resets on rebuild (fine for a demo).
8
+ ENV PORT=7860 MEMBOT_LLM_BACKEND=claude ANTHROPIC_MODEL=claude-haiku-4-5 PYTHONUNBUFFERED=1
9
+ EXPOSE 7860
10
+ CMD ["python", "app.py"]
POST.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 30-in-15 · #16 — Memory Chatbot (build-in-public post)
2
+
3
+ **Attach:** a screen-record — tell it your name/project, RELOAD the page, ask "what do you know about me?" → it recalls.
4
+ **Demo:** https://memory.gritai.solutions · **Repo:** https://github.com/GritAI-Labs/memory-chatbot
5
+
6
+ ---
7
+
8
+ 🧠 Project #16 of my "30 AI Projects in 15 days": a chatbot that actually remembers you across sessions.
9
+
10
+ Most chatbots only have a conversation buffer — the current session's messages. Reload and you're a stranger again. This one adds long-term memory: after each exchange it extracts the durable facts about you (name, preferences, what you're building), stores them, and injects them into every future conversation. Close the tab, come back tomorrow, and it still knows you.
11
+
12
+ The part I like is that the memory is visible and yours: a side panel shows exactly what it remembers, and you can delete any single fact or wipe it entirely. No black-box profile — memory you can see and control.
13
+
14
+ Under the hood it's the classic architecture: extract → store → retrieve → inject, with the long-term store deliberately separate from the short-term buffer. Runs on a local model by default (free, private) or a hosted one.
15
+
16
+ Tell it about yourself, reload, and ask what it knows.
17
+
18
+ ⭐ https://github.com/GritAI-Labs/memory-chatbot
19
+
20
+ ---
21
+
22
+ ## X / Twitter version (≤280)
23
+
24
+ 🧠 #16 of my 30 AI projects in 15 days: a chatbot that remembers you across sessions.
25
+
26
+ It extracts durable facts about you → stores them → recalls them next time. Reload the tab and it still knows your name & project. Memory you can see and delete.
27
+
28
+ → https://github.com/GritAI-Labs/memory-chatbot
29
+
30
+ ---
31
+
32
+ **Permalinks:** X: _____ · LinkedIn: _____
README.md CHANGED
@@ -1,10 +1,41 @@
1
  ---
2
  title: Memory Chatbot
3
- emoji: 👀
4
- colorFrom: blue
5
- colorTo: pink
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Memory Chatbot
3
+ emoji: 🧠
4
+ colorFrom: gray
5
+ colorTo: red
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # Memory Chatbot 🧠
12
+
13
+ A chatbot that **remembers you across sessions.** Close the tab, come back tomorrow — it still knows your
14
+ name, what you're working on, and how you like things.
15
+
16
+ > Project **#16** of the *"30 AI Projects in 15 Days"* challenge. Focus: **memory architecture + state.**
17
+
18
+ ## The lesson: buffer vs long-term memory
19
+ Most chatbots only have a **conversation buffer** — the current session's messages. Reload and they forget
20
+ you. This one adds **long-term memory**, in four moves:
21
+ 1. **Extract** — after each exchange, an LLM pulls durable facts about you (name, preferences, projects).
22
+ 2. **Store** — facts go to a local DB, keyed by user, deduped. *This is what survives the session.*
23
+ 3. **Retrieve** — on every turn, your stored facts are loaded.
24
+ 4. **Inject** — they're placed in the system prompt, so the bot recalls you.
25
+
26
+ A live **🧠 Memory panel** shows exactly what it remembers, and lets you delete any fact or forget everything —
27
+ memory you can see and control.
28
+
29
+ ## Run it
30
+ ```bash
31
+ pip install -r requirements.txt
32
+ python app.py # http://127.0.0.1:7860
33
+ # Local Ollama by default (free/private); set ANTHROPIC_API_KEY for the Claude backend.
34
+ ```
35
+
36
+ ## Prove the memory works
37
+ Tell it your name and what you're building, then **reload the page** (or come back later) — it still knows.
38
+ Different browser / cleared cookies = a fresh user with its own memory.
39
+
40
+ ---
41
+ Built by **Robert Lucyk** · [GritAI Solutions](https://gritai.solutions) · part of the 30-in-15 challenge.
app.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Memory Chatbot (#16 of the 30-in-15) — a bot that remembers you across sessions.
3
+
4
+ The lesson is memory architecture: a short-term conversation buffer (this session) vs long-term memory
5
+ (a store that outlives the session). After each exchange the bot extracts durable facts and saves them;
6
+ on every turn it injects what it remembers. Close the tab, come back tomorrow — it still knows you.
7
+
8
+ pip install -r requirements.txt
9
+ python app.py # http://127.0.0.1:7860 (local Ollama by default; ANTHROPIC_API_KEY for Claude)
10
+ """
11
+ import os
12
+ import uuid
13
+
14
+ from flask import Flask, request, render_template_string, jsonify, make_response
15
+
16
+ import llm
17
+ import store
18
+
19
+ app = Flask(__name__)
20
+ BASE_SYSTEM = ("You are a warm, helpful assistant with a long-term memory of the user across sessions. "
21
+ "Use what you remember naturally — don't recite it back robotically. Be concise.")
22
+ MAX_BUFFER = 8 # short-term turns folded in per request
23
+
24
+ PAGE = r"""<!doctype html><html lang="en"><head>
25
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
26
+ <title>GritAI · Memory Chatbot</title>
27
+ <link rel="stylesheet" href="/static/gritai.css">
28
+ <style>
29
+ .wrap{max-width:1080px;margin:0 auto;padding:22px 20px 30px}
30
+ .cols{display:grid;grid-template-columns:1fr 300px;gap:20px;margin-top:16px}
31
+ @media(max-width:820px){.cols{grid-template-columns:1fr}}
32
+ #chat{display:flex;flex-direction:column;gap:12px;min-height:52vh;max-height:64vh;overflow-y:auto;padding-right:4px}
33
+ .msg{max-width:88%;padding:11px 14px;border-radius:4px;font-size:15px;line-height:1.6;white-space:pre-wrap}
34
+ .msg.user{align-self:flex-end;background:var(--panel2);border:1px solid var(--line2)}
35
+ .msg.ai{align-self:flex-start;background:linear-gradient(180deg,var(--panel),var(--bg2));border:1px solid var(--line)}
36
+ .composer{display:flex;gap:10px;margin-top:14px}
37
+ .composer input{flex:1;background:var(--panel);border:1px solid var(--line2);border-radius:3px;color:var(--ink);
38
+ font-family:var(--body);font-size:15.5px;padding:13px 16px;outline:none}
39
+ .send{border:0;background:var(--grit);color:#140a06;font-family:var(--mono);font-weight:600;font-size:12px;
40
+ letter-spacing:.12em;text-transform:uppercase;padding:0 20px;cursor:pointer;border-radius:3px}
41
+ .send:hover{background:var(--grit2)}
42
+ .mempanel{border:1px solid var(--line2);border-radius:3px;background:var(--panel);padding:14px}
43
+ .mempanel h4{font-family:var(--disp);color:var(--grit);font-size:13px;letter-spacing:.06em;text-transform:uppercase;margin:0 0 4px}
44
+ .mempanel .hint{color:var(--dim2);font-family:var(--mono);font-size:10px;letter-spacing:.1em;text-transform:uppercase;margin-bottom:10px}
45
+ .fact{display:flex;justify-content:space-between;gap:8px;align-items:flex-start;font-size:13px;color:var(--ink);
46
+ border-bottom:1px solid var(--line);padding:7px 0}
47
+ .fact .x{cursor:pointer;color:var(--dim2);font-family:var(--mono);font-size:12px}
48
+ .fact .x:hover{color:var(--bad)}
49
+ .fresh{color:var(--ok)}
50
+ .clr{margin-top:10px;border:1px solid var(--line2);background:transparent;color:var(--dim);font-family:var(--mono);
51
+ font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;padding:6px 10px;border-radius:3px;cursor:pointer}
52
+ .clr:hover{color:var(--bad);border-color:var(--bad)}
53
+ .muted{color:var(--dim2);font-family:var(--mono);font-size:10.5px;letter-spacing:.14em;text-transform:uppercase}
54
+ .empty{color:var(--dim2);font-size:12.5px;font-style:italic}
55
+ </style></head><body>
56
+ <div class="wrap">
57
+ <header style="display:flex;align-items:center;gap:13px">
58
+ <svg width="34" height="34" viewBox="0 0 38 38" fill="none"><rect x="1" y="1" width="36" height="36" rx="2" stroke="#2b303c"/><path d="M27 12.5A9 9 0 1 0 28 22H19" stroke="#ff5a2a" stroke-width="2.4" stroke-linecap="square"/><rect x="10.5" y="10.5" width="3" height="3" fill="#ff5a2a"/></svg>
59
+ <div class="brand"><div class="co">Grit<b>AI</b> · Memory Chatbot</div>
60
+ <div class="sub">Remembers you across sessions · close the tab, come back — it still knows you</div></div>
61
+ <div style="flex:1"></div><div class="tag hot">#16 · 30-in-15</div>
62
+ </header>
63
+
64
+ <div class="cols">
65
+ <div>
66
+ <div id="chat"><div class="msg ai">Hi! I'll remember what you tell me — your name, what you're working on, how you like things — and recall it next time you're here. Tell me a bit about yourself.</div></div>
67
+ <div class="composer">
68
+ <input id="q" placeholder="Say something — I'll remember the important bits…" autofocus>
69
+ <button class="send" onclick="ask()">Send</button>
70
+ </div>
71
+ <p class="muted" style="margin-top:12px">Backend: {{ backend }} · GritAI Solutions</p>
72
+ </div>
73
+ <div>
74
+ <div class="mempanel">
75
+ <h4>🧠 Memory</h4>
76
+ <div class="hint">what I remember about you — persists across sessions</div>
77
+ <div id="facts"><span class="empty">nothing yet — tell me something durable</span></div>
78
+ <button class="clr" onclick="clearMem()">forget everything</button>
79
+ </div>
80
+ </div>
81
+ </div>
82
+ </div>
83
+ <script>
84
+ let history=[];
85
+ const chat=document.getElementById('chat');
86
+ function esc(s){return (s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
87
+ function bubble(cls,text){const d=document.createElement('div');d.className='msg '+cls;d.textContent=text;chat.appendChild(d);chat.scrollTop=chat.scrollHeight;return d;}
88
+
89
+ async function loadMem(fresh){
90
+ const r=await fetch('/api/memory'); const d=await r.json();
91
+ const box=document.getElementById('facts');
92
+ if(!d.facts||!d.facts.length){box.innerHTML='<span class="empty">nothing yet — tell me something durable</span>';return;}
93
+ box.innerHTML=d.facts.map(f=>{
94
+ const isNew=(fresh||[]).includes(f.fact);
95
+ return `<div class="fact"><span class="${isNew?'fresh':''}">${esc(f.fact)}</span><span class="x" onclick="delMem(${f.id})">✕</span></div>`;
96
+ }).join('');
97
+ }
98
+ async function delMem(id){await fetch('/api/memory/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});loadMem();}
99
+ async function clearMem(){await fetch('/api/memory/clear',{method:'POST'});loadMem();}
100
+
101
+ async function ask(){
102
+ const inp=document.getElementById('q');const text=inp.value.trim();if(!text)return;
103
+ inp.value='';bubble('user',text);history.push({role:'user',content:text});
104
+ const thinking=bubble('ai','…');
105
+ try{
106
+ const r=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({message:text,history})});
107
+ const d=await r.json();
108
+ thinking.textContent=d.reply||'(no reply)';
109
+ history.push({role:'assistant',content:d.reply||''});
110
+ if(history.length>16)history=history.slice(-16);
111
+ loadMem(d.remembered);
112
+ }catch(e){thinking.textContent='(error — is the model backend running?)';}
113
+ }
114
+ document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')ask();});
115
+ loadMem();
116
+ </script></body></html>"""
117
+
118
+
119
+ def _user():
120
+ return request.cookies.get("memuser") or ""
121
+
122
+
123
+ @app.route("/")
124
+ def index():
125
+ resp = make_response(render_template_string(PAGE, backend=llm.backend_label()))
126
+ if not request.cookies.get("memuser"):
127
+ resp.set_cookie("memuser", uuid.uuid4().hex, max_age=60 * 60 * 24 * 365, samesite="Lax")
128
+ return resp
129
+
130
+
131
+ @app.route("/api/memory")
132
+ def api_memory():
133
+ return jsonify({"facts": store.get_facts(_user())})
134
+
135
+
136
+ @app.route("/api/memory/delete", methods=["POST"])
137
+ def api_delete():
138
+ d = request.get_json(force=True)
139
+ store.delete_fact(_user(), int(d.get("id", 0)))
140
+ return jsonify({"ok": True})
141
+
142
+
143
+ @app.route("/api/memory/clear", methods=["POST"])
144
+ def api_clear():
145
+ store.clear(_user())
146
+ return jsonify({"ok": True})
147
+
148
+
149
+ @app.route("/api/chat", methods=["POST"])
150
+ def api_chat():
151
+ user_id = _user()
152
+ d = request.get_json(force=True)
153
+ message = (d.get("message") or "").strip()[:2000]
154
+ if not message:
155
+ return jsonify({"reply": "Say something!", "remembered": []})
156
+ history = d.get("history") or []
157
+ system = BASE_SYSTEM + store.memory_block(user_id) # long-term memory injected here
158
+ # short-term buffer: recent turns folded into the prompt
159
+ recent = history[-MAX_BUFFER * 2:-1] if len(history) > 1 else []
160
+ convo = "".join(f"{m['role']}: {m['content']}\n" for m in recent)
161
+ user_prompt = (f"Recent conversation:\n{convo}\n" if convo else "") + f"User: {message}"
162
+ try:
163
+ reply = llm.chat(system, user_prompt, temperature=0.6, max_tokens=600)
164
+ except Exception as e:
165
+ print(f"chat error: {type(e).__name__}")
166
+ return jsonify({"reply": "My brain backend hiccuped — is the model running?", "remembered": []})
167
+ remembered = []
168
+ try:
169
+ remembered = store.remember_from_exchange(user_id, message, reply)
170
+ except Exception as e:
171
+ print(f"memory error: {type(e).__name__}")
172
+ return jsonify({"reply": reply, "remembered": remembered})
173
+
174
+
175
+ if __name__ == "__main__":
176
+ port = int(os.environ.get("PORT", "7860"))
177
+ app.run(host="0.0.0.0", port=port, debug=False)
llm.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """LLM backend for the Memory Chatbot (#16): local Ollama (default) or Claude.
3
+
4
+ chat() for replies, extract_json() for the memory extractor. Errors log the exception TYPE only.
5
+ """
6
+ import json
7
+ import os
8
+ import re
9
+ import urllib.request
10
+
11
+ BACKEND = os.environ.get("MEMBOT_LLM_BACKEND", "ollama").lower()
12
+ OLLAMA_URL = os.environ.get("MEMBOT_OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/")
13
+ OLLAMA_MODEL = os.environ.get("MEMBOT_OLLAMA_MODEL", "qwen2.5:7b")
14
+ ANTHROPIC_KEY = (os.environ.get("ANTHROPIC_API_KEY") or "").strip() or None
15
+ ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-haiku-4-5")
16
+
17
+
18
+ def _ollama(system, user, temperature, max_tokens):
19
+ body = json.dumps({"model": OLLAMA_MODEL, "stream": False,
20
+ "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
21
+ "options": {"temperature": temperature, "num_predict": max_tokens}}).encode()
22
+ req = urllib.request.Request(OLLAMA_URL + "/api/chat", data=body, headers={"Content-Type": "application/json"})
23
+ return json.loads(urllib.request.urlopen(req, timeout=120).read())["message"]["content"].strip()
24
+
25
+
26
+ def _claude(system, user, temperature, max_tokens):
27
+ body = json.dumps({"model": ANTHROPIC_MODEL, "max_tokens": max_tokens, "temperature": temperature,
28
+ "system": system, "messages": [{"role": "user", "content": user}]}).encode()
29
+ req = urllib.request.Request("https://api.anthropic.com/v1/messages", data=body, headers={
30
+ "x-api-key": ANTHROPIC_KEY, "anthropic-version": "2023-06-01", "content-type": "application/json"})
31
+ data = json.loads(urllib.request.urlopen(req, timeout=120).read())
32
+ return "".join(b.get("text", "") for b in data.get("content", [])).strip()
33
+
34
+
35
+ def chat(system: str, user: str, temperature: float = 0.5, max_tokens: int = 700) -> str:
36
+ fn = _claude if (BACKEND == "claude" and ANTHROPIC_KEY) else _ollama
37
+ return fn(system, user, temperature, max_tokens)
38
+
39
+
40
+ def extract_json(system: str, user: str):
41
+ raw = chat(system + "\nReply with ONLY valid JSON, no prose, no code fences.", user, temperature=0.0, max_tokens=400)
42
+ s = raw.strip()
43
+ if s.startswith("```"):
44
+ s = s.split("```", 2)[1].lstrip("json").strip() if s.count("```") >= 2 else s.strip("`")
45
+ try:
46
+ return json.loads(s)
47
+ except Exception:
48
+ i, j = s.find("["), s.rfind("]")
49
+ if 0 <= i < j:
50
+ try:
51
+ return json.loads(s[i:j + 1])
52
+ except Exception:
53
+ pass
54
+ return None
55
+
56
+
57
+ def backend_label() -> str:
58
+ return "Claude" if (BACKEND == "claude" and ANTHROPIC_KEY) else f"Ollama ({OLLAMA_MODEL} @ {OLLAMA_URL})"
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ flask==3.1.3
2
+ requests==2.34.2
3
+ # store/llm use only the above + stdlib (sqlite3, urllib). Claude backend needs no extra package.
static/gritai.css ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================================
2
+ GRITAI DESIGN SYSTEM — "Engineered / Industrial"
3
+ Dark · grit-orange · Archivo + IBM Plex · blueprint grid + grain.
4
+ Canonical source of truth for every GritAI app (30-in-15 #1-30) + the hub.
5
+ Rob-approved 2026-09-05 (#9 pilot: design-critic 5.71 -> 7.57).
6
+
7
+ HOW TO USE: embed this <style> verbatim in an app's page, add the Google Fonts
8
+ <link> below, then build the body from the component classes here. Keep the
9
+ header (monogram + app name + tags), grit-orange as the ONLY accent, dark bg.
10
+
11
+ FONTS (add to <head>):
12
+ <link rel="preconnect" href="https://fonts.googleapis.com">
13
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
14
+ <link href="https://fonts.googleapis.com/css2?family=Archivo:wght@600;700;800;900&family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet">
15
+ ============================================================================ */
16
+ :root{
17
+ --bg:#0a0b0e; --bg2:#0e1015; --panel:#111318; --panel2:#15181f;
18
+ --ink:#eef0f4; --dim:#9aa1b0; --dim2:#5f6675; --line:#20242e; --line2:#2b303c;
19
+ --grit:#ff5a2a; --grit2:#ff7d54; --grit-dim:#c9451f; --ok:#5fd08a; --bad:#ff6b6b;
20
+ --disp:'Archivo',system-ui,sans-serif; --body:'IBM Plex Sans',system-ui,sans-serif;
21
+ --mono:'IBM Plex Mono',ui-monospace,monospace;
22
+ }
23
+ *{box-sizing:border-box}
24
+ html,body{height:100%}
25
+ body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--body);font-size:15px;line-height:1.6;
26
+ -webkit-font-smoothing:antialiased;position:relative;overflow-x:hidden}
27
+ /* blueprint grid + vignette */
28
+ body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;
29
+ background:linear-gradient(0deg,transparent 95%,rgba(255,90,42,.04) 100%),
30
+ repeating-linear-gradient(90deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),
31
+ repeating-linear-gradient(0deg,transparent 0 63px,rgba(255,255,255,.018) 63px 64px),
32
+ radial-gradient(120% 80% at 50% -10%,#141821 0%,var(--bg) 55%)}
33
+ /* film grain */
34
+ body::after{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;opacity:.05;mix-blend-mode:overlay;
35
+ background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}
36
+ .wrap{position:relative;z-index:1;max-width:960px;margin:0 auto;padding:0 28px 70px}
37
+
38
+ /* ---- header band (monogram SVG + wordmark + tags) ---- */
39
+ header{display:flex;align-items:center;gap:16px;padding:22px 0 18px;border-bottom:1px solid var(--line);animation:fade .6s .02s both}
40
+ .mark{width:38px;height:38px;flex:none}.mark svg{display:block}
41
+ .brand{display:flex;flex-direction:column;line-height:1}
42
+ .brand .co{font-family:var(--disp);font-weight:900;font-size:19px;letter-spacing:.5px}.brand .co b{color:var(--grit)}
43
+ .brand .sub{font-family:var(--mono);font-size:10.5px;letter-spacing:.28em;text-transform:uppercase;color:var(--dim2);margin-top:5px}
44
+ .tags{margin-left:auto;display:flex;gap:8px}
45
+ .tag{font-family:var(--mono);font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);border:1px solid var(--line2);border-radius:2px;padding:5px 9px}
46
+ .tag.hot{color:var(--grit);border-color:var(--grit-dim)}
47
+ /* canonical monogram SVG (paste in .mark):
48
+ <svg width="38" height="38" viewBox="0 0 38 38" fill="none"><rect x="1" y="1" width="36" height="36" rx="2" stroke="#2b303c"/><path d="M27 12.5A9 9 0 1 0 28 22H19" stroke="#ff5a2a" stroke-width="2.4" stroke-linecap="square"/><rect x="10.5" y="10.5" width="3" height="3" fill="#ff5a2a"/></svg> */
49
+
50
+ /* ---- hero ---- */
51
+ .hero{padding:34px 0 26px;animation:fade .6s .12s both}
52
+ .hero h1{font-family:var(--disp);font-weight:800;font-size:clamp(30px,5.4vw,52px);line-height:1.02;letter-spacing:-.02em;margin:0;max-width:16ch}
53
+ .hero h1 em{font-style:normal;color:var(--grit)}
54
+ .hero p{color:var(--dim);max-width:56ch;margin:16px 0 0;font-size:15.5px}
55
+
56
+ /* ---- section label (01 · NAME + rule) ---- */
57
+ .sec{display:flex;align-items:center;gap:14px;margin:30px 0 14px}
58
+ .sec .num{font-family:var(--mono);font-size:11px;font-weight:600;color:var(--grit);letter-spacing:.1em}
59
+ .sec .name{font-family:var(--mono);font-size:11px;font-weight:500;letter-spacing:.26em;text-transform:uppercase;color:var(--dim)}
60
+ .sec .rule{flex:1;height:1px;background:linear-gradient(90deg,var(--line2),transparent)}
61
+
62
+ /* ---- panels ---- */
63
+ .panel{border:1px solid var(--line);border-radius:3px;background:linear-gradient(180deg,var(--panel),var(--bg2))}
64
+ .card{border:1px solid var(--line2);border-radius:3px;background:var(--panel);padding:18px 20px}
65
+ .card.accent{border-left:2px solid var(--grit)}
66
+
67
+ /* ---- input field (terminal) ---- */
68
+ .field{display:flex;align-items:stretch;border:1px solid var(--line2);border-radius:3px;background:var(--panel);overflow:hidden;transition:border-color .18s}
69
+ .field:focus-within{border-color:var(--grit-dim)}
70
+ .field .car{font-family:var(--mono);color:var(--grit);padding:16px 0 16px 16px;font-size:15px;user-select:none}
71
+ .field input,.field textarea{flex:1;background:transparent;border:0;outline:none;color:var(--ink);font-family:var(--body);font-size:15.5px;padding:16px 14px;resize:vertical}
72
+ .field input::placeholder,.field textarea::placeholder{color:var(--dim2)}
73
+ textarea.ta{width:100%;min-height:140px;border:1px solid var(--line2);border-radius:3px;background:var(--panel);color:var(--ink);font-family:var(--body);font-size:15px;padding:14px 16px;outline:none;resize:vertical}
74
+ textarea.ta:focus{border-color:var(--grit-dim)}
75
+
76
+ /* ---- buttons ---- */
77
+ .run{border:0;background:var(--grit);color:#140a06;font-family:var(--mono);font-weight:600;font-size:13px;letter-spacing:.14em;text-transform:uppercase;padding:0 24px;cursor:pointer;transition:.16s;box-shadow:-1px 0 0 var(--grit-dim)}
78
+ .run:hover{background:var(--grit2);box-shadow:0 0 26px -4px rgba(255,90,42,.55)}
79
+ .run:disabled{opacity:.55;cursor:default;box-shadow:none}
80
+ .btn{display:inline-flex;align-items:center;gap:8px;border:0;border-radius:3px;background:var(--grit);color:#140a06;font-family:var(--mono);font-weight:600;font-size:13px;letter-spacing:.1em;text-transform:uppercase;padding:12px 22px;cursor:pointer;transition:.16s}
81
+ .btn:hover{background:var(--grit2);box-shadow:0 0 26px -4px rgba(255,90,42,.55)}
82
+ .btn.ghost{background:transparent;color:var(--dim);border:1px solid var(--line2)}
83
+ .btn.ghost:hover{color:var(--grit);border-color:var(--grit-dim);background:transparent;box-shadow:none}
84
+
85
+ /* ---- chips / controls ---- */
86
+ .chip{font-family:var(--mono);font-size:12px;color:var(--dim);background:var(--panel);border:1px solid var(--line);border-radius:2px;padding:8px 11px;cursor:pointer;transition:.15s}
87
+ .chip:hover{color:var(--grit);border-color:var(--grit-dim)}
88
+ .chip .pt{color:var(--dim2);margin-right:7px}
89
+ select,.select{padding:10px 12px;border:1px solid var(--line2);border-radius:3px;background:var(--panel);color:var(--ink);font-family:var(--mono);font-size:13px;outline:none;cursor:pointer}
90
+ select:focus{border-color:var(--grit-dim)}
91
+ label.lbl{font-family:var(--mono);font-size:11px;text-transform:uppercase;letter-spacing:.24em;color:var(--dim2);display:block;margin-bottom:6px}
92
+
93
+ /* ---- mono log / trace rows ---- */
94
+ .log{font-family:var(--mono);font-size:13px;line-height:1.75}
95
+ .row{display:grid;grid-template-columns:22px auto 1fr;gap:0 12px;padding:13px 18px;border-bottom:1px solid var(--line)}
96
+ .row:last-child{border-bottom:0}
97
+ .row .mk{color:var(--grit);font-weight:600}
98
+ .row .tn{color:var(--grit2);text-transform:uppercase;letter-spacing:.06em;font-weight:500}
99
+ .row .rd{color:var(--ink);word-break:break-word}.row .rd .arg{color:var(--dim2)}
100
+
101
+ /* ---- tables ---- */
102
+ table{width:100%;border-collapse:collapse;font-size:13.5px}
103
+ th{text-align:left;font-family:var(--mono);font-size:11px;text-transform:uppercase;letter-spacing:.12em;color:var(--dim2);font-weight:500;padding:11px 14px;border-bottom:1px solid var(--line2);background:var(--bg2)}
104
+ td{padding:11px 14px;border-bottom:1px solid var(--line);vertical-align:top}
105
+ tr:last-child td{border-bottom:0}
106
+ .tablewrap{border:1px solid var(--line);border-radius:3px;overflow:hidden;overflow-x:auto}
107
+
108
+ /* ---- chat bubbles ---- */
109
+ .msg{max-width:78%;padding:12px 15px;border-radius:3px;font-size:15px;line-height:1.55;margin-bottom:12px}
110
+ .msg.user{margin-left:auto;background:var(--panel2);border:1px solid var(--line2)}
111
+ .msg.bot{background:var(--panel);border:1px solid var(--line);border-left:2px solid var(--grit)}
112
+
113
+ /* ---- badges / pills ---- */
114
+ .badge{display:inline-block;font-family:var(--mono);font-size:11px;font-weight:500;letter-spacing:.06em;padding:3px 9px;border-radius:2px;border:1px solid var(--line2);color:var(--dim)}
115
+ .badge.on{color:var(--grit);border-color:var(--grit-dim)}
116
+ .hl{color:var(--grit);font-weight:600;font-family:var(--mono)}
117
+
118
+ /* ---- answer/output prose ---- */
119
+ .prose{font-size:16px;line-height:1.65}.prose p{margin:0 0 12px}.prose p:last-child{margin-bottom:0}.prose b{color:var(--ink)}
120
+
121
+ /* ---- spinner ---- */
122
+ .spin{display:inline-flex;gap:6px;padding:16px 18px}.spin span{width:8px;height:8px;border-radius:50%;background:var(--grit);opacity:.5;animation:bd 1.2s infinite}
123
+ .spin span:nth-child(2){animation-delay:.18s}.spin span:nth-child(3){animation-delay:.36s}
124
+
125
+ /* ---- footer ---- */
126
+ footer{margin-top:34px;padding-top:16px;border-top:1px solid var(--line);font-family:var(--mono);font-size:11px;letter-spacing:.06em;color:var(--dim2);display:flex;gap:16px;flex-wrap:wrap;animation:fade .6s .5s both}
127
+ footer .b{color:var(--dim)}footer .sp{margin-left:auto}
128
+ footer a{color:var(--dim);text-decoration:none}footer a:hover{color:var(--grit)}
129
+
130
+ /* ---- reveal animations ---- */
131
+ @keyframes fade{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
132
+ @keyframes slidein{from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:none}}
133
+ @keyframes bd{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-6px);opacity:1}}
134
+ .rvl{animation:fade .6s both}
store.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Long-term memory for the Memory Chatbot (#16).
3
+
4
+ The architecture, in four moves:
5
+ 1. EXTRACT — after each exchange, an LLM pulls durable facts about the user (name, prefs, projects).
6
+ 2. STORE — facts are written to SQLite, keyed by user, deduped. This is what survives across sessions.
7
+ 3. RETRIEVE— on each new turn, the user's stored facts are loaded.
8
+ 4. INJECT — they're placed in the system prompt so the bot "remembers you."
9
+
10
+ This is the distinction the rung teaches: the short-term conversation buffer lives in the request;
11
+ long-term memory lives here, in a store that outlives the session.
12
+ """
13
+ import os
14
+ import sqlite3
15
+ import threading
16
+
17
+ import llm
18
+
19
+ DB = os.environ.get("MEMBOT_DB", os.path.join(os.path.dirname(os.path.abspath(__file__)), "memory.db"))
20
+ _lock = threading.Lock()
21
+
22
+ EXTRACT_SYS = (
23
+ "You maintain a chatbot's LONG-TERM memory of a user. From the latest exchange, extract only DURABLE "
24
+ "facts worth remembering across future sessions — the user's name, stable preferences, ongoing projects, "
25
+ "role, constraints, or personal context they'd expect you to recall later. Do NOT store the assistant's "
26
+ "words, one-off questions, greetings, or transient chit-chat. Return a JSON array of short first-person-"
27
+ "about-the-user fact strings (e.g. [\"Name is Alex\", \"Prefers Python\", \"Building a bakery website\"]). "
28
+ "If nothing durable was shared, return []."
29
+ )
30
+
31
+
32
+ def _conn():
33
+ c = sqlite3.connect(DB)
34
+ c.execute("""CREATE TABLE IF NOT EXISTS facts (
35
+ id INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT NOT NULL, fact TEXT NOT NULL,
36
+ created_at TEXT DEFAULT (datetime('now')))""")
37
+ return c
38
+
39
+
40
+ def get_facts(user_id: str) -> list:
41
+ with _lock, _conn() as c:
42
+ rows = c.execute("SELECT id, fact FROM facts WHERE user_id=? ORDER BY id", (user_id,)).fetchall()
43
+ return [{"id": r[0], "fact": r[1]} for r in rows]
44
+
45
+
46
+ def add_fact(user_id: str, fact: str):
47
+ fact = (fact or "").strip()
48
+ if not fact:
49
+ return
50
+ with _lock, _conn() as c:
51
+ exists = c.execute("SELECT 1 FROM facts WHERE user_id=? AND lower(fact)=lower(?)",
52
+ (user_id, fact)).fetchone()
53
+ if not exists:
54
+ c.execute("INSERT INTO facts (user_id, fact) VALUES (?, ?)", (user_id, fact))
55
+
56
+
57
+ def delete_fact(user_id: str, fact_id: int):
58
+ with _lock, _conn() as c:
59
+ c.execute("DELETE FROM facts WHERE user_id=? AND id=?", (user_id, fact_id))
60
+
61
+
62
+ def clear(user_id: str):
63
+ with _lock, _conn() as c:
64
+ c.execute("DELETE FROM facts WHERE user_id=?", (user_id,))
65
+
66
+
67
+ def remember_from_exchange(user_id: str, user_msg: str, assistant_msg: str) -> list:
68
+ """EXTRACT + STORE. Returns the list of newly-added facts (for UI feedback)."""
69
+ prompt = f"USER SAID: {user_msg}\nASSISTANT REPLIED: {assistant_msg}\n\nExtract durable facts about the user."
70
+ facts = llm.extract_json(EXTRACT_SYS, prompt)
71
+ if not isinstance(facts, list):
72
+ return []
73
+ before = {f["fact"].lower() for f in get_facts(user_id)}
74
+ added = []
75
+ for f in facts:
76
+ if isinstance(f, str) and f.strip() and f.strip().lower() not in before:
77
+ add_fact(user_id, f.strip())
78
+ added.append(f.strip())
79
+ return added
80
+
81
+
82
+ def memory_block(user_id: str) -> str:
83
+ """RETRIEVE + format for INJECTion into the system prompt."""
84
+ facts = get_facts(user_id)
85
+ if not facts:
86
+ return ""
87
+ lines = "\n".join(f"- {f['fact']}" for f in facts)
88
+ return f"\n\nWhat you remember about this user from past sessions:\n{lines}\n"