Implementation:0xK3vin MegaMemory Embeddings Module
| Knowledge Sources | |
|---|---|
| Domains | Embeddings, Semantic_Search |
| Last Updated | 2026-10-27 12:00 GMT |
Overview
Concrete module for generating and comparing local text embeddings provided by the MegaMemory library.
Description
The Embeddings Module (src/embeddings.ts) generates 384-dimensional sentence embeddings in-process using the ONNX-quantized Xenova/all-MiniLM-L6-v2 model via @xenova/transformers. It needs no API keys or network calls after the first model download. The module exposes:
- embed — produce a mean-pooled, L2-normalized embedding Buffer for a text string
- embeddingText — compose the searchable text ("kind: name — summary") used to embed concept nodes
- cosineSimilarity — brute-force cosine similarity between two embedding Buffers
- findTopK — rank candidate nodes by similarity to a query embedding and return the top K
- initializeEmbeddings — preload the model pipeline (used by the web server for best-effort readiness)
All vectors are stored as raw float32 Buffers (384 × 4 = 1536 bytes).
Usage
Import this module whenever you need to:
- Embed a natural-language query before semantic search (understand tool, /api/search)
- Generate an embedding for a new or updated concept node (createConcept, updateConcept, resolveConflict)
- Preload the model so the first search is fast (runServe)
- Compute similarity between two embedding Buffers directly
Code Reference
Source Location
- Repository: 0xK3vin_MegaMemory
- File: src/embeddings.ts
Signature
const MODEL_NAME = "Xenova/all-MiniLM-L6-v2";
const EMBEDDING_DIM = 384;
export async function initializeEmbeddings(): Promise<void>;
export async function embed(text: string): Promise<Buffer>;
// Throws if text is empty/whitespace or the output dim != 384.
export function embeddingText(name: string, kind: string, summary: string): string;
// Returns `${kind}: ${name} — ${summary}`
export function cosineSimilarity(a: Buffer, b: Buffer): number;
// Float32 views; throws on dimension mismatch; returns 0 for zero vectors.
export function findTopK(
queryEmbedding: Buffer,
candidates: Array<{
id: string;
name: string;
kind: string;
summary: string;
embedding: Buffer | null;
}>,
topK: number
): Array<{ id: string; similarity: number }>;
export { EMBEDDING_DIM };
Import
import { embed, embeddingText, findTopK, cosineSimilarity, initializeEmbeddings, EMBEDDING_DIM } from "./embeddings.js";
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| text | string | Yes (embed) | Non-empty text to embed |
| name, kind, summary | string | Yes (embeddingText) | Node fields composed into searchable text |
| a, b | Buffer | Yes (cosineSimilarity) | 384-float32 embedding Buffers |
| queryEmbedding | Buffer | Yes (findTopK) | Embedded query vector |
| candidates | Array | Yes (findTopK) | Nodes with non-null embedding; nulls are filtered out |
| topK | number | Yes (findTopK) | Maximum matches to return |
Outputs
| Name | Type | Description |
|---|---|---|
| embed() returns | Buffer | 1536-byte Buffer (384 float32 values), L2-normalized |
| embeddingText() returns | string | "kind: name — summary" |
| cosineSimilarity() returns | number | Cosine similarity in [-1, 1]; 0 for zero vectors |
| findTopK() returns | Array<{id, similarity}> | Descending by similarity, length ≤ topK |
| initializeEmbeddings() returns | void | Resolves once the pipeline is loaded |
Usage Examples
Embed and Search
import { embed, findTopK, embeddingText } from "./embeddings.js";
// 1. Embed a user query
const queryEmbedding = await embed("how does the merge algorithm handle edges?");
// 2. Get candidate nodes from the DB (each has a stored embedding)
const candidates = db.getAllActiveNodesWithEmbeddings();
// 3. Find the top 10 most similar concepts
const topMatches = findTopK(queryEmbedding, candidates, 10);
// => [{ id: "merge-engine", similarity: 0.78 }, ...]
Compose Concept Embedding Text
import { embeddingText, embed } from "./embeddings.js";
// Build the searchable text for a new concept, then embed it
const text = embeddingText("Merge Engine", "module", "Two-pass graph merge with conflict tracking");
const embedding = await embed(text);
// Store `embedding` in the nodes.embedding BLOB column
Preload for the Web Server
import { initializeEmbeddings } from "./embeddings.js";
try {
await initializeEmbeddings();
console.log("Embedding model ready.");
} catch (err) {
// Non-fatal: /api/search will retry on demand
console.warn("Embedding model failed to preload:", err);
}