/** * graph-memory — 查询向量 LRU 缓存 * * recall 的 query embedding 是每次召回的固定开销(低成本但高频): * 同会话内重复/回退的相同查询(before_agent_start ↔ assemble ↔ gm_search) * 直接复用向量,省一次 embedding API 调用。 * * key 在内部由 `prompt + "\0" + fingerprint` md5 哈希而成(与 syncEmbed * 的指纹拼接哈希模式一致):嵌入模型指纹变化天然 miss,防止旧模型向量被 * 误用。注意:db 模式向量不走缓存(节点文本入库前必算,且 MiniMax 的 * db/query 走不同模型,向量不可互换)。 */ import { createHash } from "crypto"; export class QueryVecCache { private map = new Map(); constructor(private readonly maxEntries = 64) {} get(prompt: string, fingerprint: string): number[] | null { const key = this.key(prompt, fingerprint); const hit = this.map.get(key); if (hit === undefined) return null; // LRU 触碰:删掉重插,移到最新端 this.map.delete(key); this.map.set(key, hit); return hit; } set(prompt: string, fingerprint: string, vector: number[]): void { const key = this.key(prompt, fingerprint); if (this.map.has(key)) this.map.delete(key); else if (this.map.size >= this.maxEntries) { // Map 迭代序 = 插入序,最旧的是第一个 key const oldest = this.map.keys().next().value; if (oldest !== undefined) this.map.delete(oldest); } this.map.set(key, vector); } clear(): void { this.map.clear(); } get size(): number { return this.map.size; } private key(prompt: string, fingerprint: string): string { return createHash("md5").update(`${prompt}\0${fingerprint}`).digest("hex"); } }