memoryweave/docs/h1-h3-h4-h5-plan.md

3.2 KiB
Raw Blame History

H1 + H3 + H4 + H5: Go 后端改进

修改文件

1. /tmp/memoryweave/go/internal/storage/recall.go (H1: BM25)

Recall 方法中Step 4 (MMR) 之前,对 candidates 计算 keyword score

// Step 3.5: BM25 keyword scoring — 补充向量搜索
if len(candidates) > 0 {
    for i := range candidates {
        kwScore := computeBM25Score(query, candidates[i].Content)
        // 融合分数0.7 * 向量语义分 + 0.3 * 关键词分
        candidates[i].QualityScore = candidates[i].QualityScore * 0.7 + kwScore * 0.3
    }
}

新增函数:

// computeBM25Score 基于词频的关键词匹配分数
func computeBM25Score(query, doc string) float64 {
    queryTerms := strings.Fields(strings.ToLower(query))
    docLower := strings.ToLower(doc)
    hitCount := 0
    for _, term := range queryTerms {
        if len(term) < 2 { continue }
        count := strings.Count(docLower, term)
        if count > 0 { hitCount += count }
    }
    if hitCount == 0 { return 0 }
    // 归一化到 [0, 1]
    score := float64(hitCount) / float64(len(queryTerms))
    if score > 1.0 { score = 1.0 }
    return score
}

2. /tmp/memoryweave/go/internal/api/routes/core.go (H3 + H4 + H5)

H3: 自动信任评分

Recall handler 末尾respond 之前),异步更新信任评分:

// H3: 异步更新信任评分
go func() {
    if err := a.GraphStore.UpdateEdgeTrustScores(); err != nil {
        log.Printf("[zhiyid] update trust scores: %v", err)
    }
}()

H4: 默认 diversity

修改 Recall handler 中的 diversity 默认值:

// 在解析请求体后
if req.Diversity <= 0 {
    req.Diversity = 0.3  // 默认0.3,在相关性和多样性间平衡
}

H5: 混合搜索模式

在请求体中新增 mode 字段:

type RecallRequest struct {
    Query     string  `json:"query"`
    Limit     int     `json:"limit"`
    TopK      int     `json:"top_k"`
    Namespace string  `json:"namespace"`
    AgentID   string  `json:"agent_id"`
    Diversity float64 `json:"diversity"`
    Mode      string  `json:"mode"`  // "hybrid"(default), "semantic", "keyword"
}

根据 mode 做不同输入:

  • "semantic" 或 "" → 只走向量搜索(当前行为)
  • "keyword" → 走 graph.db FallbackTextSearch关键词搜索+ BM25 scoring
  • "hybrid"(默认)→ 向量 + BM25 combinedH1 实现)

3. /tmp/memoryweave/go/internal/governance/graph_sqlite.go (H5: keyword 搜索增强)

增强 FallbackTextSearch

  • 当前只搜 node.name + relation
  • 新增搜索 edges 的 properties JSON 中的 content 字段
  • 按 keyword match count 排序

验证

# Hybrid mode (默认)
curl -s -X POST -H "X-API-Key: zhiyi-dev-key-2026" -d '{"query":"memory sidecar","top_k":3}' http://localhost:7821/api/v1/recall

# Keyword mode
curl -s -X POST -H "X-API-Key: zhiyi-dev-key-2026" -d '{"query":"memory sidecar","top_k":3,"mode":"keyword"}' http://localhost:7821/api/v1/recall

# Semantic mode
curl -s -X POST -H "X-API-Key: zhiyi-dev-key-2026" -d '{"query":"memory sidecar","top_k":3,"mode":"semantic"}' http://localhost:7821/api/v1/recall

# Diversity (默认0.3)
curl -s -X POST -H "X-API-Key: zhiyi-dev-key-2026" -d '{"query":"memory","top_k":5}' http://localhost:7821/api/v1/recall