296 lines
12 KiB
Python
296 lines
12 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
|
|
import json
|
|
import re
|
|
import sys
|
|
import urllib.request
|
|
|
|
import db
|
|
import llama
|
|
import numpy as np
|
|
import 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_path):
|
|
embed_process = llama.start_embed(log=log_path)
|
|
try:
|
|
yield
|
|
finally:
|
|
if embed_process is not None:
|
|
embed_process.terminate()
|
|
|
|
|
|
# Embed texts via the local embedding server, 32 per request, each cut to 2000 chars.
|
|
def embed(texts):
|
|
vectors = []
|
|
for start in range(0, len(texts), 32):
|
|
body = {"input": [text[:2000] for text in texts[start : start + 32]], "model": "bge-m3"}
|
|
response = json.load(
|
|
_open(
|
|
urllib.request.Request(
|
|
API, json.dumps(body).encode(), {"Content-Type": "application/json"}
|
|
),
|
|
timeout=600,
|
|
)
|
|
)
|
|
vectors += [
|
|
item["embedding"] for item in sorted(response["data"], key=lambda item: item["index"])
|
|
]
|
|
matrix = np.array(vectors, dtype=np.float32)
|
|
# L2-normalize so dot products are cosine similarities.
|
|
return matrix / np.maximum(np.linalg.norm(matrix, axis=1, keepdims=True), 1e-9)
|
|
|
|
|
|
# Meeting timestamp from the folder name, e.g. 2026-11-02T14-30-00; "" if none.
|
|
def _stamp(name):
|
|
match = re.search(r"\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d", name)
|
|
return match[0] if match 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 = [row for row in db.connect().execute("SELECT * FROM memory") if pred(row)]
|
|
if not rows:
|
|
return [], None
|
|
return rows, np.frombuffer(b"".join(row["vec"] for row in rows), np.float32).reshape(
|
|
len(rows), -1
|
|
)
|
|
|
|
|
|
# Summary entries may be dicts {"text": ...} or plain strings.
|
|
def _summary_text(item):
|
|
return item["text"] if isinstance(item, dict) else str(item)
|
|
|
|
|
|
# Topic as one string: title (optional), summary, decisions, open questions.
|
|
def _topic_text(topic, title=True):
|
|
parts = (
|
|
([topic["title"]] if title else [])
|
|
+ [_summary_text(item) for item in topic.get("summary", [])]
|
|
+ list(topic.get("decisions", []))
|
|
+ list(topic.get("open_questions", []))
|
|
)
|
|
return (
|
|
". ".join(part for part in parts if part)
|
|
if title
|
|
else " ".join(part for part in parts if part)
|
|
)
|
|
|
|
|
|
# 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
|
|
|
|
report_json = report._load(name, "report.json", None)
|
|
if report_json is None:
|
|
return
|
|
report_json, _ = report.named(name, report_json)
|
|
items = []
|
|
# One item per topic summary, decision, action and open question.
|
|
for topic_index, topic in enumerate(report_json["topics"], 1):
|
|
# Shared fields of every item of this topic: (name, position, start, meeting, date, title, anchor).
|
|
base = (
|
|
name,
|
|
topic_index,
|
|
topic["start_s"],
|
|
report_json["meeting_title"],
|
|
report_json["date"],
|
|
topic["title"],
|
|
slugify(report._head(topic_index, topic), "-"),
|
|
)
|
|
topic_items = [("topic", _topic_text(topic, False))] + [
|
|
("decision", decision) for decision in topic.get("decisions", [])
|
|
]
|
|
topic_items += [
|
|
(
|
|
"action",
|
|
" — ".join(str(action[key]) for key in ("who", "what", "when") if action.get(key)),
|
|
)
|
|
for action in topic.get("actions", [])
|
|
]
|
|
topic_items += [("open_question", question) for question in topic.get("open_questions", [])]
|
|
items += [(base, kind, text) for kind, text in topic_items if text]
|
|
# 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.
|
|
vectors = embed([f"{base[5]}: {text}" for base, _, text in items])
|
|
db.replace_memory(
|
|
name,
|
|
[
|
|
(*base[:2], kind, *base[2:], text, vector.tobytes())
|
|
for (base, kind, text), vector in zip(items, vectors, strict=False)
|
|
],
|
|
)
|
|
print(f"memory: indexed {len(items)} items")
|
|
|
|
|
|
# One excerpt line cited as [n] by the LLM: date, meeting, topic, kind, text.
|
|
def _prev_line(number, row):
|
|
return f"[{number}] {row['date']} «{row['meeting']}» — {row['topic']} ({row['kind']}): {row['text']}"
|
|
|
|
|
|
# Link this meeting's topics to earlier meetings; results go into report.json.
|
|
def _link(name):
|
|
report_json = report._load(name, "report.json", None)
|
|
if report_json is None:
|
|
return
|
|
named_report, _ = report.named(name, report_json)
|
|
# Stamp of this meeting, from its folder name.
|
|
current_stamp = _stamp(name)
|
|
# Only strictly earlier meetings; stamps sort lexicographically.
|
|
rows, matrix = _rows(
|
|
lambda row: current_stamp and _stamp(row["name"]) and _stamp(row["name"]) < current_stamp
|
|
)
|
|
# Clear old links so re-running the step does not accumulate them.
|
|
for topic in report_json["topics"]:
|
|
topic["previous"] = []
|
|
if rows:
|
|
# Query vectors: each current topic as title + content.
|
|
query_vectors = embed([_topic_text(topic) for topic in named_report["topics"]])
|
|
# Cosine similarity matrix: rows = current topics, cols = stored items (both normalized).
|
|
similarity = query_vectors @ matrix.T
|
|
for topic, named_topic, similarities in zip(
|
|
report_json["topics"], named_report["topics"], similarity, strict=False
|
|
):
|
|
# Best K_TOPIC candidates above the MEM_MIN similarity threshold.
|
|
top = [
|
|
index
|
|
for index in np.argsort(-similarities)[:K_TOPIC]
|
|
if similarities[index] >= MEM_MIN
|
|
]
|
|
if not top:
|
|
continue
|
|
actions = "; ".join(
|
|
" — ".join(str(action[key]) for key in ("who", "what", "when") if action.get(key))
|
|
for action in named_topic.get("actions", [])
|
|
)
|
|
# Prompt: current topic, then numbered earlier excerpts the model may cite as [n].
|
|
user = (
|
|
f"ARGOMENTO: {named_topic['title']}\nSINTESI: {' '.join(_summary_text(item) for item in named_topic.get('summary', []))}\nDECISIONI: {'; '.join(named_topic.get('decisions', []))}\n"
|
|
f"AZIONI: {actions}\nDOMANDE APERTE: {'; '.join(named_topic.get('open_questions', []))}\n\nPRECEDENTI:\n"
|
|
+ "\n".join(_prev_line(number, rows[index]) for number, index in enumerate(top, 1))
|
|
)
|
|
# report.chat returns parsed JSON or None; None -> no links.
|
|
response = report.chat(SYS_M, user, 1500) or {}
|
|
# Cap at 4 links per topic (matches the prompt).
|
|
for link in (response.get("links") or [])[:4]:
|
|
# Validate LLM output: ref in range, known status, non-empty text.
|
|
try:
|
|
ref, status, text = int(link["ref"]), link["status"], str(link["text"]).strip()
|
|
except (KeyError, TypeError, ValueError):
|
|
continue
|
|
if 1 <= ref <= len(top) and status in STATUSES and text:
|
|
previous = rows[top[ref - 1]]
|
|
topic["previous"].append(
|
|
{
|
|
"text": text,
|
|
"status": status,
|
|
"name": previous["name"],
|
|
"meeting": previous["meeting"],
|
|
"date": previous["date"],
|
|
"topic": previous["topic"],
|
|
"anchor": previous["anchor"],
|
|
"t": previous["t"],
|
|
}
|
|
)
|
|
# Write links into report.json; run() re-renders from it.
|
|
(db.out_dir(name) / "report.json").write_text(
|
|
json.dumps(report_json, 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 error:
|
|
print("memory link skipped:", repr(error))
|
|
index(name)
|
|
except Exception as error:
|
|
print("memory index skipped:", repr(error))
|
|
# 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(question):
|
|
# Cosine search over the normalized matrix; keep the best K_ASK excerpts.
|
|
rows, matrix = _rows(lambda row: True)
|
|
if not rows:
|
|
yield {"sources": []}
|
|
yield {"t": "Nessuna riunione indicizzata."}
|
|
return
|
|
top = np.argsort(-(matrix @ embed([question])[0]))[:K_ASK]
|
|
selected = [rows[index] for index in top]
|
|
yield {
|
|
"sources": [
|
|
{
|
|
"n": number,
|
|
**{
|
|
key: row[key]
|
|
for key in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")
|
|
},
|
|
}
|
|
for number, row in enumerate(selected, 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: {question}\n\nESTRATTI:\n"
|
|
+ "\n".join(_prev_line(number, row) for number, row in enumerate(selected, 1)),
|
|
},
|
|
],
|
|
}
|
|
for delta in llama.stream(body, 1800):
|
|
yield {"t": delta}
|
|
|
|
|
|
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 path in sorted(db.OUT.glob("*/report.json")):
|
|
index(path.parent.name)
|