Files
memoryweave/go/internal/distill/echo_guard.go
T

261 lines
10 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 distill
import (
"strings"
"unicode"
"unicode/utf8"
)
// ─── 教学示例回显防线(2026-10-12)─────────────────────────────────────────
//
// 起因(生产实测):prompt 的「重要指令」块为了让 2B 理解格式而写的**示例取值**,
// 被模型整段照抄进输出。解析器无法分辨「示例」与「真抽取」,于是照单全收:
//
// · 抄来的示例事实(如「用户昨天买了苹果。」= 9 字)< 20 字 → 被质量门丢光
// ⇒ 生产日志 `facts=0` 出现 301 次(约 76% 的 episode 产出为零)
// · 抄来的示例实体(The Name of the Wind by Patrick Rothfuss / Galway, Ireland /
// 慈善篮球赛 / 某饮料公司 …)会被当真实实体写进记忆图谱 ⇒ 垃圾节点
// · 抄来的示例评分行(若模型把示例数值一并抄出)
//
// ⚠️ 不要把「评分恒为 0.5」也算到这个账上:现 prompt 里没有 0.5 的示例,
// 而 IsDegenerateScore 的实测说明模型**本就会**合法地给出五维同值(0.8×5 / 0.0×5)。
// 0.5×5 的成因未证实,不归因(2026-10-12 自查撤回)。
//
// 判据:**逐字相同**(归一化后)才算回显;对纯教学 illustration 额外允许
// 「≥4 字的子串」命中(用于抓 John / Patrick Rothfuss 这类被拆碎的残片)。
//
// 为什么不一律用子串:格式说明类字面量里含**真实 token**(如「牵挂: … 待办.md …」),
// 用子串会把真实实体「待办.md」误杀 → 故这类只认整体逐字相同(allowSubstr=false)。
//
// 代价不对称:漏掉一条回显 = 永久污染记忆;误杀一条恰好像示例的短事实 = 损失一条低信息事实。
type echoLiteral struct {
text string
allowSubstr bool // true=纯教学 illustration,≥4 字子串也算回显
}
var promptEchoLiterals = []echoLiteral{
// —— 事实改写示例(prompt「2. 进行轻量上下文补全」)——
{"用户今早喝了咖啡", true},
{"用户昨天买了苹果。", true},
{"用户的朋友John在学医。", true},
{"你好", false},
{"哈哈", false},
{"谢谢", false},
// —— 「3. 保留所有具体实体和细节」的 illustration:纯教学,允许子串命中 ——
{"The Name of the Wind by Patrick Rothfuss", true},
{"一本书", false},
{"Galway, Ireland", true},
{"北京海淀区", true},
{"慈善篮球赛", true},
{"留学项目", true},
{"某饮料公司", true},
{"4年前", false},
{"下个月", false},
{"上周", false},
// —— 结构化前缀示例:含真实 token(待办.md)→ 只认整体逐字相同 ——
{"牵挂: 待处理: 待办.md 里已打勾的旧条目清理", false},
// —— 输出格式占位符(模型常把这些当内容抄出来)——
{"独立事实1", false},
{"独立事实2", false},
{"决定1", false},
{"结论1", false},
{"行动1", false},
{"问题1", false},
{"entity1", false},
{"entity2", false},
{"实体名", false},
{"实体类型", false},
{"五个数字用竖线分隔", false},
}
// normalizeEcho 归一化:去首尾空白 + 去尾部句读(模型常省/加句号)。
func normalizeEcho(s string) string {
s = strings.TrimSpace(s)
return strings.TrimRight(s, "。..!!??~~、,, ")
}
// IsPromptEcho 判断一条事实/实体名是否只是 prompt 教学示例的回显。
func IsPromptEcho(s string) bool {
n := normalizeEcho(s)
if n == "" {
return false
}
nr := utf8.RuneCountInString(n)
for _, l := range promptEchoLiterals {
ln := normalizeEcho(l.text)
if ln == "" {
continue
}
if n == ln {
return true
}
if l.allowSubstr && nr >= 4 && strings.Contains(ln, n) {
return true
}
}
return false
}
// ─── 概念/实体提取路径([graph/notes] 兜底拆实体)──────────────────────────────
//
// 背景(GA-P0-5):蒸馏侧 IsPromptEcho 只罩 LLM 输出的 facts/entities,图谱污染闭环
// 还有另一条腿 —— 审计笔记把污染词当证据列出来 → 笔记被蒸馏成 episode → 调用方把整句
// 提问原样传给 /api/v1/graph/notes → entity_index 从图谱节点名词表拆出候选实体 → 若
// 候选只是 prompt 教学示例的回显残片,会被当真实实体写回图谱 ⇒ 已删除的污染节点
// (n_galway / n_rothfuss / n_the_name_of_the_wind)被重建。
//
// 判据与 IsPromptEcho 完全同源(都读 promptEchoLiterals,清单本身零改动):逐字相等
// (归一化后)或 illustration 类(allowSubstr=true)的 ≥4 字子串残片即算回显;占位符类
// (allowSubstr=false)只认逐字相等。唯一差别是输入形态:图谱节点名是「n_the_name_of_the_wind」
// 这种规整形,需先还原成可读文本(去 n_、下划线→空格、小写)再比对。
//
// GA-P0-6 补两层判据(都从 9 条 allowSubstr=true 的 illustration 派生,清单本身零改动):
// 1. 标点/空格不敏感 —— 实体侧 `galway ireland` 与字面量 `Galway, Ireland` 因内部逗号
// 差异既不等也不构成子串 ⇒ 比对前两侧都剥成「只留字母数字汉字」,等价即拦。
// 这正是图谱节点名最常见的形态(该家族第 1 轮漏删也栽在这个逗号上)。
// 2. 多示例词并列 —— 审计散文被蒸馏/拆实体后产出形如「A_B_示例词1_示例词2_…」的节点。
// 候选若包含整条 illustration 字面量(归一化后),或含 ≥2 个 illustration 显著 token
// (promptEchoTokens),判回显;单 token(只出现 1 个)不拦,保留给真实讨论。
//
// 与 IsPromptEcho 一样**只拦「逐字相等/残片」级**,不拦普通包含 —— 例如「用户提到
// galway」里 galway 若是真实实体,只要它不在某条示例字面量的残片里就放行;误杀面与
// 蒸馏侧一致(那里已实测会杀 John / Patrick Rothfuss 这类单字残片)。
func IsPromptEchoEntity(s string) bool {
n := normalizeEchoEntity(s)
if n == "" {
return false
}
nk := compareKey(strings.ToLower(n))
nr := utf8.RuneCountInString(n)
// 判据二:≥2 个 illustration 显著 token 并列 ⇒ 示例词被拼进同一节点名。
if tokenEchoCount(nk) >= 2 {
return true
}
for _, l := range promptEchoLiterals {
ln := strings.ToLower(normalizeEcho(l.text))
if ln == "" {
continue
}
lk := compareKey(ln)
if nk == lk {
return true
}
if l.allowSubstr && nr >= 4 && strings.Contains(lk, nk) && tokenEchoCount(nk) >= 1 {
return true
}
// 判据二:候选包含整条 illustration 字面量 ⇒ 示例词被拼进长节点名。
if l.allowSubstr && strings.Contains(nk, lk) {
return true
}
}
return false
}
// normalizeEchoEntity 把图谱节点名归一成可与字面量比对的形态。
func normalizeEchoEntity(s string) string {
s = strings.TrimPrefix(s, "n_")
s = strings.ReplaceAll(s, "_", " ")
s = strings.ToLower(s)
return normalizeEcho(s)
}
// promptEchoTokens:从 9 条 allowSubstr=true 的 illustration 里提取的显著 token
// (地名/人名/书名/活动名/公司名)。候选节点名若包含 ≥2 个 ⇒ 判为多示例词并列的回显。
// 单 token(只出现 1 个)不拦 —— 如「northern ireland」只含 ireland,保留给真实讨论。
var promptEchoTokens = []string{
"john", // 人名(用户的朋友John在学医。)
"rothfuss", // 人名(The Name of the Wind by Patrick Rothfuss)
"the name of the wind", // 书名
"galway", // 地名
"ireland", // 地区
"北京海淀区", // 地名
"慈善篮球赛", // 活动名
"留学项目", // 活动名
"某饮料公司", // 公司名
}
// tokenEchoCount 统计 key 命中的 illustration 显著 token 数。
func tokenEchoCount(key string) int {
c := 0
for _, t := range promptEchoTokens {
if strings.Contains(key, compareKey(strings.ToLower(t))) {
c++
}
}
return c
}
// compareKey 把字符串压成「只留字母数字汉字」的形态(去掉所有标点/空白),
// 用于标点/空格不敏感比对:`galway ireland` 与 `galway, ireland` 视为相同。
func compareKey(s string) string {
var b strings.Builder
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
b.WriteRune(r)
}
}
return b.String()
}
// EchoStats 记录本次剔除量,供日志观测。
type EchoStats struct {
FactsDropped int
EntitiesDropped int
OtherDropped int
AllFactsWereEcho bool // 全部事实都是回显 ⇒ 本次 LLM 输出对事实部分无效
Sample string // 第一条被剔除的原文(生产日志据此确认"是不是示例")
}
// Total 返回被剔除的条目总数。
func (s EchoStats) Total() int { return s.FactsDropped + s.EntitiesDropped + s.OtherDropped }
// StripPromptEcho 剔除回显项。
//
// 若事实**全部**来自回显 ⇒ 连评分一起作废(评分行与事实同源,都是抄来的),
// 并清空其余字段,返回空 LLMResponse,让上游落到「从原文启发式提取」而不是
// 把示例当产出入库。这是**结构化降级**:系统仍产出东西,但不产出垃圾。
func StripPromptEcho(resp LLMResponse) (LLMResponse, EchoStats) {
var st EchoStats
keep := func(in []string) []string {
if len(in) == 0 {
return in
}
out := make([]string, 0, len(in))
for _, s := range in {
if IsPromptEcho(s) {
if st.Sample == "" {
st.Sample = s
}
continue
}
out = append(out, s)
}
return out
}
beforeFacts := len(resp.Facts)
resp.Facts = keep(resp.Facts)
st.FactsDropped = beforeFacts - len(resp.Facts)
beforeEnt := len(resp.Entities)
resp.Entities = keep(resp.Entities)
st.EntitiesDropped = beforeEnt - len(resp.Entities)
beforeOther := len(resp.Decisions) + len(resp.Conclusions) + len(resp.ActionsTaken) + len(resp.OpenQuestions)
resp.Decisions = keep(resp.Decisions)
resp.Conclusions = keep(resp.Conclusions)
resp.ActionsTaken = keep(resp.ActionsTaken)
resp.OpenQuestions = keep(resp.OpenQuestions)
st.OtherDropped = beforeOther - (len(resp.Decisions) + len(resp.Conclusions) + len(resp.ActionsTaken) + len(resp.OpenQuestions))
if beforeFacts > 0 && len(resp.Facts) == 0 {
st.AllFactsWereEcho = true
// 评分与事实同源 ⇒ 一起作废(避免把示例评分当有效判断喂给分道逻辑)
return LLMResponse{}, st
}
return resp, st
}