diff --git a/go/internal/api/cosine.go b/go/internal/api/cosine.go new file mode 100644 index 0000000..c7877c1 --- /dev/null +++ b/go/internal/api/cosine.go @@ -0,0 +1,23 @@ +package api + +import "math" + +// cosineSimilarity 计算两个向量的余弦相似度。 +// 放在 api 包根目录,让 server(蒸馏写入路径)和 routes(commit 路径) +// 共享同一套近重复判据(>=0.98),避免两套逻辑各自漂移。 +func cosineSimilarity(a, b []float32) float64 { + var dot, normA, normB float64 + n := len(a) + if len(b) < n { + n = len(b) + } + for i := 0; i < n; i++ { + dot += float64(a[i]) * float64(b[i]) + normA += float64(a[i]) * float64(a[i]) + normB += float64(b[i]) * float64(b[i]) + } + if normA == 0 || normB == 0 { + return 0 + } + return dot / math.Sqrt(normA*normB) +} diff --git a/go/internal/api/server.go b/go/internal/api/server.go index bad246f..4f09c60 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -168,12 +168,24 @@ func NewServer() http.Handler { if !distill.IsQualityFact(fact) { continue // 碎片/噪声过滤 } - // 查重: 同 namespace 已存在完全相同 content → 跳过 + // 查重: 同 namespace 已存在**语义等价**记忆 → 跳过 + // 必须用 cosine 近重复判据(≥0.98),不能只比字符串相等—— + // 否则 "牧尘在招商局工作" 与 "牧尘在招商局工作。"(多一个句号) + // 会被判为两条不同事实双双入库,造成近重复堆积。 + var skip bool if qvec, eErr := emb.EncodeSingle(fact); eErr == nil { - if sim, _ := ldb.Search("memories", qvec, 1, input.Namespace); len(sim) > 0 && sim[0].Content == fact { - continue + if sim, _ := ldb.Search("memories", qvec, 5, input.Namespace); len(sim) > 0 { + for _, ex := range sim { + if ex.Content == fact || cosineSimilarity(qvec, ex.Vector) >= 0.98 { + skip = true + break + } + } } } + if skip { + continue + } mem := models.MemoryRecord{ ID: fmt.Sprintf("mem_%d", time.Now().UnixNano()), AgentID: input.AgentID,