feat(memory): 记忆召回加 Relevance —— Generative Agents 打分补齐第三项 (P1)

审计三真桩之一。记忆召回此前打分只有 Recency+Importance,缺 Relevance(对当前
任务的语义相关性)——注释写"待接 Milvus",但召回时甚至不知道当前问什么。

关键发现:dispatcher 注入点 fetchMemory(ctx,uid,_) 手上已有当前任务文本(b.query),
只是被 `_` 丢弃了。所以不是"接 Milvus"那么重,把 query 一路传下去 + 缓存嵌入即可。

设计(偏离注释的"接 Milvus"——用户偏好量小,不值当上向量库):
- Profile 加 embedding 列(float32 小端打包存 bytea);Upsert 时对 value 向量化缓存
  (value 没变不重算,失败留空不阻断)。
- memory 包定义 Embedder 小接口,gateway 注入 rag.Engine(复用同一控制面下发的
  embedding 模型),不硬依赖 rag 内部;rag.Engine 加导出 Embed 方法。
- memory_get 工具加可选 query 入参;fetchMemory 停止丢弃 b.query 传下去。
- Get(ctx,uid,query):query 非空且 embedder 就绪 → embed(query) 对每条缓存向量
  内存算余弦 → 三项打分 0.25R+0.35I+0.4Rel;否则回落两项(升级前行为)。
- 优雅降级贯穿:无 query/无 embedder/query 嵌入失败/行无向量 → 静默回落,绝不报错。
  零 Milvus 依赖、零向量库同步问题、保住"没 embedding 也能跑"。

验证:单测(编解码往返/cosine 截0/三项模式相关性翻转顺序/降级返 nil)+ 端到端
(真 PG:写入即向量化、query=咖啡把低重要度的咖啡记忆翻到运动前面)。migration
加列已 live;embedding 复用 RAG 已验证基建。三模块 build/vet/test 全绿。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-07-18 12:47:55 +08:00
parent a742d118ad
commit 7ae7f7be67
8 changed files with 314 additions and 22 deletions
@@ -446,8 +446,9 @@ func evalLevel(r harness.Result) string {
}
// fetchMemory 经 MCP memory_get 工具召回用户常驻画像。
// query = 当前任务/问题文本:传给 memory_get 按语义相关性(Relevance)优先召回;空则退回最近性+重要度。
// 工具不可用/超时/无 user_id 时返回空串,降级为无记忆推理(不阻断主流程)。
func (o *Orchestrator) fetchMemory(ctx context.Context, userID, _ string) string {
func (o *Orchestrator) fetchMemory(ctx context.Context, userID, query string) string {
if o.tools == nil || userID == "" {
return ""
}
@@ -455,7 +456,7 @@ func (o *Orchestrator) fetchMemory(ctx context.Context, userID, _ string) string
defer cancel()
res, err := o.tools.CallTool(cctx, contract.ToolSubjectGo("memory_get"), &contract.ToolCall{
Tool: "memory_get",
Args: map[string]any{"user_id": userID},
Args: map[string]any{"user_id": userID, "query": query},
})
if err != nil {
log.Printf("[eino] memory_get unavailable for %s, degrade: %v", userID, err)
+11 -2
View File
@@ -60,6 +60,11 @@ type toolDef struct {
func NewGateway(b *sharedbus.Bus, m *memory.Store, h *history.Store, r *rag.Engine, pgDSN string) *Gateway {
g := &Gateway{bus: b, memory: m, history: h, rag: r, pgDSN: pgDSN}
// 记忆 Relevance 复用 RAG 的 embedding(同一控制面下发的模型):召回时对 query 算语义相关性。
// rag.Engine 满足 memory.Embedder;未配置 embedding 时 memory 优雅回落两项打分。
if m != nil && r != nil {
m.SetEmbedder(r)
}
g.tools = g.buildRegistry()
return g
}
@@ -98,7 +103,10 @@ func (g *Gateway) buildRegistry() map[string]toolDef {
},
"memory_get": {
cn: "记忆召回", desc: "召回当前用户的长期画像与偏好(称呼/职业/回答偏好等)。需要个性化、了解“我是谁”时调用。",
agent: true, agentName: "recall_user_memory", inject: []string{"user_id"}, handler: g.memoryGet,
agent: true, agentName: "recall_user_memory",
// query 可选:给了则按对当前任务的语义相关性优先召回(Relevance),不给则按最近性+重要度。
params: []paramSpec{{Name: "query", Type: "string", Desc: "当前任务/问题文本,用于按相关性优先召回(可选)", Required: false}},
inject: []string{"user_id"}, handler: g.memoryGet,
},
"memory_upsert": {
cn: "记忆写入", desc: "把关于用户的一条事实/偏好长期记住(如称呼、职业、回答偏好)。",
@@ -223,7 +231,8 @@ func (g *Gateway) listTools() *contract.ToolResult {
// memoryGet 召回某用户的常驻画像(已渲染为可注入 prompt 的多行文本)。
func (g *Gateway) memoryGet(ctx context.Context, call *contract.ToolCall) *contract.ToolResult {
uid, _ := call.Args["user_id"].(string)
profile, err := g.memory.Get(ctx, uid)
query, _ := call.Args["query"].(string) // 可选:按对当前任务的语义相关性优先召回
profile, err := g.memory.Get(ctx, uid, query)
if err != nil {
return &contract.ToolResult{OK: false, Error: "memory_get: " + err.Error()}
}
+3 -3
View File
@@ -12,12 +12,12 @@ func TestRankProfiles(t *testing.T) {
{Key: "低重要久远", Value: "b", Importance: 2, LastSeenAt: now.AddDate(0, 0, -60)},
{Key: "中等", Value: "c", Importance: 5, LastSeenAt: now.AddDate(0, 0, -10)},
}
ranked := rankProfiles(rows, now, 0)
ranked := rankProfiles(rows, now, 0, nil)
if ranked[0].Key != "高重要近期" || ranked[2].Key != "低重要久远" {
t.Errorf("应按 Score 降序:高重要近期 > 中等 > 低重要久远,得 %s/%s/%s", ranked[0].Key, ranked[1].Key, ranked[2].Key)
}
// 截断 top-N
if got := rankProfiles(rows, now, 2); len(got) != 2 || got[0].Key != "高重要近期" {
if got := rankProfiles(rows, now, 2, nil); len(got) != 2 || got[0].Key != "高重要近期" {
t.Errorf("top-2 截断错: %d 条 首=%s", len(got), got[0].Key)
}
// 原切片不被改动(rankProfiles 应 copy
@@ -42,7 +42,7 @@ func TestProfileScore_DefaultImportance(t *testing.T) {
now := time.Now()
// importance=0(旧/未评分)应按兜底 5 计,而不是 0(否则被不公平遗忘)。
p := Profile{Importance: 0, LastSeenAt: now}
got := profileScore(p, now)
got := profileScore(p, now, nil)
want := wRecency*1.0 + wImportance*(defaultImportance/10)
if got != want {
t.Errorf("未评分行应用兜底 importance: got %v want %v", got, want)
@@ -0,0 +1,89 @@
package memory
import (
"context"
"hash/fnv"
"math"
"os"
"strings"
"testing"
)
// detEmbedder:确定性伪嵌入(同文本同向量;含指定关键词的文本在对应维度更高)。
// 只为端到端验证「本包代码路径」——Upsert 存向量 → Get 算余弦重排 —— 对真 PG,
// 不打真 embedding 网络(那是 rag 包已验证的复用基建)。
type detEmbedder struct{}
func (detEmbedder) Embed(_ context.Context, texts []string) ([][]float32, error) {
const dim = 16
kw := []string{"咖啡", "coffee", "运动", "健身", "音乐"}
out := make([][]float32, len(texts))
for i, t := range texts {
v := make([]float32, dim)
for _, w := range kw {
if strings.Contains(t, w) {
h := fnv.New32a()
_, _ = h.Write([]byte(w))
v[h.Sum32()%dim] += 1
}
}
var n float64
for _, x := range v {
n += float64(x) * float64(x)
}
if n > 0 {
for j := range v {
v[j] = float32(float64(v[j]) / math.Sqrt(n))
}
}
out[i] = v
}
return out, nil
}
// 端到端(真 PG):写两条记忆(咖啡 importance=3 / 运动 importance=8)→
// 无 query 时运动(重要度高)在前;query="咖啡"时咖啡(语义相关)翻到前面。
func TestRelevance_EndToEnd(t *testing.T) {
dsn := os.Getenv("MEMORY_TEST_DSN")
if dsn == "" {
t.Skip("设 MEMORY_TEST_DSN 启用 Postgres 端到端测试")
}
s := Open(dsn)
if s.db == nil {
t.Fatal("Store 不应降级")
}
s.SetEmbedder(detEmbedder{})
ctx := context.Background()
uid := "memtest-relevance-e2e"
defer func() {
_ = s.Delete(ctx, uid, "饮品偏好")
_ = s.Delete(ctx, uid, "运动习惯")
}()
if err := s.Upsert(ctx, uid, "饮品偏好", "喜欢手冲咖啡 coffee 不加糖", 3); err != nil {
t.Fatalf("upsert 咖啡: %v", err)
}
if err := s.Upsert(ctx, uid, "运动习惯", "每天健身运动一小时", 8); err != nil {
t.Fatalf("upsert 运动: %v", err)
}
// 确认写入即向量化:embedding 列非空。
var rows []Profile
s.db.WithContext(ctx).Where("user_id = ?", uid).Find(&rows)
for _, r := range rows {
if len(r.Embedding) == 0 {
t.Errorf("%s 应已向量化(embedding 非空)", r.Key)
}
}
// 无 query:两项打分,运动(importance 8)在前。
noQ, _ := s.Get(ctx, uid, "")
if !strings.HasPrefix(noQ, "- 运动习惯") {
t.Errorf("无 query 应重要度优先(运动在前),得:\n%s", noQ)
}
// query 咖啡:三项打分,咖啡语义相关翻到前面(尽管重要度更低)。
withQ, _ := s.Get(ctx, uid, "推荐一款好喝的咖啡 coffee")
if !strings.HasPrefix(withQ, "- 饮品偏好") {
t.Errorf("query=咖啡 应相关性优先(咖啡在前),得:\n%s", withQ)
}
}
@@ -0,0 +1,84 @@
package memory
import (
"context"
"math"
"testing"
"time"
)
// 向量编解码往返:float32 打包进 bytea 再取回不失真。
func TestVecRoundTrip(t *testing.T) {
v := []float32{0.1, -0.5, 1.0, 0, 0.333}
got := decodeVec(encodeVec(v))
if len(got) != len(v) {
t.Fatalf("长度不符: %d vs %d", len(got), len(v))
}
for i := range v {
if got[i] != v[i] {
t.Errorf("第%d个失真: %v vs %v", i, got[i], v[i])
}
}
// 脏数据(长度非 4 倍数)返回 nil,不 panic。
if decodeVec([]byte{1, 2, 3}) != nil {
t.Error("非法字节应返回 nil")
}
if decodeVec(nil) != nil {
t.Error("空返回 nil")
}
}
// cosine01:同向=1,正交=0.5→截到实际(正交余弦0→0),反向截到 0。
func TestCosine01(t *testing.T) {
a := []float32{1, 0, 0}
if c := cosine01(a, a); math.Abs(c-1) > 1e-6 {
t.Errorf("同向应为 1,得 %v", c)
}
if c := cosine01(a, []float32{0, 1, 0}); c != 0 {
t.Errorf("正交余弦 0,得 %v", c)
}
if c := cosine01(a, []float32{-1, 0, 0}); c != 0 {
t.Errorf("反向应截到 0(不奖励相反语义),得 %v", c)
}
if c := cosine01(a, []float32{0, 0, 0}); c != 0 {
t.Errorf("零向量应为 0,得 %v", c)
}
}
// 三项打分模式(rel 非 nil):相关性高的排到前面,即使重要度/最近性略低。
func TestRankProfiles_RelevanceMode(t *testing.T) {
now := time.Now()
rows := []Profile{
{BaseModel: BaseModel{ID: "a"}, Key: "无关但重要", Importance: 10, LastSeenAt: now},
{BaseModel: BaseModel{ID: "b"}, Key: "高度相关", Importance: 3, LastSeenAt: now},
}
rel := map[string]float64{"a": 0.05, "b": 0.95} // b 语义强相关
// 两项模式(rel=nil):a(重要度10)应在前。
if got := rankProfiles(rows, now, 0, nil); got[0].ID != "a" {
t.Errorf("两项模式重要度高者应在前,得 %s", got[0].ID)
}
// 三项模式:b 相关性 0.95 主导,应翻到前面。
if got := rankProfiles(rows, now, 0, rel); got[0].ID != "b" {
t.Errorf("三项模式相关性高者应在前,得 %s", got[0].ID)
}
}
// relevance 优雅降级:无 embedder / query 空 → 返回 nil(不报错、不影响召回)。
func TestRelevance_GracefulFallback(t *testing.T) {
s := &Store{} // 无 embedder
if s.relevance(context.Background(), []Profile{{Key: "k"}}, "问题") != nil {
t.Error("无 embedder 应返回 nil")
}
s.emb = stubEmbedder{}
if s.relevance(context.Background(), []Profile{{Key: "k"}}, " ") != nil {
t.Error("query 空白应返回 nil(不白算嵌入)")
}
}
// stubEmbedder 返回固定维度向量,供降级测试(不打真网络)。
type stubEmbedder struct{}
func (stubEmbedder) Embed(_ context.Context, _ []string) ([][]float32, error) {
return [][]float32{{1, 0}}, nil
}
+117 -14
View File
@@ -4,6 +4,7 @@ package memory
import (
"context"
"encoding/binary"
"fmt"
"log"
"math"
@@ -54,13 +55,27 @@ type Profile struct {
Value string `gorm:"type:text"`
Importance float64 `gorm:"column:importance"` // 1~10consolidate 时 LLM 打分(poignancy)→ 读路径权重
LastSeenAt time.Time `gorm:"column:last_seen_at"` // 最近被印证时间 → Recency 衰减依据
Embedding []byte `gorm:"column:embedding"` // value 的嵌入向量(float32 小端打包);召回时对 query 算余弦 → Relevance
}
// TableName 固定表名,遵守 sundynix_ 前缀约定。
func (Profile) TableName() string { return "sundynix_user_profile" }
// Embedder 是把文本转向量的最小接口(memory 包不硬依赖 rag 内部;由 gateway 注入 rag.Engine)。
// 返回每条文本一个向量;未配置/失败时 memory 优雅降级为 Recency+Importance 两项打分。
type Embedder interface {
Embed(ctx context.Context, texts []string) ([][]float32, error)
}
// Store 封装画像读写。db 为 nil 表示降级(无 Postgres 时记忆功能空转,不阻断工具服务)。
type Store struct{ db *gorm.DB }
// emb 为 nil 或未配置时,Relevance 打分静默跳过(回落两项打分,行为与升级前一致)。
type Store struct {
db *gorm.DB
emb Embedder
}
// SetEmbedder 注入嵌入能力(gateway 装配时传 rag.Engine)。nil 安全。
func (s *Store) SetEmbedder(e Embedder) { s.emb = e }
// Open 连接 Postgres 并自动迁移 sundynix_user_profile。连接失败不 fatal:返回降级实例。
func Open(dsn string) *Store {
@@ -123,18 +138,26 @@ func migrateLegacyProfile(db *gorm.DB) {
log.Printf("[memory] 已回灌 %d 条偏好(新雪花 id)", len(saved))
}
// 读路径打分参数(Generative Agents 公式Recency + Importance 两项;Relevance 待接 Milvus)。
// 读路径打分参数(Generative Agents 公式Recency + Importance + Relevance)。
const (
memTopN = 30 // 注入上限(截断,控 context)
wRecency = 0.4 // 最近性权重
wImportance = 0.6 // 重要度权重
recencyDecayPerDay = 0.98 // 每天衰减因子(指数)
defaultImportance = 5.0 // 旧/未评分行的兜底重要度(避免被不公平遗忘)
// 无 query / 无 embedder(回落两项)—— 保持升级前的行为与权重。
wRecency = 0.4
wImportance = 0.6
// relevance 模式(召回带 query 且 embedder 就绪):三项加权,语义相关性主导但不淹没另两项。
wRecencyR = 0.25
wImportanceR = 0.35
wRelevance = 0.4
)
// Get 返回某用户画像,渲染为可注入 prompt 的多行文本。
// 按 Score = wRecency·Recency + wImportance·Importance 降序,截断 top-N(控 context + 自然遗忘)。
func (s *Store) Get(ctx context.Context, userID string) (string, error) {
// query 非空且 embedder 就绪时,融入 Relevance(对当前任务的语义相关性)三项打分;
// 否则回落 Recency+Importance 两项(升级前行为)。截断 top-N(控 context + 自然遗忘 + 相关性优先)。
func (s *Store) Get(ctx context.Context, userID, query string) (string, error) {
if s.db == nil || userID == "" {
return "", nil
}
@@ -142,7 +165,8 @@ func (s *Store) Get(ctx context.Context, userID string) (string, error) {
if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Find(&rows).Error; err != nil {
return "", err
}
ranked := rankProfiles(rows, time.Now(), memTopN)
rel := s.relevance(ctx, rows, query)
ranked := rankProfiles(rows, time.Now(), memTopN, rel)
var b strings.Builder
for _, r := range ranked {
fmt.Fprintf(&b, "- %s%s\n", r.Key, r.Value)
@@ -150,6 +174,28 @@ func (s *Store) Get(ctx context.Context, userID string) (string, error) {
return strings.TrimRight(b.String(), "\n"), nil
}
// relevance 计算每条偏好对 query 的语义相关性(profile.ID → 余弦[0,1])。
// 无 embedder / query 空 / query 嵌入失败 → 返回 nil(打分回落两项,绝不因此报错)。
// 行无缓存向量(存量未回填 / 嵌入曾失败)→ 该行不进 map,等同 relevance 0(不加分不减分)。
func (s *Store) relevance(ctx context.Context, rows []Profile, query string) map[string]float64 {
if s.emb == nil || strings.TrimSpace(query) == "" {
return nil
}
qv, err := s.emb.Embed(ctx, []string{query})
if err != nil || len(qv) == 0 || len(qv[0]) == 0 {
return nil // 嵌入不可用:优雅回落,不影响召回
}
q := qv[0]
rel := make(map[string]float64, len(rows))
for _, r := range rows {
v := decodeVec(r.Embedding)
if len(v) == len(q) && len(v) > 0 {
rel[r.ID] = cosine01(q, v)
}
}
return rel
}
// List 返回某用户全部 active 偏好(结构化,供管理面板查看/编辑),按 Score 降序、不截断。
func (s *Store) List(ctx context.Context, userID string) ([]Profile, error) {
if s.db == nil || userID == "" {
@@ -159,15 +205,16 @@ func (s *Store) List(ctx context.Context, userID string) ([]Profile, error) {
if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Find(&rows).Error; err != nil {
return nil, err
}
return rankProfiles(rows, time.Now(), 0), nil
return rankProfiles(rows, time.Now(), 0, nil), nil // 管理面板:无 query,两项打分
}
// rankProfiles 纯函数:按 Score 降序排序(同分 key 升序稳定),截断 top-NtopN<=0 不截断)。
func rankProfiles(rows []Profile, now time.Time, topN int) []Profile {
// rel 非 nil = relevance 模式(三项打分,缺失 ID 视为 relevance 0);nil = 两项打分(升级前行为)。
func rankProfiles(rows []Profile, now time.Time, topN int, rel map[string]float64) []Profile {
out := make([]Profile, len(rows))
copy(out, rows)
sort.SliceStable(out, func(i, j int) bool {
si, sj := profileScore(out[i], now), profileScore(out[j], now)
si, sj := profileScore(out[i], now, rel), profileScore(out[j], now, rel)
if si != sj {
return si > sj
}
@@ -179,13 +226,60 @@ func rankProfiles(rows []Profile, now time.Time, topN int) []Profile {
return out
}
// profileScore 计算一条偏好的 Recency+Importance 综合分(各归一到 [0,1]
func profileScore(p Profile, now time.Time) float64 {
// profileScore 综合分(各项归一到 [0,1])。rel==nil → 两项(Recency+Importance);否则三项加入 Relevance
func profileScore(p Profile, now time.Time, rel map[string]float64) float64 {
imp := p.Importance
if imp <= 0 {
imp = defaultImportance
}
return wRecency*recencyScore(now, p.LastSeenAt) + wImportance*(imp/10)
recency := recencyScore(now, p.LastSeenAt)
impN := imp / 10
if rel == nil {
return wRecency*recency + wImportance*impN
}
return wRecencyR*recency + wImportanceR*impN + wRelevance*rel[p.ID] // 缺失 ID → 0
}
// ---- 向量编解码 + 余弦(float32 小端打包存 PG bytea;召回时内存算相似度)----
func encodeVec(v []float32) []byte {
b := make([]byte, 4*len(v))
for i, f := range v {
binary.LittleEndian.PutUint32(b[i*4:], math.Float32bits(f))
}
return b
}
func decodeVec(b []byte) []float32 {
if len(b) == 0 || len(b)%4 != 0 {
return nil
}
v := make([]float32, len(b)/4)
for i := range v {
v[i] = math.Float32frombits(binary.LittleEndian.Uint32(b[i*4:]))
}
return v
}
// cosine01 余弦相似度截到 [0,1](负相关记 0,不奖励相反语义)。
func cosine01(a, b []float32) float64 {
var dot, na, nb float64
for i := range a {
dot += float64(a[i]) * float64(b[i])
na += float64(a[i]) * float64(a[i])
nb += float64(b[i]) * float64(b[i])
}
if na == 0 || nb == 0 {
return 0
}
c := dot / (math.Sqrt(na) * math.Sqrt(nb))
if c < 0 {
return 0
}
if c > 1 {
return 1
}
return c
}
// recencyScore 指数衰减的最近性分:last_seen 越久越低;未记时间视为新鲜(1)。
@@ -211,10 +305,19 @@ func (s *Store) Upsert(ctx context.Context, userID, key, value string, importanc
if importance > 0 {
updates["importance"] = importance
}
p := &Profile{UserID: userID, Key: key, Value: value, Importance: importance, LastSeenAt: now}
// 写入即向量化 value(供召回算 Relevance)。embedder 未配置/失败 → 留空向量,召回自动回落,不阻断写入。
if s.emb != nil && strings.TrimSpace(value) != "" {
if vecs, err := s.emb.Embed(ctx, []string{value}); err == nil && len(vecs) > 0 && len(vecs[0]) > 0 {
enc := encodeVec(vecs[0])
p.Embedding = enc
updates["embedding"] = enc
}
}
return s.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "user_id"}, {Name: "key"}},
DoUpdates: clause.Assignments(updates),
}).Create(&Profile{UserID: userID, Key: key, Value: value, Importance: importance, LastSeenAt: now}).Error
}).Create(p).Error
}
// Touch 仅刷新某条偏好的 last_seen(NOOP 印证:被再次提及但内容不变,强化 Recency)。
@@ -99,7 +99,7 @@ func TestProfileStore_Integration(t *testing.T) {
// Get 渲染多行(按 key 排序),软删的不出现。
_ = s.Upsert(ctx, "u1", "爱好", "围棋", 6)
got, _ := s.Get(ctx, "u1")
got, _ := s.Get(ctx, "u1", "")
if got == "" || got != "- 城市:上海\n- 爱好:围棋" {
t.Errorf("Get 渲染不符: %q", got)
}
+6
View File
@@ -84,6 +84,12 @@ func (e *Engine) embed() *embedClient {
return e.emb
}
// Embed 导出当前 embedding 能力供 memory 包复用(满足 memory.Embedder)。
// 未配置时返回错误,调用方(记忆 Relevance)据此优雅回落。热更新下发的模型即时生效。
func (e *Engine) Embed(ctx context.Context, texts []string) ([][]float32, error) {
return e.embed().Embed(ctx, texts)
}
func (e *Engine) chatClient() *chatClient {
e.mu.RLock()
defer e.mu.RUnlock()