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 篇(噪声已过滤)。
This commit is contained in:
xiaoyi
2026-09-27 02:19:13 +08:00
parent 5944df41b5
commit 46eaf1a35d
3 changed files with 470 additions and 4 deletions
+236
View File
@@ -0,0 +1,236 @@
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
}
+166
View File
@@ -0,0 +1,166 @@
package routes
import (
"reflect"
"testing"
"time"
)
func fakeVocab(m map[string]float64) (NodeVocabularyFunc, *int) {
calls := 0
return func() map[string]float64 {
calls++
return m
}, &calls
}
// 真实场景:hermes 织忆插件把整句提问当 entity 传过来,服务端要能拆出实体。
func TestExtractNLSentence(t *testing.T) {
load, _ := fakeVocab(map[string]float64{
"织忆": 3.386e-06,
"位置": 1.510e-06,
"小怡": 3.134e-06,
"牧尘": 2.491e-06,
})
idx := NewEntityIndex(load)
got := idx.Extract("现在织忆recall带obsidian实体位置么", 2)
want := []string{"织忆", "位置"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v want %v", got, want)
}
// 只取 1 个时必须是权重最高的那个
if got := idx.Extract("现在织忆recall带obsidian实体位置么", 1); !reflect.DeepEqual(got, []string{"织忆"}) {
t.Fatalf("top1 got %v", got)
}
}
func TestExtractASCIIKeepsOriginalSpelling(t *testing.T) {
load, _ := fakeVocab(map[string]float64{
"Obsidian": 2.0e-06,
"CLI": 1.0e-06,
})
idx := NewEntityIndex(load)
got := idx.Extract("obsidian 和 cli 怎么配", 5)
want := []string{"Obsidian", "CLI"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v want %v", got, want)
}
}
func TestExtractDropsContainedShorterName(t *testing.T) {
load, _ := fakeVocab(map[string]float64{
"织忆系统": 3.0e-06,
"织忆": 2.0e-06,
})
idx := NewEntityIndex(load)
if got := idx.Extract("织忆系统的笔记", 5); !reflect.DeepEqual(got, []string{"织忆系统"}) {
t.Fatalf("got %v", got)
}
}
func TestExtractWeightRatioFilter(t *testing.T) {
load, _ := fakeVocab(map[string]float64{"织忆": 3.0e-06, "位置": 1.0e-06})
idx := NewEntityIndex(load)
if got := idx.Extract("织忆和位置", 5); len(got) != 2 {
t.Fatalf("默认阈值应保留两个,got %v", got)
}
idx.MinWeightRatio = 0.5
if got := idx.Extract("织忆和位置", 5); !reflect.DeepEqual(got, []string{"织忆"}) {
t.Fatalf("阈值 0.5 应只剩织忆,got %v", got)
}
}
func TestExtractSkipsTooShortAndNonLetterNames(t *testing.T) {
load, _ := fakeVocab(map[string]float64{"忆": 5.0e-06, "12": 4.0e-06})
idx := NewEntityIndex(load)
if got := idx.Extract("织忆12", 5); got != nil {
t.Fatalf("expected nil, got %v", got)
}
}
func TestExtractNoHitAndEmptyQuery(t *testing.T) {
load, _ := fakeVocab(map[string]float64{"织忆": 3.0e-06})
idx := NewEntityIndex(load)
if got := idx.Extract("今天天气不错", 3); got != nil {
t.Fatalf("expected nil, got %v", got)
}
if got := idx.Extract(" ", 3); got != nil {
t.Fatalf("expected nil, got %v", got)
}
if got := idx.Extract("织忆", 0); got != nil {
t.Fatalf("maxEntities=0 应返回 nil, got %v", got)
}
}
func TestExtractCachesVocabularyAndBacksOffOnFailure(t *testing.T) {
load, calls := fakeVocab(map[string]float64{"织忆": 3.0e-06})
idx := NewEntityIndex(load)
now := time.Unix(1700000000, 0)
idx.now = func() time.Time { return now }
idx.Extract("织忆", 1)
idx.Extract("织忆", 1)
if *calls != 1 {
t.Fatalf("TTL 内应只加载一次,calls=%d", *calls)
}
now = now.Add(11 * time.Minute)
idx.Extract("织忆", 1)
if *calls != 2 {
t.Fatalf("TTL 过期应重新加载,calls=%d", *calls)
}
// 加载失败(空词表)→ 退避期内不重复打 DB,且不 panic
failCalls := 0
bad := NewEntityIndex(func() map[string]float64 { failCalls++; return nil })
bad.now = func() time.Time { return now }
if got := bad.Extract("织忆", 1); got != nil {
t.Fatalf("空词表应返回 nil, got %v", got)
}
bad.Extract("织忆", 1)
if failCalls != 1 {
t.Fatalf("退避期内应只尝试一次,failCalls=%d", failCalls)
}
now = now.Add(2 * time.Minute)
bad.Extract("织忆", 1)
if failCalls != 2 {
t.Fatalf("退避期过后应重试,failCalls=%d", failCalls)
}
}
func TestExtractDegreeFilterDropsNoiseNode(t *testing.T) {
load, _ := fakeVocab(map[string]float64{
"天气": 3.0e-06,
"一句话": 1.6e-06,
})
idx := NewEntityIndex(load)
idx.Degree = func(name string) int {
if name == "一句话" {
return 2 // 自动切词噪声节点(实测 graph.db:一句话 deg=2)
}
return 50
}
got := idx.Extract("完全不相干的一句话天气不错", 3)
if !reflect.DeepEqual(got, []string{"天气"}) {
t.Fatalf("got %v want [天气]", got)
}
// 度数过滤把候选清空 → 返回 nil(宁可不给,也别给噪声笔记)
idx2 := NewEntityIndex(load)
idx2.Degree = func(string) int { return 0 }
if got := idx2.Extract("完全不相干的一句话天气不错", 3); got != nil {
t.Fatalf("got %v want nil", got)
}
}
func TestNilEntityIndexIsSafe(t *testing.T) {
var idx *EntityIndex
idx.Warm(0)
if got := idx.Extract("织忆", 3); got != nil {
t.Fatalf("expected nil, got %v", got)
}
noLoad := NewEntityIndex(nil)
if got := noLoad.Extract("织忆", 3); got != nil {
t.Fatalf("expected nil, got %v", got)
}
}
+68 -4
View File
@@ -82,6 +82,14 @@ func NewServer() http.Handler {
// 图谱(带 Navigate 结果缓存:TTL 5min,容量 500,热点实体缓存命中加速)
graphStore, cachedGraphStoreRef := storage.NewCachedGraphStore(initGraphStore())
// 整句→实体 拆解索引(节点名词表,TTL 10min;供 /api/v1/graph/notes 兜底。
// 起因:调用方把整句提问当 entity 传,整句匹配不到节点 → 0 篇笔记)
entityIndex := routes.NewEntityIndex(func() map[string]float64 {
return graphStore.PageRank(0.85, 20)
})
entityIndex.Degree = func(name string) int { return graphStore.GetEntityDegree(name) }
entityIndex.Warm(45 * time.Second)
api := routes.NewAPI(ldb, emb, rerank, conflictDetector, graphStore)
// G1: Recall 管线挂图谱扩展
@@ -524,6 +532,9 @@ func NewServer() http.Handler {
// 图谱导航 + Obsidian 笔记关联
mux.HandleFunc("/api/v1/graph/notes", func(w http.ResponseWriter, r *http.Request) {
entity := r.URL.Query().Get("entity")
if entity == "" {
entity = r.URL.Query().Get("query") // 也接受整句 query
}
maxHops := 2
if h := r.URL.Query().Get("max_hops"); h != "" {
if parsed, err := strconv.Atoi(h); err == nil && parsed > 0 {
@@ -539,11 +550,14 @@ func NewServer() http.Handler {
var noteResults []map[string]interface{}
var paths []map[string]interface{}
mode := "none"
var usedEntities []string
if entity != "" {
p, err := graphStore.Navigate(routes.NormalizeEntity(entity), maxHops, "", nil)
norm := routes.NormalizeEntity(entity)
p, err := graphStore.Navigate(norm, maxHops, "", nil)
if err == nil {
paths = p
entities := []string{routes.NormalizeEntity(entity)}
entities := []string{norm}
for _, path := range p {
if s, ok := path["source"].(string); ok {
entities = append(entities, s)
@@ -556,14 +570,64 @@ func NewServer() http.Handler {
noteResults = obsidian.SearchNotesByEntities(entities, maxNotes)
}
}
if len(noteResults) > 0 {
mode = "direct"
} else if cands := entityIndex.Extract(entity, 2); len(cands) > 0 {
// 兜底:entity 是整句自然语言(调用方原样传用户提问)→ 本地把它拆成候选实体
const maxSearchEntities = 8 // 参与笔记匹配的实体上限:候选 + 少量邻居,防噪声淹没
ents := make([]string, 0, maxSearchEntities)
seen := make(map[string]bool, maxSearchEntities)
for _, cand := range cands {
ne := routes.NormalizeEntity(cand)
if ne == "" || seen[ne] {
continue
}
seen[ne] = true
ents = append(ents, ne)
if p, err := graphStore.Navigate(ne, maxHops, "", nil); err == nil {
if len(p) > 20 { // 单跳邻居即可,避免把整个二跳子图塞进响应
p = p[:20]
}
if len(paths) < 50 {
paths = append(paths, p...)
}
for _, path := range p {
if len(ents) >= maxSearchEntities {
break
}
if s, ok := path["source"].(string); ok && !seen[s] {
seen[s] = true
ents = append(ents, s)
}
if t, ok := path["target"].(string); ok && !seen[t] {
seen[t] = true
ents = append(ents, t)
}
}
}
}
if obsidian != nil && len(ents) > 0 {
noteResults = obsidian.SearchNotesByEntities(ents, maxNotes)
}
if len(noteResults) > 0 {
mode = "nl_extract"
usedEntities = cands
log.Printf("[graph/notes] 整句兜底拆实体 %v(实际匹配 %d 个)→ %d 篇笔记(入参 %q)", cands, len(ents), len(noteResults), entity)
}
}
}
respondJSON(w, 200, map[string]interface{}{
resp := map[string]interface{}{
"entity": entity,
"graph_paths": paths,
"notes": noteResults,
"paths_count": len(paths),
"notes_count": len(noteResults),
})
"mode": mode,
}
if len(usedEntities) > 0 {
resp["entities_used"] = usedEntities
}
respondJSON(w, 200, resp)
})
// 自然语言图谱查询 /api/v1/graph/nl_query