From d77eb6d2367dde6adb65b5c7eeeeea050da263d7 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 04:14:58 +0800 Subject: [PATCH] memory: search by meaning, on a small model on this computer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A memory search now finds what means the same in other words or another language ("什么时候上线" finds "Releases go out on Tuesdays"), for the MCP server's memory_search and the Library's Memory tab alike. It is off until switched on under Memory → Search by meaning, since it downloads paraphrase-multilingual-MiniLM-L12-v2 (Xenova's int8 ONNX, ~135 MB, pinned revision, size and sha256 checked); switched off, the model is deleted. - internal/pii/guard: the BERT code runs the embedder too (LoadEmbedder, mean pooling; the tokenizer reads 250,002 pieces and WhitespaceSplit). Its vectors match ONNX Runtime's int8 to cosine >= 0.995 and are no further from fp32 than ORT's own; testdata carries both. - internal/memembed: the switch, the download, vectors.bin keyed by each memory's sha256 (read once, again when the text changes, a cut-short file read as none), Keep reading in the backend, the model let go after 10 minutes unused. - internal/memory: memory.Semantic fuses the meaning ranking with the word ranking by reciprocal rank; a tie goes to the nearer in meaning, since a first word hit may hold one common word ("when do we release" had "Never delete images when..." first). Near 0.30 / Within 0.15 come from 97 real memories and 16 queries, half Chinese for English memories: 12 of 16 sought found with ~4 others each. Rank searches without noting memories used. - GUI: the Search by meaning row (download %, memories read, failures), and the tab's search lists what the backend ranked first (POST /api/memory/rank), then word matches. zh, zh-TW, ja, de. - docs/subsystems/memory.md: the section, out of "Not built yet". Why not multilingual-e5-small, which this was built on first: run for real, its cosines sat at 0.78-0.89 for everything, and a Chinese search ranked Chinese memories over the English one it meant. e5-small, e5-base and MiniLM were compared in ONNX Runtime on the same 97 memories; MiniLM put the sought one first 9 of 16 and in the top 3 12 of 16, with the rest at a median cosine of 0.16. Run before the rebases (mote, on origin/main as of the work): - gofmt -l internal/ clean; go vet of memembed, memory, pii/..., gui, library; GOOS=linux and GOOS=windows vet of memembed and pii/guard. - MAGPIE_EMBED_DIR=~/models/pml go test -run Embedder ./internal/pii/guard: 7 texts (CJK, full width, emoji, digits before runs of spaces) at 0.9962-1.0000 with ORT int8. - go test memembed, memory, memdistill, pii/..., library, browsermcp. - Linux (magpie-desktop, -tags nogui, mote's disk was full): go test memembed, memory, pii/guard, gui (461s), cli (1228s, past the default 10m timeout, so -timeout 30m); gateway -run 'MemoryMCP|OwnMCP'. - Rebased on origin/main 3ebb1ba2c, on mote at this tree: gofmt -l internal/ clean; go vet of memembed, memory, pii/..., library, gui, gateway, and GOOS=linux and GOOS=windows vet of the first four; go test memembed, memory, pii/..., library, browsermcp (Embedder test on ~/models/pml); gateway -run 'MemoryMCP|OwnMCP'; cli -run 'Settings|Parity|Budget'. - Rebased again on origin/main 5d6935b11 (title bar, cli parity, account export, provider catalog): go vet of gui and cli; go test -run 'Settings|Parity|Budget' of cli and gui, ok with the Bark test fix two commits up (TestSettingsSaveKeepsWhatItDoesNotSend, red on main). - GUI on mote, this commit plus the next (90f4a377b, which fixes library-bar-more for #5982): every library-*.test.cjs, i18n-keys and i18n-en-no-cjk, BROWSER=chromium and webkit, 701/702 each. The red is library-loading's tab list, which has no "Claude plugins" (6af54dc9a) and is red alone at origin/main faffb1e95 (#5997). library-bili's webkit saved count times out about 1 run in 3, on main too (#6015). - A real switch-on: the pinned files downloaded from Hugging Face and checked in 11s, 5 memories read; 什么时候上线, 端口被占用怎么办, 清理磁盘, 回复用什么语言 and "when do we release" each find their memory first. 缩进用什么 finds nothing (0.23 to the tabs memory, under Near). - Broken by hand: without the tie rule, TestSearchFindsByMeaning's new case is red (images first). Not run: the whole Go suite and the whole GUI suite; go test of internal/gui and the whole of internal/cli after the rebases (WSL kept restarting, and they passed on Linux before). --- docs/subsystems/memory.md | 47 +- internal/cli/settings_parity_test.go | 3 + internal/gateway/memory_mcp.go | 2 + internal/gui/app.go | 2 + internal/gui/assets/plugins/library/client.js | 82 ++- internal/gui/assets/plugins/library/i18n.js | 28 + internal/gui/library.go | 1 + internal/gui/memory_semantic.go | 74 +++ internal/gui/tests/library-memory.test.cjs | 80 ++- internal/memembed/memembed.go | 495 ++++++++++++++++++ internal/memembed/memembed_test.go | 194 +++++++ internal/memembed/vectors.go | 111 ++++ internal/memory/search.go | 123 ++++- internal/pii/fetch.go | 7 + internal/pii/guard/bert.go | 23 +- internal/pii/guard/embedder.go | 235 +++++++++ internal/pii/guard/embedder_test.go | 73 +++ internal/pii/guard/guard.go | 2 +- internal/pii/guard/guard_test.go | 2 +- internal/pii/guard/testdata/embedder.json | 1 + internal/pii/guard/tokenizer.go | 30 +- 21 files changed, 1574 insertions(+), 41 deletions(-) create mode 100644 internal/gui/memory_semantic.go create mode 100644 internal/memembed/memembed.go create mode 100644 internal/memembed/memembed_test.go create mode 100644 internal/memembed/vectors.go create mode 100644 internal/pii/guard/embedder.go create mode 100644 internal/pii/guard/embedder_test.go create mode 100644 internal/pii/guard/testdata/embedder.json diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index df86b6450..440363d1f 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -210,15 +210,54 @@ off until switched on under Memory → Tidy up every night. and `POST /api/memory/dream/undo`; `GET /api/memory/distill` carries `dreaming`. -## Not built yet +### Search by meaning -Semantic search is planned; today search is by words (`Search`, CJK -split per character, `TestSearch`). +[internal/memembed](../../internal/memembed/memembed.go) ranks a search by +what it means as well as by its words, so "什么时候上线" finds "Releases go +out on Tuesdays". It is off until switched on under Memory → Search by +meaning, since it downloads a model (~135 MB). + +- The model is paraphrase-multilingual-MiniLM-L12-v2, Xenova's int8 ONNX + at a pinned revision, fetched from Hugging Face with each file's size + and sha256 checked (`pii.Fetch`) into + `/paraphrase-multilingual-MiniLM-L12-v2/`. It + runs in Go on the PII guard's BERT code (`guard.LoadEmbedder`); nothing + leaves the computer. Its vectors match ONNX Runtime's to cosine 0.995 + and are no further from fp32 than ONNX Runtime's own + (`TestEmbedderMatchesONNXRuntime`). A search and a memory are read the + same way, with no prefix. multilingual-e5-small was tried first: its + cosines sat in 0.78 to 0.89 for everything, and a Chinese search ranked + Chinese memories over the English one it meant. +- Switched off, the model folder is deleted (`Set`). The switch is + `memory-semantic.json` in the config folder; one that can't be read is + off (`TestNotThereIsWords`). +- What is read: each active or candidate memory's text and why, as an + one text, keyed by its sha256 in `vectors.bin` beside the model, once, + and again when its text changes; vectors of texts gone are dropped + (`TestIndexReadsOnce`). `Keep` reads them in the backend each minute and + on a nudge (`Poke`); a search reads up to 16 missing ones itself, and + with none read yet it is by words while Keep reads. The model is let go + after 10 minutes unused. +- Ranking (`memory.Semantic`, `fuse` in + [search.go](../../internal/memory/search.go)): the memories whose + cosine with the query passes `Near` (0.30) and is within `Within` (0.15) + of the best are fused with the word hits by reciprocal rank (`rrfK` 20), + pinned ×1.2 and non-global ×1.1. Calibrated on 97 real memories and 16 + queries, half in Chinese for English memories: the one sought scored a + median 0.47, the rest a median 0.16; 12 of 16 found with ~4 others each + (`TestSearchFindsByMeaning`). +- Every search goes through it: the MCP server's `memory_search` and the + Memory tab, which asks `POST /api/memory/rank` `{q, status}` (ids, best + first, not noted as used; null while off) and lists what it ranked + first, then what holds the words. `GET`/`POST /api/memory/semantic` + `{on}` give the row its state: the download's progress, the memories + read, and why either failed. ## Verification ```sh -mote-run go test ./internal/memory ./internal/memdistill ./internal/library +mote-run go test ./internal/memory ./internal/memdistill ./internal/memembed ./internal/library +mote-run sh -c 'MAGPIE_EMBED_DIR=$HOME/models/pml go test -run Embedder ./internal/pii/guard' mote-run go test -run 'Distill|Dream' ./internal/gui mote-run go test -tags nogui -run 'MemoryMCP|OwnMCP' ./internal/gateway mote-run go test ./internal/browsermcp ./internal/cli diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 2d6a642e1..8d758fd66 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -402,6 +402,9 @@ var notYet = map[string]string{ "POST /api/memory/dream": L, // memory_distill.go "POST /api/memory/dream/run": L, // memory_distill.go "POST /api/memory/dream/undo": L, // memory_distill.go + "GET /api/memory/semantic": L, // memory_semantic.go + "POST /api/memory/semantic": L, // memory_semantic.go + "POST /api/memory/rank": L, // memory_semantic.go "POST /api/library/skills/regroup": W, // library.go "GET /api/omarchy/widget": W, // omarchy.go "POST /api/omarchy/widget": W, // omarchy.go diff --git a/internal/gateway/memory_mcp.go b/internal/gateway/memory_mcp.go index 572c37bb9..1201fdfcc 100644 --- a/internal/gateway/memory_mcp.go +++ b/internal/gateway/memory_mcp.go @@ -10,6 +10,8 @@ import ( "strings" "time" + // search by meaning, when switched on (memory.Semantic) + _ "github.com/yetone/magpie/internal/memembed" "github.com/yetone/magpie/internal/memory" "github.com/yetone/magpie/internal/usage" ) diff --git a/internal/gui/app.go b/internal/gui/app.go index 7f386ea8c..9585239ae 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -607,6 +607,8 @@ func Run(version string, showMain bool, link string) error { }() // conversations read into memory, when switched on (Memory tab) go keepDistilling(backendCtx) + // memories read for search by meaning, when switched on + go keepEmbedding(backendCtx) // before the item is made, which starts as hidden as AppKit kept it hiddenAtStart := bringTrayBack() diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 537434561..05566f9d6 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -959,6 +959,10 @@ magpie.plugin("library", (ctx) => { let mem = null; // /api/memory let dist = null; // /api/memory/distill: conversations read into memory let distPoll = 0; + let sem = null; // /api/memory/semantic: search by meaning (memembed) + let semPoll = 0; + let memRank = null; // {q, status, ids}: the search's ranking by meaning, best first + let rankT = 0; let memLoading = false; let memQ = ""; // the search typed let memStatus = "active"; @@ -988,13 +992,15 @@ magpie.plugin("library", (ctx) => { if (memLoading) return; memLoading = true; try { - [mem, dist] = await Promise.all([api("memory"), api("memory/distill").catch(() => null)]); + [mem, dist, sem] = await Promise.all([api("memory"), api("memory/distill").catch(() => null), api("memory/semantic").catch(() => null)]); } catch (e) { status(e.message, "err"); } memLoading = false; if (tab === "memory" && mem) render(); distWatch(); + semWatch(); + rankSoon(); } function memDirty() { if (!memOpen || !memDraft) return false; @@ -1069,6 +1075,7 @@ magpie.plugin("library", (ctx) => { row.append(glyph(GLYPH.doc), who, sw); card.append(row); if (dist) card.append(distillRow(), dreamRow()); + if (sem) card.append(semRow()); if (!lib.servers.some((s) => s.name === "magpie-memory")) { const r = el("div", "row lib-row lib-memtools"); const w = el("div", "who"); @@ -1085,21 +1092,25 @@ magpie.plugin("library", (ctx) => { q.type = "search"; q.className = "lib-memq"; q.dataset.lib = "memq"; - q.oninput = () => { memQ = q.value; render(); }; + q.oninput = () => { memQ = q.value; render(); rankSoon(); }; q.onkeydown = (e) => e.stopPropagation(); const sugg = count("candidate"); const st = segs([ ["active", t("In use") + (count("active") ? " · " + count("active") : "")], ...(sugg || memStatus === "candidate" ? [["candidate", t("To review") + (sugg ? " · " + sugg : "")]] : []), ["archived", t("Archived") + (count("archived") ? " · " + count("archived") : "")], - ], memStatus, (v) => { memStatus = v; memOpen = null; render(); }); + ], memStatus, (v) => { memStatus = v; memOpen = null; render(); rankSoon(); }); st.classList.add("lib-memstatus"); const sc = menuButton(memScope ? scopeName(memScope) : t("All"), "lib-memscope", () => openProtoMenu(sc, [{ v: "", name: t("Everywhere and every project"), literalName: true, note: "" }, ...memScopes(true).filter((s) => all.some((m) => m.scope === s)).map((s) => ({ v: s, name: scopeName(s), literalName: true, note: "" }))], memScope, (v) => { memScope = v; render(); }, "Where it applies")); const words = memQ.trim().toLowerCase().split(/\s+/).filter(Boolean); + // with search by meaning on, what it ranked comes first, best first, + // then what holds the words typed and it didn't rank + const ranked = memRank && memRank.q === memQ && memRank.status === memStatus ? memRank.ids : []; + const at = new Map(ranked.map((id, i) => [id, i])); const shown = all.filter((m) => (memStatus === "archived" ? m.status === "archived" || m.status === "superseded" : m.status === memStatus) && (!memScope || m.scope === memScope) - && words.every((w) => [m.text, m.why || "", ...(m.tags || []), kindName(m.kind), scopeName(m.scope)].join(" ").toLowerCase().includes(w))) - .sort((a, b) => (!!b.pinned - !!a.pinned) || (b.updated > a.updated ? 1 : b.updated < a.updated ? -1 : 0)); + && (at.has(m.id) || words.every((w) => [m.text, m.why || "", ...(m.tags || []), kindName(m.kind), scopeName(m.scope)].join(" ").toLowerCase().includes(w)))) + .sort((a, b) => (at.has(b.id) - at.has(a.id)) || (at.get(a.id) - at.get(b.id)) || (!!b.pinned - !!a.pinned) || (b.updated > a.updated ? 1 : b.updated < a.updated ? -1 : 0)); // what's picked is what's listed: a search, a filter or another // status leaves the rest unpicked, and an empty list ends Select memShown = shown; @@ -1325,6 +1336,67 @@ magpie.plugin("library", (ctx) => { r.append(glyph(GLYPH.backup), w, acts); return r; } + // Search by meaning (memembed): a small model on this computer reads + // each memory once, and the search finds what means the same in other + // words or another language. Switched off, the model is deleted. + function semRow() { + const s = sem; + const r = el("div", "row lib-row lib-memsem"); + const w = el("div", "who"); + w.append(el("div", "name", t("Search by meaning"))); + let line = t("Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.", { size: Math.round(s.size / 1e6) + " MB" }); + let err = false; + if (s.on && s.downloading) line = t("Downloading the model · {p}%", { p: Math.floor(100 * s.done / (s.size || 1)) }); + else if (s.on && s.error && !s.installed) { line = t("Couldn't download the model: {error}", { error: s.error }); err = true; } + else if (s.on && s.failed) { line = t("Couldn't read the memories: {error}", { error: s.failed }); err = true; } + else if (s.on && s.installed && s.read < s.of) line = t("Reading the memories · {n} of {m}", { n: s.read, m: s.of }); + else if (s.on && s.installed) line = t("Finds memories that mean what you search for, in any language, on this computer."); + w.append(el("div", "sub" + (err ? " err" : ""), line)); + const acts = el("div", "lib-acts"); + if (s.on && s.error && !s.installed && !s.downloading) acts.append(button(t("Try again"), "action lib-semretry", () => semChange(true))); + acts.append(toggle(s.on, t("Search by meaning"), (on) => semChange(on))); + r.append(glyph(GLYPH.search), w, acts); + return r; + } + async function semChange(on) { + try { + sem = await api("memory/semantic", { on }); + } catch (e) { + status(e.message, "err", 6000); + } + memRank = null; + render(); + semWatch(); + rankSoon(); + } + // while the model downloads or the memories are read, the row is read + // again every 2s + function semWatch() { + clearTimeout(semPoll); + const s = sem; + if (!s?.on || !(s.downloading || s.reading || (s.installed && s.read < s.of && !s.failed))) return; + semPoll = setTimeout(async () => { + if (tab !== "memory") return; + const was = s.installed; + try { sem = await api("memory/semantic"); } catch {} + render(); + semWatch(); + if (!was && sem.installed) rankSoon(); + }, 2000); + } + // the search, ranked by meaning a moment after the typing stops + function rankSoon() { + clearTimeout(rankT); + if (!sem?.on || !sem.installed || !memQ.trim()) { memRank = null; return; } + rankT = setTimeout(async () => { + const q = memQ, st = memStatus; + let r; + try { r = await api("memory/rank", { q, status: st }); } catch { return; } + if (q !== memQ || st !== memStatus || tab !== "memory") return; + memRank = r.ids ? { q, status: st, ids: r.ids } : null; + render(); + }, 250); + } async function distChange(path, body, reload) { try { dist = await api(path, body); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index efcc67cba..ca0a4562f 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -30,6 +30,13 @@ magpie.strings({ "Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "合并重复的记忆,归档过时的记忆。你写的和置顶的保持不变。", "Tidying…": "正在整理…", "Couldn't tidy: {error}": "未能整理:{error}", + "Search by meaning": "按意思搜索", + "Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "按意思找到相关的记忆,不限语言。会下载一个 {size} 的模型,在这台电脑上运行。", + "Downloading the model · {p}%": "正在下载模型 · {p}%", + "Couldn't download the model: {error}": "未能下载模型:{error}", + "Couldn't read the memories: {error}": "未能读取记忆:{error}", + "Reading the memories · {n} of {m}": "正在读取记忆 · {n}/{m}", + "Finds memories that mean what you search for, in any language, on this computer.": "按意思找到相关的记忆,不限语言,在这台电脑上运行。", "Tidied {when} · undone": "{when}整理过 · 已撤销", "Tidied {when} · {m} merged, {a} set aside": "{when}整理过 · 合并 {m} 条,归档 {a} 条", "Nothing to tidy {when}": "{when}没有需要整理的", @@ -986,6 +993,13 @@ magpie.strings({ "Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "合併重複的記憶,封存過時的記憶。你寫的和釘選的保持不變。", "Tidying…": "正在整理…", "Couldn't tidy: {error}": "未能整理:{error}", + "Search by meaning": "依意思搜尋", + "Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "依意思找到相關的記憶,不限語言。會下載一個 {size} 的模型,在這台電腦上執行。", + "Downloading the model · {p}%": "正在下載模型 · {p}%", + "Couldn't download the model: {error}": "無法下載模型:{error}", + "Couldn't read the memories: {error}": "無法讀取記憶:{error}", + "Reading the memories · {n} of {m}": "正在讀取記憶 · {n}/{m}", + "Finds memories that mean what you search for, in any language, on this computer.": "依意思找到相關的記憶,不限語言,在這台電腦上執行。", "Tidied {when} · undone": "{when}整理過 · 已復原", "Tidied {when} · {m} merged, {a} set aside": "{when}整理過 · 合併 {m} 則,封存 {a} 則", "Nothing to tidy {when}": "{when}沒有需要整理的", @@ -1942,6 +1956,13 @@ magpie.strings({ "Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "重複したメモリーをまとめ、古くなったものをアーカイブします。自分で書いたものとピン留めしたものはそのままです。", "Tidying…": "整理中…", "Couldn't tidy: {error}": "整理できませんでした:{error}", + "Search by meaning": "意味で検索", + "Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "意味の近いメモリーを言語を問わず見つけます。このコンピュータで動く {size} のモデルをダウンロードします。", + "Downloading the model · {p}%": "モデルをダウンロード中 · {p}%", + "Couldn't download the model: {error}": "モデルをダウンロードできませんでした:{error}", + "Couldn't read the memories: {error}": "メモリーを読み込めませんでした:{error}", + "Reading the memories · {n} of {m}": "メモリーを読み込み中 · {n}/{m}", + "Finds memories that mean what you search for, in any language, on this computer.": "意味の近いメモリーを言語を問わず、このコンピュータ上で見つけます。", "Tidied {when} · undone": "{when}に整理 · 取り消し済み", "Tidied {when} · {m} merged, {a} set aside": "{when}に整理 · {m} 件をまとめ、{a} 件をアーカイブ", "Nothing to tidy {when}": "{when}:整理するものなし", @@ -2898,6 +2919,13 @@ magpie.strings({ "Merges memories that repeat and sets aside ones out of date. What you wrote or pinned stays.": "Führt doppelte Erinnerungen zusammen und archiviert veraltete. Was du geschrieben oder angeheftet hast, bleibt.", "Tidying…": "Wird aufgeräumt…", "Couldn't tidy: {error}": "Aufräumen fehlgeschlagen: {error}", + "Search by meaning": "Nach Bedeutung suchen", + "Finds memories that mean what you search for, in any language. Downloads a {size} model that runs on this computer.": "Findet Erinnerungen, die meinen, wonach du suchst, in jeder Sprache. Lädt ein {size} großes Modell, das auf diesem Computer läuft.", + "Downloading the model · {p}%": "Modell wird geladen · {p} %", + "Couldn't download the model: {error}": "Modell konnte nicht geladen werden: {error}", + "Couldn't read the memories: {error}": "Erinnerungen konnten nicht gelesen werden: {error}", + "Reading the memories · {n} of {m}": "Erinnerungen werden gelesen · {n} von {m}", + "Finds memories that mean what you search for, in any language, on this computer.": "Findet Erinnerungen, die meinen, wonach du suchst, in jeder Sprache, auf diesem Computer.", "Tidied {when} · undone": "{when} aufgeräumt · rückgängig gemacht", "Tidied {when} · {m} merged, {a} set aside": "{when} aufgeräumt · {m} zusammengeführt, {a} archiviert", "Nothing to tidy {when}": "{when} nichts aufzuräumen", diff --git a/internal/gui/library.go b/internal/gui/library.go index f7956c81c..90de5dcc0 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -177,6 +177,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { browserRoutes(mux, w) memoryRoutes(mux) memoryDistillRoutes(mux) + memorySemanticRoutes(mux) mux.HandleFunc("GET /api/library", func(rw http.ResponseWriter, r *http.Request) { v, err := libraryRead(nil, r.URL.Query().Get("glance") == "1") if err != nil { diff --git a/internal/gui/memory_semantic.go b/internal/gui/memory_semantic.go new file mode 100644 index 000000000..ccf3fc1b2 --- /dev/null +++ b/internal/gui/memory_semantic.go @@ -0,0 +1,74 @@ +package gui + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "time" + + "github.com/yetone/magpie/internal/memembed" + "github.com/yetone/magpie/internal/memory" +) + +// keepEmbedding reads new memories for search by meaning while the +// backend runs, when it is switched on (memembed.Keep). +func keepEmbedding(ctx context.Context) { memembed.Keep(ctx, time.Minute) } + +func memorySemanticRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/memory/semantic", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, memembed.Now()) + }) + // {on}: switched on, the model is fetched when it isn't on disk; + // switched off, it is deleted + mux.HandleFunc("POST /api/memory/semantic", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + On bool `json:"on"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if err := memembed.Set(in.On); err != nil { + fail(rw, err) + return + } + writeJSON(rw, memembed.Now()) + }) + // {q, status}: the Memory tab's search, as an agent's: the ids found, + // best first, without noting them as used. None when search by + // meaning is off: the tab filters by words itself. + mux.HandleFunc("POST /api/memory/rank", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Q string `json:"q"` + Status string `json:"status"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + out := struct { + IDs []string `json:"ids"` + }{} + if strings.TrimSpace(in.Q) == "" || !memembed.On() { + writeJSON(rw, out) + return + } + statuses := []string{in.Status} + if in.Status == memory.Archived { + statuses = append(statuses, memory.Superseded) + } + out.IDs = []string{} + for _, st := range statuses { + hits, err := memory.Rank(memory.Query{Text: in.Q, Status: st, Limit: 200}) + if err != nil { + fail(rw, err) + return + } + for _, h := range hits { + out.IDs = append(out.IDs, h.ID) + } + } + writeJSON(rw, out) + }) +} diff --git a/internal/gui/tests/library-memory.test.cjs b/internal/gui/tests/library-memory.test.cjs index 3eea83730..d352ba6e5 100644 --- a/internal/gui/tests/library-memory.test.cjs +++ b/internal/gui/tests/library-memory.test.cjs @@ -7,7 +7,9 @@ // a