176 lines
9.9 KiB
Python
176 lines
9.9 KiB
Python
# /// script
|
|
# requires-python = ">=3.10,<3.13"
|
|
# dependencies = ["numpy", "markdown"]
|
|
# ///
|
|
"""Cross-meeting memory: bge-m3 embeddings of topics/decisions/actions/open questions in meetings.db.
|
|
uv run --script memory.py --reindex"""
|
|
import contextlib, json, re, sys, urllib.request
|
|
import numpy as np
|
|
import db, llama, report
|
|
|
|
# bge-m3 embeddings endpoint on the local embedding server.
|
|
API = f"http://127.0.0.1:{llama.EMBED_PORT}/v1/embeddings"
|
|
# MEM_MIN: min cosine to link; K_TOPIC: candidates per topic; K_ASK: excerpts for a question.
|
|
MEM_MIN, K_TOPIC, K_ASK = 0.55, 6, 12
|
|
# Direct opener bypassing the corp proxy (the embedding server is localhost).
|
|
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
|
|
# Italian prompt: link current-meeting topics to earlier excerpts; JSON output.
|
|
SYS_M = ('Hai un argomento della riunione attuale ed estratti numerati di riunioni precedenti. Rispondi SOLO JSON: {"links":[{"text":str,"ref":int,"status":"confermato"|"cambiato"|"aperto"|"contesto"}]}. '
|
|
'"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. '
|
|
'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.')
|
|
# Prompt for ask(): answer from numbered excerpts only, cite as [n].
|
|
SYS_ASK = 'Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi in testo semplice (niente JSON). Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.'
|
|
# Valid link statuses; anything else from the LLM is dropped.
|
|
STATUSES = {"confermato", "cambiato", "aperto", "contesto"}
|
|
|
|
|
|
# Start the CPU embedding server for the block; stop it on exit only if this call started it.
|
|
@contextlib.contextmanager
|
|
def embedder(log):
|
|
p = llama.start_embed(log=log)
|
|
try: yield
|
|
finally:
|
|
if p is not None: p.terminate()
|
|
|
|
|
|
# Embed texts via the local embedding server, 32 per request, each cut to 2000 chars.
|
|
def embed(texts):
|
|
out = []
|
|
for i in range(0, len(texts), 32):
|
|
body = {"input": [x[:2000] for x in texts[i:i + 32]], "model": "bge-m3"}
|
|
r = json.load(_open(urllib.request.Request(API, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=600))
|
|
out += [d["embedding"] for d in sorted(r["data"], key=lambda d: d["index"])]
|
|
v = np.array(out, dtype=np.float32)
|
|
# L2-normalize so dot products are cosine similarities.
|
|
return v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9)
|
|
|
|
|
|
# Meeting timestamp from the folder name, e.g. 2026-11-02T14-30-00; "" if none.
|
|
def _stamp(n):
|
|
m = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", n)
|
|
return m[0] if m else ""
|
|
|
|
|
|
# Load memory rows matching pred and stack their vectors into an (n, dim) matrix.
|
|
def _rows(pred):
|
|
# ponytail: brute-force cosine over all rows; switch to sqlite-vec when rows > ~100k.
|
|
rows = [r for r in db.connect().execute("SELECT * FROM memory") if pred(r)]
|
|
if not rows: return [], None
|
|
return rows, np.frombuffer(b"".join(r["vec"] for r in rows), np.float32).reshape(len(rows), -1)
|
|
|
|
|
|
# Summary entries may be dicts {"text": ...} or plain strings.
|
|
def _txt(x): return x["text"] if isinstance(x, dict) else str(x)
|
|
|
|
|
|
# Topic as one string: title (optional), summary, decisions, open questions.
|
|
def _topic_text(t, title=True):
|
|
parts = ([t["title"]] if title else []) + [_txt(x) for x in t.get("summary", [])] + list(t.get("decisions", [])) + list(t.get("open_questions", []))
|
|
return ". ".join(p for p in parts if p) if title else " ".join(p for p in parts if p)
|
|
|
|
|
|
# Embed one meeting's report items into the memory table (replaces its previous rows).
|
|
def index(name):
|
|
# slugify matches the report's heading anchors.
|
|
from markdown.extensions.toc import slugify
|
|
rep = report._load(name, "report.json", None)
|
|
if rep is None: return
|
|
rep, _ = report.named(name, rep)
|
|
items = []
|
|
# One item per topic summary, decision, action and open question.
|
|
for i, t in enumerate(rep["topics"], 1):
|
|
# Shared fields of every item of this topic: (name, position, start, meeting, date, title, anchor).
|
|
base = (name, i, t["start_s"], rep["meeting_title"], rep["date"], t["title"], slugify(report._head(i, t), "-"))
|
|
its = [("topic", _topic_text(t, False))] + [("decision", x) for x in t.get("decisions", [])]
|
|
its += [("action", " — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k))) for a in t.get("actions", [])]
|
|
its += [("open_question", x) for x in t.get("open_questions", [])]
|
|
items += [(base, k, x) for k, x in its if x]
|
|
# Nothing to index: clear the old rows for this meeting.
|
|
if not items: db.replace_memory(name, []); return
|
|
# Prefix the title so each item's vector carries its topic context.
|
|
V = embed([f"{b[5]}: {x}" for b, _, x in items])
|
|
db.replace_memory(name, [(*b[:2], k, *b[2:], x, v.tobytes()) for (b, k, x), v in zip(items, V)])
|
|
print(f"memory: indexed {len(items)} items")
|
|
|
|
|
|
# One excerpt line cited as [n] by the LLM: date, meeting, topic, kind, text.
|
|
def _prev_line(n, r): return f"[{n}] {r['date']} «{r['meeting']}» — {r['topic']} ({r['kind']}): {r['text']}"
|
|
|
|
|
|
# Link this meeting's topics to earlier meetings; results go into report.json.
|
|
def _link(name):
|
|
rep = report._load(name, "report.json", None)
|
|
if rep is None: return
|
|
named_rep, _ = report.named(name, rep)
|
|
# Stamp of this meeting, from its folder name.
|
|
cur = _stamp(name)
|
|
# Only strictly earlier meetings; stamps sort lexicographically.
|
|
rows, M = _rows(lambda r: cur and _stamp(r["name"]) and _stamp(r["name"]) < cur)
|
|
# Clear old links so re-running the step does not accumulate them.
|
|
for t in rep["topics"]: t["previous"] = []
|
|
if rows:
|
|
# Query vectors: each current topic as title + content.
|
|
Q = embed([_topic_text(t) for t in named_rep["topics"]])
|
|
# Cosine similarity matrix: rows = current topics, cols = stored items (both normalized).
|
|
S = Q @ M.T
|
|
for t, nt, s in zip(rep["topics"], named_rep["topics"], S):
|
|
# Best K_TOPIC candidates above the MEM_MIN similarity threshold.
|
|
top = [j for j in np.argsort(-s)[:K_TOPIC] if s[j] >= MEM_MIN]
|
|
if not top: continue
|
|
acts = "; ".join(" — ".join(str(a[k]) for k in ("who", "what", "when") if a.get(k)) for a in nt.get("actions", []))
|
|
# Prompt: current topic, then numbered earlier excerpts the model may cite as [n].
|
|
user = (f"ARGOMENTO: {nt['title']}\nSINTESI: {' '.join(_txt(x) for x in nt.get('summary', []))}\nDECISIONI: {'; '.join(nt.get('decisions', []))}\n"
|
|
f"AZIONI: {acts}\nDOMANDE APERTE: {'; '.join(nt.get('open_questions', []))}\n\nPRECEDENTI:\n"
|
|
+ "\n".join(_prev_line(n, rows[j]) for n, j in enumerate(top, 1)))
|
|
# report.chat returns parsed JSON or None; None -> no links.
|
|
r = report.chat(SYS_M, user, 1500) or {}
|
|
# Cap at 4 links per topic (matches the prompt).
|
|
for l in (r.get("links") or [])[:4]:
|
|
# Validate LLM output: ref in range, known status, non-empty text.
|
|
try: ref, st, tx = int(l["ref"]), l["status"], str(l["text"]).strip()
|
|
except (KeyError, TypeError, ValueError): continue
|
|
if 1 <= ref <= len(top) and st in STATUSES and tx:
|
|
p = rows[top[ref - 1]]
|
|
t["previous"].append({"text": tx, "status": st, "name": p["name"], "meeting": p["meeting"], "date": p["date"],
|
|
"topic": p["topic"], "anchor": p["anchor"], "t": p["t"]})
|
|
# Write links into report.json; run() re-renders from it.
|
|
(db.out_dir(name) / "report.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
|
|
|
|
def run(name, link=True):
|
|
"""Flow step: link to earlier meetings, index this one, render. Memory problems never fail the flow."""
|
|
try:
|
|
# Embedder lives for linking and indexing; its log sits with the meeting logs.
|
|
with embedder(db.logs(name) / "embed.log"):
|
|
if link:
|
|
try: _link(name)
|
|
except Exception as e: print("memory link skipped:", repr(e))
|
|
index(name)
|
|
except Exception as e: print("memory index skipped:", repr(e))
|
|
# Render even when the memory steps failed.
|
|
report.render(name)
|
|
|
|
|
|
# Q&A across all indexed meetings: top-K excerpts -> LLM answer citing [n].
|
|
# Generator: first {"sources": [...]}, then {"t": text delta} events as the model writes.
|
|
def ask_stream(q):
|
|
# Cosine search over the normalized matrix; keep the best K_ASK excerpts.
|
|
rows, M = _rows(lambda r: True)
|
|
if not rows: yield {"sources": []}; yield {"t": "Nessuna riunione indicizzata."}; return
|
|
top = np.argsort(-(M @ embed([q])[0]))[:K_ASK]
|
|
rs = [rows[j] for j in top]
|
|
yield {"sources": [{"n": n, **{k: x[k] for k in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")}} for n, x in enumerate(rs, 1)]}
|
|
body = {"temperature": 0.2, "max_tokens": 1500, "chat_template_kwargs": {"enable_thinking": False},
|
|
"messages": [{"role": "system", "content": SYS_ASK},
|
|
{"role": "user", "content": f"DOMANDA: {q}\n\nESTRATTI:\n" + "\n".join(_prev_line(n, x) for n, x in enumerate(rs, 1))}]}
|
|
for d in llama.stream(body, 1800): yield {"t": d}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Force UTF-8 so Italian text prints correctly on Windows consoles.
|
|
sys.stdout.reconfigure(encoding="utf-8")
|
|
# CLI: rebuild the memory index for every meeting that has a report.json.
|
|
if "--reindex" in sys.argv:
|
|
with embedder(db.GLOBAL / "embed.log"):
|
|
for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name)
|