Files
memoryweave/go/internal/api/routes/entity_index.go
T
xiaoyi 46eaf1a35d feat(graph/notes): 整句→实体兜底拆解(EntityIndex)
问题:调用方(hermes 织忆插件)把整句用户提问直接当 entity 传给
/api/v1/graph/notes,NormalizeEntity 后整句匹配不到图谱节点 → 0 篇笔记,
Obsidian 笔记层在真实对话里几乎不生效。

改动(纯服务端,调用方无需改,也就无需重启 hermes 网关):
- 新增 routes.EntityIndex:节点名词表(PageRank,TTL 10min,后台 45s 预热)
  + 最长/权重匹配把整句拆成候选实体;候选需过 相对权重比(0.15) 与 图谱度数(>=3)
  两道过滤,压掉通用词/自动切词噪声节点。
- /api/v1/graph/notes:entity 直查 0 篇笔记时自动兜底拆实体重查;
  新增 query 参数;响应新增 mode(direct|nl_extract|none) 与 entities_used。
  兜底路径 graph_paths 截断(单实体 20 条、合计 50 条)、参与匹配实体上限 8。
- 覆盖测试 10 个:真实句子拆解/大小写/包含冗余/权重比/度数过滤/TTL缓存与失败退避/nil 安全。

实测(生产 7821):单词实体 entity=织忆 仍 mode=direct 3 篇(回归不变);
整句 "织忆召回会不会给出obsidian实体所在的笔记位置呢" → mode=nl_extract
used=[Obsidian 织忆] 3 篇真路径 0.29s;无意义句 "完全不相干的一句话天气不错"
→ mode=none 0 篇(噪声已过滤)。
2026-09-27 02:19:13 +08:00

237 lines
6.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package routes
import (
"sort"
"strings"
"sync"
"time"
"unicode"
)
// NodeVocabularyFunc 返回「节点名 → PageRank 权重」快照(通常是 graphStore.PageRank)。
type NodeVocabularyFunc func() map[string]float64
// entityCandidate 是查询串里命中的一个图谱节点。
type entityCandidate struct {
Name string // 原始拼写(用于 Navigate / 笔记匹配)
Weight float64
Runes int
Pos int
}
// EntityIndex 用图谱节点名词表把「整句自然语言」拆成候选实体(本地最长/权重匹配)。
//
// 背景:调用方(hermes 织忆插件)把整句用户提问直接当 entity 传给
// /api/v1/graph/notes,NormalizeEntity 后整句匹配不到任何节点 → 0 篇笔记。
// 服务端在这里兜底拆实体,调用方无需改动(也就无需重启 hermes 网关)。
type EntityIndex struct {
load NodeVocabularyFunc
ttl time.Duration
// MinNameRunes / MaxNameRunes 限定候选实体长度(rune 数)。
MinNameRunes int
MaxNameRunes int
// MinWeightRatio 丢掉相对 top 候选过弱的候选(压通用词噪声,如「位置」)。
MinWeightRatio float64
// Degree 返回实体在图谱里的度数(edges 计数);nil 表示不做度数过滤。
Degree func(name string) int
// MinDegree 度数低于此值的候选判为噪声节点(如自动切词产物「一句话」)。
MinDegree int
mu sync.RWMutex
names map[string]entityCandidate
loadedAt time.Time
lastTryAt time.Time
retryGap time.Duration
now func() time.Time
}
// NewEntityIndex 创建实体索引;load 为 nil 时 Extract 恒返回空。
func NewEntityIndex(load NodeVocabularyFunc) *EntityIndex {
return &EntityIndex{
load: load,
ttl: 10 * time.Minute,
MinNameRunes: 2,
MaxNameRunes: 8,
MinWeightRatio: 0.15,
MinDegree: 3,
retryGap: 60 * time.Second,
now: time.Now,
}
}
// Warm 在 delay 之后后台加载一次词表,避免首次兜底请求被 2.5s 的 PageRank 阻塞。
func (e *EntityIndex) Warm(delay time.Duration) {
if e == nil || e.load == nil {
return
}
go func() {
if delay > 0 {
time.Sleep(delay)
}
e.vocabulary()
}()
}
// vocabulary 返回当前词表(TTL 内复用;加载失败按 retryGap 退避,永不 panic)。
func (e *EntityIndex) vocabulary() map[string]entityCandidate {
if e == nil || e.load == nil {
return nil
}
now := e.now()
e.mu.RLock()
if len(e.names) > 0 && now.Sub(e.loadedAt) < e.ttl {
names := e.names
e.mu.RUnlock()
return names
}
e.mu.RUnlock()
e.mu.Lock()
defer e.mu.Unlock()
now = e.now()
// 双检:可能在等锁期间已被别的请求加载好
if len(e.names) > 0 && now.Sub(e.loadedAt) < e.ttl {
return e.names
}
if !e.lastTryAt.IsZero() && now.Sub(e.lastTryAt) < e.retryGap {
return e.names // 退避期内:用旧词表(可能为空)但不重复打 DB
}
e.lastTryAt = now
raw := e.load()
if len(raw) == 0 {
return e.names
}
names := make(map[string]entityCandidate, len(raw))
for name, w := range raw {
name = strings.TrimSpace(name)
if name == "" {
continue
}
key := strings.ToLower(name)
if prev, ok := names[key]; !ok || w > prev.Weight {
names[key] = entityCandidate{Name: name, Weight: w, Runes: len([]rune(name))}
}
}
e.names = names
e.loadedAt = now
return names
}
// Extract 把整句拆成候选实体:取所有「是查询串子串」的节点名,按权重排序去重。
// 返回按权重降序的实体名,最多 maxEntities 个;无命中返回 nil。
func (e *EntityIndex) Extract(query string, maxEntities int) []string {
if e == nil || maxEntities <= 0 {
return nil
}
query = strings.TrimSpace(query)
if query == "" {
return nil
}
names := e.vocabulary()
if len(names) == 0 {
return nil
}
runes := []rune(strings.ToLower(query))
total := len(runes)
minLen, maxLen := e.MinNameRunes, e.MaxNameRunes
if minLen < 1 {
minLen = 1
}
if maxLen < minLen {
maxLen = minLen
}
// 收集所有命中:候选名必须是查询串的(区分大小写已归一为小写)子串
found := make(map[string]entityCandidate)
for i := 0; i < total; i++ {
limit := maxLen
if total-i < limit {
limit = total - i
}
for n := limit; n >= minLen; n-- {
key := string(runes[i : i+n])
c, ok := names[key]
if !ok || !hasLetter(c.Name) {
continue
}
if prev, dup := found[key]; !dup || c.Weight > prev.Weight {
c.Pos = i
found[key] = c
}
break // 同一位置只取最长命中,短前缀交给其他起点
}
}
if len(found) == 0 {
return nil
}
cands := make([]entityCandidate, 0, len(found))
for _, c := range found {
cands = append(cands, c)
}
sort.Slice(cands, func(i, j int) bool {
if cands[i].Weight != cands[j].Weight {
return cands[i].Weight > cands[j].Weight
}
if cands[i].Runes != cands[j].Runes {
return cands[i].Runes > cands[j].Runes
}
return cands[i].Pos < cands[j].Pos
})
top := cands[0].Weight
ratio := e.MinWeightRatio
if ratio < 0 {
ratio = 0
}
out := make([]string, 0, maxEntities)
checks := 0
maxChecks := maxEntities * 2
for _, c := range cands {
if top > 0 && c.Weight < top*ratio {
break // 已按权重降序,后面更弱
}
redundant := false
lc := strings.ToLower(c.Name)
for _, sel := range out {
if strings.ToLower(sel) == lc {
redundant = true
break
}
// 短名被已选长名包含(且不更强)→ 冗余,如「织忆」vs「织忆系统」
if strings.Contains(strings.ToLower(sel), lc) {
redundant = true
break
}
}
if redundant {
continue
}
if e.Degree != nil && checks < maxChecks {
checks++
if e.Degree(c.Name) < e.MinDegree {
continue // 噪声节点(自动切词产物等),不参与笔记匹配
}
}
out = append(out, c.Name)
if len(out) >= maxEntities {
break
}
}
if len(out) == 0 {
return nil
}
return out
}
// hasLetter 过滤纯符号/数字的节点名(图谱里有少量噪声节点)。
func hasLetter(s string) bool {
for _, r := range s {
if unicode.IsLetter(r) {
return true
}
}
return false
}