Files
memoryweave/go/internal/distill/distill_parser.go
T
小唯 d5b82d5b19 feat(distill): 经验层 category=experience 灰控落地(默认关,t_2595b626)
- experience_gate.go 新增:env 门控 ZHIYI_DISTILL_EXPERIENCE(启动读一次,同 density_gate 写法)、
  ExperienceRecord{Task,Solution,Boundary}(无 confidence 自评,质量复用五维 overall/VD/RU)、
  独立 prompt 附加常量(1157B,拼在 outFmt 之后)、ParseExperienceLine(4 段硬约束 + 反回显)、
  ExperienceGrounded(反张冠李戴:task 对象名必须在 episode 原文有影子,确定性零 LLM)
- engine/parser/server 接线:关态条件短路不可达 ⇒ 关态 prompt 逐字节不变
  (sha256 三臂一致:head-off==tree-off=49295e70…,开态=关态+1157B)
- score_cache 门控开时加 \x00experience-v1 后缀,防旧 prompt 缓存短路灰度
- 落库:接地闸 → 近重复跳过(cosine≥0.98)→ 写现成 category=experience(不造新表/新列)

实测(40 条真实工作笔记,本地 2B):EXP 行出现 32/40=80%,但过格式闸仅 2/40=5%
⇒ 2B 会写 EXP 内容但用自然语言衔接、不拆竖线三段,属能力边界。故**默认关,未部署未 push**。
go test ./internal/distill/ ./internal/api/routes/ -count=1 全绿
2026-11-07 02:41:33 +08:00

269 lines
11 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.
// 织忆 MemoryWeave — 蒸馏输出解析器(行协议 Line Protocol)
//
// 背景(t_180c0179):蒸馏引擎曾让本地 2B 直接产 JSON 再解析,线上 0.43%(35/8058)失败,
// 错误形如 `invalid character '\u00e6' after array element` —— 根因是 LLM 输出里
// 有未转义的内层双引号({"facts":["他说"你好"就这样"]})⇒ 引号提前闭合 ⇒ 解析崩。
// 这是**架构层**缺陷:JSON 是单字节错误即全盘崩溃的格式,2B 的格式合规天花板(99.5~99.8%)
// 由参数量决定,prompt 补不上。根治 = 换格式,不是修解析器。
//
// 行协议把「单条记录的语法风险」降到每条记录独立一行:FACT| 之后整行都是内容,
// 引号、竖线、等号等任意字符都不需要转义。单行坏了丢一行,绝不整条 episode 崩溃。
package distill
import (
"bufio"
"encoding/json"
"log"
"strconv"
"strings"
)
// DistillConfig 蒸馏引擎配置(t_180c0179 新增)。
// OutputFormat: "json"(旧) | "lines"(新,默认)。
// 一行配置回退旧 JSON 路径;旧 prompt + recoverTruncatedJSON + fallbackSingle 全保留不删。
type DistillConfig struct {
OutputFormat string // "json"(旧) | "lines"(新, 默认)
}
// ParseLineFormat 解析行协议(Line Protocol)输出。
//
// 输入形如:
//
// FACT|他说"你好"就这样
// FACT|第二条事实,引号"和"不需要转义
// ENTITY|小唯|person
// ENTITY|ffmpeg|tool
// SCORE|0.8|0.7|0.6|0.9|0.7
// END
//
// 规则:
// - 每条记录独占一行,FACT| / ENTITY| / SCORE| 开头
// - FACT 行:第一个 | 之后整行都是事实内容,可含任意引号、竖线(SplitN(...,2) 保护)
// - ENTITY 行:ENTITY|name|type(SplitN(...,3),type 可缺省)
// - SCORE 行:SCORE|is|su|pa|vd|ru(5 维评分,0.0~1.0,可缺省)
// - END 收尾(可省略);END 之后的行忽略
// - 非 FACT/ENTITY/SCORE 开头的行**静默跳过**(自动丢弃 LLM 的前言废话)
//
// 容错点:单行格式错误 → 丢弃该行不 abort;截断 → 只丢最后一行;
// 无递归无嵌套状态机;**从不返回 error**(最差空切片)。
//
// ok=false 表示未识别到任何有效行(调用方据此落到 JSON 兜底)。
// t_2595b626:新增第 5 返回值 experiences(EXP 行;门控关恒 nil,行为与现状一致)。
func ParseLineFormat(raw string) (facts []string, entities []Entity, scores FiveDScore, experiences []ExperienceRecord, ok bool) {
var lines [][3]string // [0]=type, [1]=name(或fact内容或score), [2]=type(或score串)
scanner := bufio.NewScanner(strings.NewReader(raw))
scanner.Buffer(make([]byte, 0, 64*1024), 1<<20)
var seenEnd bool
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if line == "" {
continue
}
if seenEnd {
break
}
switch {
// 🔴 EXP 分支排在最前:门控关 ⇒ 条件短路不可达,EXP 行走 default「垃圾行
// 静默跳过」,与现状逐字一致(AC1)。门控开 ⇒ 解析 + 单行合法性闸。
// EXP 不进 lines[]:它不是 FACT/ENTITY/SCORE,不参与截断启发式;
// END 之后的行由 seenEnd break 统一忽略。
case experienceGateEnabled && strings.HasPrefix(line, "EXP|"):
// t_2595b626 经验层
if exp := ParseExperienceLine(line); exp != nil {
experiences = append(experiences, *exp)
ok = true
}
case line == "END" || strings.HasPrefix(line, "END|"):
seenEnd = true
case strings.HasPrefix(line, "FACT|"):
// SplitN(...,2):第一个 | 之后整行都是内容(含 | 和引号)
content := line[len("FACT|"):]
if content != "" {
lines = append(lines, [3]string{"FACT", content, ""})
}
case strings.HasPrefix(line, "ENTITY|"):
parts := strings.SplitN(line, "|", 3)
if len(parts) >= 2 && parts[1] != "" {
etype := "entity"
if len(parts) >= 3 && parts[2] != "" {
etype = parts[2]
}
lines = append(lines, [3]string{"ENTITY", parts[1], etype})
}
case strings.HasPrefix(line, "SCORE|"):
// 正常行:SCORE|v1|v2|v3|v4|v5(恰好 5 个 | → SplitN(...,6) 得 6 段)。
// 2026-10-08 修复(t_23f6bce3):2B 常把示例行里的占位符名 is|su|pa|vd|ru
// 照抄进输出 → SCORE|is|su|pa|vd|ru|v1|...|v5(7 段,被 SplitN limit 6 合并成 6 段,
// 前 5 段是占位符名,len(parts)==6 误判通过但存的是占位符而非数值 → 5D 全零)。
// 对策:若尾段含 ≥4 个 |(即原行 >5 段),按「占位符前缀被照抄」处理:
// 取最后一个 | 起、含 4 个 | 的 5 个数值段作为真实评分。
parts := strings.SplitN(line, "|", 6)
if len(parts) == 6 {
vals := parts[1:]
if tail := vals[4]; strings.Count(tail, "|") >= 4 {
// 原行有 >5 段:最后 5 段才是数值(前面被照抄了占位符名/示例)
all := strings.Split(line, "|")
if len(all) > 6 {
vals = all[len(all)-5:]
} else {
// 段数不足以取尾 5 段 → 放弃该行(不存脏值)
vals = nil
}
}
if len(vals) == 5 {
for _, x := range vals {
if !isValidScoreField(x) {
vals = nil
break
}
}
}
if vals != nil {
lines = append(lines, [3]string{"SCORE", strings.Join(vals, "|"), ""})
}
}
default:
// 垃圾行(前言废话/注释等)→ 静默跳过
}
}
// 截断检测(t_180c0179 AC1 用例5):仅当**存在**显式 END 时跳过后续行;
// 缺少 END 不再视为「最后一行被截断」—— 生产 prompt 未要求 END,
// 且模型完整输出的末行(SCORE)不是截断。
// 真截断(半条记录)由「最后一条是半句」的固有概率低 + 上游 max_tokens
// 预留空间(2400)共同压制;本层只做保守丢弃:最后一行若以 FACT|/ENTITY|
// 开头且**该行无完整闭合的下一类型行**才丢(实际简化:末行是 SCORE 保留,
// 末行是 FACT/ENTITY 且总行数>1 则丢 —— 覆盖「半截 FACT」场景)。
if !seenEnd && len(lines) >= 2 {
last := lines[len(lines)-1]
if last[0] == "SCORE" {
// SCORE 行永远是末行(prompt 要求评分放最后一行)→ 保留,不当截断。
// 修复 2026-10-08:此前无 END 就盲丢末行,导致 SCORE 行被系统性抹掉、
// 5D 评分恒为全零 ⇒ 评分闸门形同虚设。
} else {
lines = lines[:len(lines)-1]
}
}
// 有 SCORE 行则解析评分
for _, l := range lines {
if l[0] == "SCORE" {
vals := strings.Split(l[1], "|")
if len(vals) == 5 {
f := []*float64{&scores.IS, &scores.SU, &scores.PA, &scores.VD, &scores.RU}
for i, v := range vals {
if x, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil {
*f[i] = x
}
}
}
}
}
for _, l := range lines {
switch l[0] {
case "FACT":
facts = append(facts, l[1])
ok = true
case "ENTITY":
entities = append(entities, Entity{Name: l[1], Type: l[2], Properties: []string{"llm_extracted"}})
ok = true
}
}
// experiences 在扫描循环内已填充(门控开且行合法)
return facts, entities, scores, experiences, ok
}
// isValidScoreField 判一个 SCORE 字段是否为合法数值(0.0~1.0 浮点)。
// 2026-10-08 t_23f6bce3:SCORE 行被 2B 照抄占位符名(is|su|...)时会混入非数值段,
// 须逐段校验,防止把占位符名当评分存进去。
func isValidScoreField(s string) bool {
x, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
return err == nil && x >= 0.0 && x <= 1.0
}
// parseJSONFormat 旧 JSON 解析路径(从 callLLM5D 原样抽离,作为行协议的兜底)。
// 与原实现逐操作一致:剥 markdown code fence → 找第一个 { 和最后一个 } 截取 →
// Unmarshal → 失败则 recoverTruncatedJSON 救回 → 再 Unmarshal。仍失败返回 ok=false。
func parseJSONFormat(raw string) (LLMResponse, bool) {
c := strings.TrimSpace(raw)
c = strings.TrimPrefix(c, "```json")
c = strings.TrimPrefix(c, "```")
c = strings.TrimSuffix(c, "```")
c = strings.TrimSpace(c)
if idx := strings.Index(c, "{"); idx > 0 {
c = c[idx:]
}
if idx := strings.LastIndex(c, "}"); idx >= 0 && idx < len(c)-1 {
c = c[:idx+1]
}
c = strings.TrimSpace(c)
var llmResp LLMResponse
if err := json.Unmarshal([]byte(c), &llmResp); err != nil {
recovered, ok := recoverTruncatedJSON(c)
if !ok {
return LLMResponse{}, false
}
c = recovered
if err := json.Unmarshal([]byte(c), &llmResp); err != nil {
return LLMResponse{}, false
}
}
return llmResp, true
}
// parseDistillOutput 三级兜底链(t_180c0179):
//
// ParseLineFormat(raw) → 旧 parseJSONFormat(raw) → 空切片
//
// 第一级行协议优先(LLM 被训练成行协议输出);若未识别到任何行(如模型仍产 JSON),
// 落到第二级旧 JSON 兜底;两级都空则返回空 LLMResponse(最差空切片,不返回 error)。
// 这样上游 distillOne 对「解析不出」走启发式提取,而不是把整条 episode 当空结果丢掉。
//
// 2026-10-12:两条分支的返回值都过一遍 StripPromptEcho —— 实测 2B 会把 prompt
// 「重要指令」块里的教学示例(「用户昨天买了苹果。」「Galway, Ireland」…)原样抄进输出,
// 解析器照单全收 ⇒ 示例事实被质量门丢光(生产 facts=0 达 301 次)+ 示例实体污染图谱。
// 此处是**唯一咽喉**(engine.go 只从此处取 LLM 结果),防线放这里两条路径都覆盖。
// logEchoStrip 只在实际剔除时打一行(生产用它验证防线在跑,且能看到被剔的是不是示例)。
func logEchoStrip(path string, st EchoStats) {
if st.Total() == 0 {
return
}
log.Printf("[distill][ECHO] path=%s 剔除教学示例回显 %d 项(facts=%d entities=%d other=%d allFactsEcho=%v)样例=%q",
path, st.Total(), st.FactsDropped, st.EntitiesDropped, st.OtherDropped, st.AllFactsWereEcho,
truncate(st.Sample, 40))
}
func parseDistillOutput(raw string) LLMResponse {
facts, entities, scores, experiences, ok := ParseLineFormat(raw)
if ok {
var names []string
for _, en := range entities {
names = append(names, en.Name)
}
resp, st := StripPromptEcho(LLMResponse{
IS: scores.IS,
SU: scores.SU,
PA: scores.PA,
VD: scores.VD,
RU: scores.RU,
Facts: facts,
Entities: names,
})
// t_2595b626:EXP 行在 ParseExperienceLine 已过单行合法性闸;落库前还有
// ExperienceGrounded 接地闸兜底(api/server.go)。
resp.Experiences = experiences
logEchoStrip("line", st)
return resp
}
if resp, ok2 := parseJSONFormat(raw); ok2 {
var st EchoStats
resp, st = StripPromptEcho(resp)
logEchoStrip("json", st)
return resp
}
return LLMResponse{}
}