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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import uuid
|
| 6 |
+
import sqlite3
|
| 7 |
+
import hashlib
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import List, Dict, Any, Optional, Tuple
|
| 10 |
+
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
# =========================
|
| 14 |
+
# RFT Memory Receipt Engine
|
| 15 |
+
# =========================
|
| 16 |
+
|
| 17 |
+
BASE_DIR = os.environ.get("RFT_MEM_BASE", "var/rftmem")
|
| 18 |
+
os.makedirs(BASE_DIR, exist_ok=True)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def sha256_str(s: str) -> str:
|
| 22 |
+
return hashlib.sha256(s.encode("utf-8")).hexdigest()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def now_ms() -> int:
|
| 26 |
+
return int(time.time() * 1000)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def atomic_write(path: str, data: bytes) -> None:
|
| 30 |
+
tmp = path + ".tmp"
|
| 31 |
+
with open(tmp, "wb") as f:
|
| 32 |
+
f.write(data)
|
| 33 |
+
f.flush()
|
| 34 |
+
os.fsync(f.fileno())
|
| 35 |
+
os.replace(tmp, path)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def safe_fts_match(user_query: str) -> str:
|
| 39 |
+
"""
|
| 40 |
+
FTS5 MATCH can error on punctuation/special syntax.
|
| 41 |
+
Convert input into a conservative OR query: word1 OR word2 OR ...
|
| 42 |
+
"""
|
| 43 |
+
words = re.findall(r"[A-Za-z0-9_]+", (user_query or "").lower())
|
| 44 |
+
if not words:
|
| 45 |
+
return "___NO_HITS___"
|
| 46 |
+
seen = set()
|
| 47 |
+
uniq = []
|
| 48 |
+
for w in words:
|
| 49 |
+
if w not in seen:
|
| 50 |
+
seen.add(w)
|
| 51 |
+
uniq.append(w)
|
| 52 |
+
return " OR ".join(uniq)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class RetrievalHit:
|
| 57 |
+
event_id: str
|
| 58 |
+
seq: int
|
| 59 |
+
role: str
|
| 60 |
+
text: str
|
| 61 |
+
ts_ms: int
|
| 62 |
+
digest: str
|
| 63 |
+
chain_hash: str
|
| 64 |
+
score: float
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class RFTMemoryStore:
|
| 68 |
+
"""
|
| 69 |
+
Source of truth: append-only JSONL per session + hash-chained ledger.
|
| 70 |
+
Index: SQLite (events table + FTS5) for lexical retrieval.
|
| 71 |
+
Receipts: JSON files saved per assistant turn, downloadable and verifiable.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, base_dir: str):
|
| 75 |
+
self.base_dir = base_dir
|
| 76 |
+
self.db_path = os.path.join(base_dir, "index.sqlite")
|
| 77 |
+
self._init_db()
|
| 78 |
+
|
| 79 |
+
def _init_db(self):
|
| 80 |
+
os.makedirs(self.base_dir, exist_ok=True)
|
| 81 |
+
con = sqlite3.connect(self.db_path)
|
| 82 |
+
cur = con.cursor()
|
| 83 |
+
|
| 84 |
+
cur.execute("""
|
| 85 |
+
CREATE TABLE IF NOT EXISTS events (
|
| 86 |
+
session_id TEXT,
|
| 87 |
+
event_id TEXT PRIMARY KEY,
|
| 88 |
+
seq INTEGER,
|
| 89 |
+
ts_ms INTEGER,
|
| 90 |
+
role TEXT,
|
| 91 |
+
text TEXT,
|
| 92 |
+
digest TEXT,
|
| 93 |
+
prev_hash TEXT,
|
| 94 |
+
chain_hash TEXT,
|
| 95 |
+
collapse REAL
|
| 96 |
+
)
|
| 97 |
+
""")
|
| 98 |
+
|
| 99 |
+
# FTS index
|
| 100 |
+
cur.execute("""
|
| 101 |
+
CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(
|
| 102 |
+
event_id,
|
| 103 |
+
session_id,
|
| 104 |
+
text,
|
| 105 |
+
content=''
|
| 106 |
+
)
|
| 107 |
+
""")
|
| 108 |
+
|
| 109 |
+
cur.execute("""
|
| 110 |
+
CREATE TABLE IF NOT EXISTS receipts (
|
| 111 |
+
receipt_id TEXT PRIMARY KEY,
|
| 112 |
+
session_id TEXT,
|
| 113 |
+
ts_ms INTEGER,
|
| 114 |
+
prompt_hash TEXT,
|
| 115 |
+
response_hash TEXT,
|
| 116 |
+
receipt_path TEXT
|
| 117 |
+
)
|
| 118 |
+
""")
|
| 119 |
+
|
| 120 |
+
con.commit()
|
| 121 |
+
con.close()
|
| 122 |
+
|
| 123 |
+
def session_dir(self, session_id: str) -> str:
|
| 124 |
+
d = os.path.join(self.base_dir, "sessions", session_id)
|
| 125 |
+
os.makedirs(d, exist_ok=True)
|
| 126 |
+
return d
|
| 127 |
+
|
| 128 |
+
def session_log_path(self, session_id: str) -> str:
|
| 129 |
+
return os.path.join(self.session_dir(session_id), "events.jsonl")
|
| 130 |
+
|
| 131 |
+
def receipts_dir(self, session_id: str) -> str:
|
| 132 |
+
d = os.path.join(self.session_dir(session_id), "receipts")
|
| 133 |
+
os.makedirs(d, exist_ok=True)
|
| 134 |
+
return d
|
| 135 |
+
|
| 136 |
+
def collapse_score(self, session_id: str, role: str, text: str) -> float:
|
| 137 |
+
role_w = {"user": 1.0, "tool": 0.9, "assistant": 0.6}.get(role, 0.7)
|
| 138 |
+
tokens = set(t.lower() for t in re.findall(r"[A-Za-z0-9_]+", text or ""))
|
| 139 |
+
if not tokens:
|
| 140 |
+
return 0.0
|
| 141 |
+
|
| 142 |
+
recent = self.get_events(session_id, limit=20)
|
| 143 |
+
recent_tokens = set()
|
| 144 |
+
for e in recent:
|
| 145 |
+
recent_tokens |= set(t.lower() for t in re.findall(r"[A-Za-z0-9_]+", e["text"] or ""))
|
| 146 |
+
|
| 147 |
+
unseen = len(tokens - recent_tokens)
|
| 148 |
+
novelty = unseen / max(1, len(tokens))
|
| 149 |
+
length_factor = min(1.0, len(tokens) / 30.0)
|
| 150 |
+
|
| 151 |
+
score = role_w * (0.65 * novelty + 0.35 * length_factor)
|
| 152 |
+
return float(max(0.0, min(1.0, score)))
|
| 153 |
+
|
| 154 |
+
def _get_last_seq_and_chain(self, session_id: str) -> Tuple[int, str]:
|
| 155 |
+
con = sqlite3.connect(self.db_path)
|
| 156 |
+
cur = con.cursor()
|
| 157 |
+
|
| 158 |
+
cur.execute("SELECT COALESCE(MAX(seq), 0) FROM events WHERE session_id=?", (session_id,))
|
| 159 |
+
last_seq = int(cur.fetchone()[0] or 0)
|
| 160 |
+
|
| 161 |
+
cur.execute("""
|
| 162 |
+
SELECT chain_hash FROM events
|
| 163 |
+
WHERE session_id=?
|
| 164 |
+
ORDER BY seq DESC
|
| 165 |
+
LIMIT 1
|
| 166 |
+
""", (session_id,))
|
| 167 |
+
row = cur.fetchone()
|
| 168 |
+
con.close()
|
| 169 |
+
|
| 170 |
+
last_chain = row[0] if row and row[0] else ("0" * 64)
|
| 171 |
+
return last_seq, last_chain
|
| 172 |
+
|
| 173 |
+
def append_event(self, session_id: str, role: str, text: str) -> Dict[str, Any]:
|
| 174 |
+
event_id = uuid.uuid4().hex
|
| 175 |
+
ts = now_ms()
|
| 176 |
+
|
| 177 |
+
last_seq, prev_chain = self._get_last_seq_and_chain(session_id)
|
| 178 |
+
seq = last_seq + 1
|
| 179 |
+
|
| 180 |
+
payload = {
|
| 181 |
+
"session_id": session_id,
|
| 182 |
+
"event_id": event_id,
|
| 183 |
+
"seq": seq,
|
| 184 |
+
"ts_ms": ts,
|
| 185 |
+
"role": role,
|
| 186 |
+
"text": text
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
digest = sha256_str(json.dumps(payload, sort_keys=True, ensure_ascii=False))
|
| 190 |
+
chain_hash = sha256_str(prev_chain + digest)
|
| 191 |
+
collapse = self.collapse_score(session_id, role, text)
|
| 192 |
+
|
| 193 |
+
rec = {
|
| 194 |
+
**payload,
|
| 195 |
+
"digest": digest,
|
| 196 |
+
"prev_hash": prev_chain,
|
| 197 |
+
"chain_hash": chain_hash,
|
| 198 |
+
"collapse": collapse
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
# Append-only JSONL
|
| 202 |
+
log_path = self.session_log_path(session_id)
|
| 203 |
+
line = (json.dumps(rec, ensure_ascii=False) + "\n").encode("utf-8")
|
| 204 |
+
with open(log_path, "ab") as f:
|
| 205 |
+
f.write(line)
|
| 206 |
+
f.flush()
|
| 207 |
+
os.fsync(f.fileno())
|
| 208 |
+
|
| 209 |
+
# Update indexes
|
| 210 |
+
con = sqlite3.connect(self.db_path)
|
| 211 |
+
cur = con.cursor()
|
| 212 |
+
cur.execute("""
|
| 213 |
+
INSERT INTO events(session_id,event_id,seq,ts_ms,role,text,digest,prev_hash,chain_hash,collapse)
|
| 214 |
+
VALUES(?,?,?,?,?,?,?,?,?,?)
|
| 215 |
+
""", (session_id, event_id, seq, ts, role, text, digest, prev_chain, chain_hash, collapse))
|
| 216 |
+
cur.execute("INSERT INTO events_fts(event_id, session_id, text) VALUES(?,?,?)", (event_id, session_id, text))
|
| 217 |
+
con.commit()
|
| 218 |
+
con.close()
|
| 219 |
+
|
| 220 |
+
return rec
|
| 221 |
+
|
| 222 |
+
def get_events(self, session_id: str, limit: int = 400) -> List[Dict[str, Any]]:
|
| 223 |
+
con = sqlite3.connect(self.db_path)
|
| 224 |
+
cur = con.cursor()
|
| 225 |
+
cur.execute("""
|
| 226 |
+
SELECT event_id, seq, ts_ms, role, text, digest, prev_hash, chain_hash, collapse
|
| 227 |
+
FROM events
|
| 228 |
+
WHERE session_id=?
|
| 229 |
+
ORDER BY seq ASC
|
| 230 |
+
LIMIT ?
|
| 231 |
+
""", (session_id, int(limit)))
|
| 232 |
+
rows = cur.fetchall()
|
| 233 |
+
con.close()
|
| 234 |
+
|
| 235 |
+
out = []
|
| 236 |
+
for r in rows:
|
| 237 |
+
out.append({
|
| 238 |
+
"event_id": r[0],
|
| 239 |
+
"seq": int(r[1] or 0),
|
| 240 |
+
"ts_ms": r[2],
|
| 241 |
+
"role": r[3],
|
| 242 |
+
"text": r[4],
|
| 243 |
+
"digest": r[5],
|
| 244 |
+
"prev_hash": r[6],
|
| 245 |
+
"chain_hash": r[7],
|
| 246 |
+
"collapse": float(r[8] or 0.0),
|
| 247 |
+
})
|
| 248 |
+
return out
|
| 249 |
+
|
| 250 |
+
def search_lexical(self, session_id: str, query: str, k: int = 8) -> List[RetrievalHit]:
|
| 251 |
+
match = safe_fts_match(query)
|
| 252 |
+
|
| 253 |
+
con = sqlite3.connect(self.db_path)
|
| 254 |
+
cur = con.cursor()
|
| 255 |
+
cur.execute("""
|
| 256 |
+
SELECT e.event_id, e.seq, e.role, e.text, e.ts_ms, e.digest, e.chain_hash,
|
| 257 |
+
bm25(events_fts) as rank
|
| 258 |
+
FROM events_fts
|
| 259 |
+
JOIN events e ON e.event_id = events_fts.event_id
|
| 260 |
+
WHERE events_fts.text MATCH ? AND e.session_id=?
|
| 261 |
+
ORDER BY rank ASC
|
| 262 |
+
LIMIT ?
|
| 263 |
+
""", (match, session_id, int(k)))
|
| 264 |
+
rows = cur.fetchall()
|
| 265 |
+
con.close()
|
| 266 |
+
|
| 267 |
+
hits = []
|
| 268 |
+
for (eid, seq, role, text, ts, digest, chain_hash, rank) in rows:
|
| 269 |
+
r = float(rank if rank is not None else 0.0)
|
| 270 |
+
score = 1.0 / (1.0 + max(0.0, r))
|
| 271 |
+
hits.append(RetrievalHit(eid, int(seq or 0), role, text, ts, digest, chain_hash, score))
|
| 272 |
+
return hits
|
| 273 |
+
|
| 274 |
+
def write_receipt(self, session_id: str, user_text: str, retrieved: List[RetrievalHit], prompt: str, response: str) -> str:
|
| 275 |
+
receipt_id = uuid.uuid4().hex
|
| 276 |
+
ts = now_ms()
|
| 277 |
+
|
| 278 |
+
receipt = {
|
| 279 |
+
"receipt_id": receipt_id,
|
| 280 |
+
"session_id": session_id,
|
| 281 |
+
"ts_ms": ts,
|
| 282 |
+
"query": user_text,
|
| 283 |
+
"retrieval": [{
|
| 284 |
+
"event_id": h.event_id,
|
| 285 |
+
"seq": h.seq,
|
| 286 |
+
"role": h.role,
|
| 287 |
+
"text": h.text,
|
| 288 |
+
"score": h.score,
|
| 289 |
+
"digest": h.digest,
|
| 290 |
+
"chain_hash": h.chain_hash
|
| 291 |
+
} for h in retrieved],
|
| 292 |
+
"prompt_hash": sha256_str(prompt),
|
| 293 |
+
"response_hash": sha256_str(response),
|
| 294 |
+
"engine": {
|
| 295 |
+
"name": "RFT Memory Receipt Engine",
|
| 296 |
+
"version": "0.2",
|
| 297 |
+
"method": "append-only ledger + FTS retrieval + hash-chain receipts"
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
path = os.path.join(self.receipts_dir(session_id), f"{receipt_id}.json")
|
| 302 |
+
atomic_write(path, json.dumps(receipt, indent=2, ensure_ascii=False).encode("utf-8"))
|
| 303 |
+
|
| 304 |
+
con = sqlite3.connect(self.db_path)
|
| 305 |
+
cur = con.cursor()
|
| 306 |
+
cur.execute("""
|
| 307 |
+
INSERT INTO receipts(receipt_id, session_id, ts_ms, prompt_hash, response_hash, receipt_path)
|
| 308 |
+
VALUES(?,?,?,?,?,?)
|
| 309 |
+
""", (receipt_id, session_id, ts, receipt["prompt_hash"], receipt["response_hash"], path))
|
| 310 |
+
con.commit()
|
| 311 |
+
con.close()
|
| 312 |
+
|
| 313 |
+
return path
|
| 314 |
+
|
| 315 |
+
def verify_receipt(self, receipt_json: Dict[str, Any]) -> Tuple[bool, str]:
|
| 316 |
+
session_id = receipt_json.get("session_id")
|
| 317 |
+
if not session_id:
|
| 318 |
+
return False, "Missing session_id."
|
| 319 |
+
|
| 320 |
+
con = sqlite3.connect(self.db_path)
|
| 321 |
+
cur = con.cursor()
|
| 322 |
+
|
| 323 |
+
for item in receipt_json.get("retrieval", []):
|
| 324 |
+
eid = item.get("event_id")
|
| 325 |
+
expected_digest = item.get("digest")
|
| 326 |
+
expected_chain = item.get("chain_hash")
|
| 327 |
+
|
| 328 |
+
cur.execute("SELECT digest, chain_hash FROM events WHERE event_id=? AND session_id=?", (eid, session_id))
|
| 329 |
+
row = cur.fetchone()
|
| 330 |
+
if not row:
|
| 331 |
+
con.close()
|
| 332 |
+
return False, f"Event not found: {eid}"
|
| 333 |
+
if row[0] != expected_digest:
|
| 334 |
+
con.close()
|
| 335 |
+
return False, f"Digest mismatch for {eid}"
|
| 336 |
+
if row[1] != expected_chain:
|
| 337 |
+
con.close()
|
| 338 |
+
return False, f"Chain hash mismatch for {eid}"
|
| 339 |
+
|
| 340 |
+
con.close()
|
| 341 |
+
return True, "Receipt verified: all referenced events exist and hashes match."
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
store = RFTMemoryStore(BASE_DIR)
|
| 345 |
+
|
| 346 |
+
EXAMPLE_PROMPTS = [
|
| 347 |
+
"Store this: Dog=Nova, City=Manchester, Drink=Pepsi Max.",
|
| 348 |
+
"What is my dog's name?",
|
| 349 |
+
"What city did I say?",
|
| 350 |
+
"My drink is Coke Zero now. This overrides earlier.",
|
| 351 |
+
"What is my favourite drink?",
|
| 352 |
+
"Search for: Nova",
|
| 353 |
+
"Search for: Manchester",
|
| 354 |
+
]
|
| 355 |
+
|
| 356 |
+
GUIDED_DEMO_STEPS = [
|
| 357 |
+
"My name is Liam. Remember that.",
|
| 358 |
+
"Store these exactly: Dog = Nova. City = Manchester. Favourite drink = Pepsi Max.",
|
| 359 |
+
"What’s my dog’s name?",
|
| 360 |
+
"What city did I say?",
|
| 361 |
+
"My favourite drink is Coke Zero now. This overrides earlier.",
|
| 362 |
+
"What’s my favourite drink?",
|
| 363 |
+
"Search for 'Nova' and show the matching memory line.",
|
| 364 |
+
"Search for 'Coke' and show the matching memory line.",
|
| 365 |
+
]
|
| 366 |
+
|
| 367 |
+
HOW_TO_MD = """
|
| 368 |
+
# How to use this Space
|
| 369 |
+
|
| 370 |
+
## What to write
|
| 371 |
+
- Store facts: “My name is Liam.” / “Dog=Nova, City=Manchester.”
|
| 372 |
+
- Ask for recall: “What’s my dog’s name?”
|
| 373 |
+
- Override old facts: “My drink is Coke Zero now. This overrides earlier.”
|
| 374 |
+
- Search deliberately: “Nova”, “Manchester”, “Coke”.
|
| 375 |
+
|
| 376 |
+
## What to expect
|
| 377 |
+
- Every message is stored in an append-only ledger.
|
| 378 |
+
- Each turn retrieves a fixed number (K) of memory slices.
|
| 379 |
+
- Each turn generates a receipt listing exactly what was retrieved.
|
| 380 |
+
- Receipt verification proves the referenced events exist and hashes match.
|
| 381 |
+
|
| 382 |
+
## Who this is useful for
|
| 383 |
+
- Agent builders needing restart continuity
|
| 384 |
+
- Teams needing auditability (“show what influenced the output”)
|
| 385 |
+
- Debugging long-lived workflows without replaying full history
|
| 386 |
+
- Anyone controlling token spend via fixed retrieval budgets
|
| 387 |
+
|
| 388 |
+
## Why it matters
|
| 389 |
+
Storing logs is easy. Proving influence is the hard part.
|
| 390 |
+
Receipts turn memory into something inspectable and defensible.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def new_session_id() -> str:
|
| 395 |
+
return uuid.uuid4().hex
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def events_to_messages(events: List[Dict[str, Any]]) -> List[Dict[str, str]]:
|
| 399 |
+
msgs = []
|
| 400 |
+
for e in events:
|
| 401 |
+
if e["role"] in ("user", "assistant"):
|
| 402 |
+
msgs.append({"role": e["role"], "content": e["text"]})
|
| 403 |
+
return msgs
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def format_ledger(events: List[Dict[str, Any]]) -> str:
|
| 407 |
+
lines = []
|
| 408 |
+
for e in events[-250:]:
|
| 409 |
+
t = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(e["ts_ms"] / 1000))
|
| 410 |
+
lines.append(
|
| 411 |
+
f"{t} | seq={e['seq']} | {e['role']}\n"
|
| 412 |
+
f"{e['text']}\n"
|
| 413 |
+
f"event_id={e['event_id']} collapse={e['collapse']:.2f}\n"
|
| 414 |
+
f"digest={e['digest']}\n"
|
| 415 |
+
f"chain={e['chain_hash']}\n"
|
| 416 |
+
f"{'-'*72}"
|
| 417 |
+
)
|
| 418 |
+
return "\n".join(lines)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def build_prompt(user_msg: str, hits: List[RetrievalHit]) -> str:
|
| 422 |
+
memories = "\n".join([f"- ({h.role}) {h.text}" for h in hits]) if hits else "(none)"
|
| 423 |
+
return (
|
| 424 |
+
"SYSTEM: Use retrieved memory slices if relevant. Prefer exact stored facts.\n"
|
| 425 |
+
f"RETRIEVED MEMORIES:\n{memories}\n\n"
|
| 426 |
+
f"USER:\n{user_msg}\n"
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def response_from_retrieval(hits: List[RetrievalHit]) -> str:
|
| 431 |
+
if not hits:
|
| 432 |
+
return "No matching memory slices were retrieved for this query."
|
| 433 |
+
lines = ["Retrieved memory slices:"]
|
| 434 |
+
for h in hits:
|
| 435 |
+
lines.append(f"- {h.score:.4f} | {h.role} | {h.text}")
|
| 436 |
+
return "\n".join(lines)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def chat_turn(session_id: str, user_msg: str, retrieval_k: int):
|
| 440 |
+
if not session_id:
|
| 441 |
+
session_id = new_session_id()
|
| 442 |
+
|
| 443 |
+
store.append_event(session_id, "user", user_msg)
|
| 444 |
+
|
| 445 |
+
hits = store.search_lexical(session_id, user_msg, k=int(retrieval_k))
|
| 446 |
+
prompt = build_prompt(user_msg, hits)
|
| 447 |
+
response = response_from_retrieval(hits)
|
| 448 |
+
|
| 449 |
+
store.append_event(session_id, "assistant", response)
|
| 450 |
+
|
| 451 |
+
receipt_path = store.write_receipt(session_id, user_msg, hits, prompt, response)
|
| 452 |
+
|
| 453 |
+
events = store.get_events(session_id, limit=900)
|
| 454 |
+
ledger = format_ledger(events)
|
| 455 |
+
retrieved_view = "\n".join([f"{h.score:.4f} | {h.role} | {h.text}" for h in hits]) if hits else "(none)"
|
| 456 |
+
messages = events_to_messages(events)
|
| 457 |
+
|
| 458 |
+
return session_id, messages, retrieved_view, ledger, receipt_path
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def run_guided_demo(session_id: str, retrieval_k: int):
|
| 462 |
+
if not session_id:
|
| 463 |
+
session_id = new_session_id()
|
| 464 |
+
|
| 465 |
+
last_receipt = ""
|
| 466 |
+
last_retrieved = ""
|
| 467 |
+
last_ledger = ""
|
| 468 |
+
for step in GUIDED_DEMO_STEPS:
|
| 469 |
+
session_id, messages, last_retrieved, last_ledger, last_receipt = chat_turn(session_id, step, retrieval_k)
|
| 470 |
+
|
| 471 |
+
return session_id, messages, last_retrieved, last_ledger, last_receipt
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def manual_search(session_id: str, query: str, k: int) -> str:
|
| 475 |
+
if not session_id:
|
| 476 |
+
return "(no session)"
|
| 477 |
+
hits = store.search_lexical(session_id, query, k=int(k))
|
| 478 |
+
if not hits:
|
| 479 |
+
return "(no hits)"
|
| 480 |
+
out = []
|
| 481 |
+
for h in hits:
|
| 482 |
+
out.append(
|
| 483 |
+
f"{h.score:.4f} | seq={h.seq} | {h.role}\n"
|
| 484 |
+
f"{h.text}\n"
|
| 485 |
+
f"event_id={h.event_id}\n"
|
| 486 |
+
f"digest={h.digest}\n"
|
| 487 |
+
f"chain={h.chain_hash}\n"
|
| 488 |
+
f"{'-'*60}"
|
| 489 |
+
)
|
| 490 |
+
return "\n".join(out)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def verify_uploaded_receipt(file_obj) -> str:
|
| 494 |
+
if file_obj is None:
|
| 495 |
+
return "Upload a receipt JSON file."
|
| 496 |
+
with open(file_obj.name, "r", encoding="utf-8") as f:
|
| 497 |
+
data = json.load(f)
|
| 498 |
+
ok, msg = store.verify_receipt(data)
|
| 499 |
+
return f"{'✅' if ok else '❌'} {msg}"
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def reset_session():
|
| 503 |
+
sid = new_session_id()
|
| 504 |
+
return sid, [], "", "", None
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def fill_example(selected: str) -> str:
|
| 508 |
+
return selected or ""
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
with gr.Blocks(title="RFT Memory Receipt Engine") as demo:
|
| 512 |
+
gr.Markdown("# RFT Memory Receipt Engine\nLocal persistence + lexical retrieval + verifiable receipts.")
|
| 513 |
+
|
| 514 |
+
with gr.Row():
|
| 515 |
+
session_id = gr.Textbox(label="Session ID", value=new_session_id())
|
| 516 |
+
new_sess_btn = gr.Button("New Session", variant="secondary")
|
| 517 |
+
|
| 518 |
+
retrieval_k = gr.Slider(1, 20, value=8, step=1, label="Retrieval K")
|
| 519 |
+
|
| 520 |
+
with gr.Tabs():
|
| 521 |
+
with gr.Tab("Chat"):
|
| 522 |
+
chatbot = gr.Chatbot(label="Conversation", height=320, type="messages")
|
| 523 |
+
|
| 524 |
+
with gr.Row():
|
| 525 |
+
example_pick = gr.Dropdown(label="Example prompts", choices=EXAMPLE_PROMPTS, value=EXAMPLE_PROMPTS[0])
|
| 526 |
+
use_example = gr.Button("Use Example", variant="secondary")
|
| 527 |
+
|
| 528 |
+
user_msg = gr.Textbox(label="Message", placeholder="Type a message…")
|
| 529 |
+
send = gr.Button("Send", variant="primary")
|
| 530 |
+
|
| 531 |
+
retrieved_out = gr.Textbox(label="Retrieved memory slices", lines=8)
|
| 532 |
+
ledger_out = gr.Textbox(label="Session ledger (hash-chained)", lines=14)
|
| 533 |
+
|
| 534 |
+
receipt_path = gr.Textbox(label="Last receipt path (server)", lines=1)
|
| 535 |
+
receipt_file = gr.File(label="Download last receipt JSON")
|
| 536 |
+
|
| 537 |
+
use_example.click(fill_example, inputs=[example_pick], outputs=[user_msg])
|
| 538 |
+
|
| 539 |
+
send.click(
|
| 540 |
+
chat_turn,
|
| 541 |
+
inputs=[session_id, user_msg, retrieval_k],
|
| 542 |
+
outputs=[session_id, chatbot, retrieved_out, ledger_out, receipt_path],
|
| 543 |
+
).then(lambda p: p, inputs=[receipt_path], outputs=[receipt_file])
|
| 544 |
+
|
| 545 |
+
with gr.Tab("Guided Demo"):
|
| 546 |
+
gr.Markdown("Runs a scripted set of messages to show storage, recall, overrides, search, and receipts.")
|
| 547 |
+
run_demo_btn = gr.Button("Run Guided Demo", variant="primary")
|
| 548 |
+
|
| 549 |
+
demo_chatbot = gr.Chatbot(label="Demo conversation", height=320, type="messages")
|
| 550 |
+
demo_retrieved = gr.Textbox(label="Last retrieved memory slices", lines=8)
|
| 551 |
+
demo_ledger = gr.Textbox(label="Ledger after demo", lines=14)
|
| 552 |
+
demo_receipt_path = gr.Textbox(label="Last demo receipt path (server)", lines=1)
|
| 553 |
+
demo_receipt_file = gr.File(label="Download last demo receipt JSON")
|
| 554 |
+
|
| 555 |
+
run_demo_btn.click(
|
| 556 |
+
run_guided_demo,
|
| 557 |
+
inputs=[session_id, retrieval_k],
|
| 558 |
+
outputs=[session_id, demo_chatbot, demo_retrieved, demo_ledger, demo_receipt_path],
|
| 559 |
+
).then(lambda p: p, inputs=[demo_receipt_path], outputs=[demo_receipt_file])
|
| 560 |
+
|
| 561 |
+
with gr.Tab("Manual Search"):
|
| 562 |
+
q = gr.Textbox(label="Search query", placeholder="Type keywords…")
|
| 563 |
+
do_search = gr.Button("Search", variant="primary")
|
| 564 |
+
results = gr.Textbox(label="Results", lines=14)
|
| 565 |
+
do_search.click(manual_search, inputs=[session_id, q, retrieval_k], outputs=[results])
|
| 566 |
+
|
| 567 |
+
with gr.Tab("Verify Receipt"):
|
| 568 |
+
receipt_upload = gr.File(label="Upload a receipt JSON")
|
| 569 |
+
verify_btn = gr.Button("Verify", variant="primary")
|
| 570 |
+
verify_out = gr.Textbox(label="Verification result")
|
| 571 |
+
verify_btn.click(verify_uploaded_receipt, inputs=[receipt_upload], outputs=[verify_out])
|
| 572 |
+
|
| 573 |
+
with gr.Tab("How to Use"):
|
| 574 |
+
gr.Markdown(HOW_TO_MD)
|
| 575 |
+
|
| 576 |
+
new_sess_btn.click(
|
| 577 |
+
reset_session,
|
| 578 |
+
inputs=[],
|
| 579 |
+
outputs=[session_id, chatbot, retrieved_out, ledger_out, receipt_file],
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
demo.launch()
|