Files
memoryweave/go/internal/distill/engine.go
T
小唯 88f610aa1e feat(memory-source): 打通 commit→distill→memories.source→recall 全链(含 metadata.source 与 wiki:<路径> 标记)
- recall.go: RecallResult.Source = 记忆 source(此前只有 struct 字段没人填)
- distill/engine.go: DistillInput.Source(来源透传)
- auto_distill.go: AutoDistillTrigger 增加 source 参数并透传
- routes/core.go: /commit 请求体新增 source + metadata(此前缺失 → Go 静默丢弃 → 入库恒空)
- server.go: 蒸馏产物 Source = wiki:<路径>(有出处时),手动蒸馏端点也支持 source
- 清理 worker 误提交的 15MB 二进制(go/cmd/zhiyid/zhiyid-new)并加 .gitignore
2026-09-26 21:43:54 +08:00

1065 lines
36 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 — 蒸馏引擎核心
// 两阶段蒸馏:硬规则过滤 → LLM 5维度评估 → 批量蒸馏
package distill
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/xiaoxue/memoryweave/internal/metrics"
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
)
// ─── 类型定义 ────────────────────────────────────────────────
// Category 记忆类别
type Category string
const (
CatSystemFact Category = "system_fact"
CatUserPref Category = "user_pref"
CatProjContext Category = "proj_context"
CatToolUsage Category = "tool_usage"
CatCodeSnippet Category = "code_snippet"
CatDecision Category = "decision"
)
// DistillInput 蒸馏输入
type DistillInput struct {
EpisodeID string
Content string
Category Category
Namespace string
AgentID string
// 2026-09-26:来源(笔记路径等)—— 透传到蒸馏产物 MemoryRecord.Source,recall 时带回
Source string
}
// DistillResult 蒸馏输出
type DistillResult struct {
Facts []string
Entities []Entity
Score5D FiveDScore
Overall float64
Index []AAAKEntry // P4: AAAK 压缩索引(每条事实的紧凑摘要)
}
// Entity 实体
type Entity struct {
Name string `json:"name"`
Type string `json:"type"` // entity / fact / decision / skill
Properties []string `json:"properties"`
}
// FiveDScore LLM 5维评估
type FiveDScore struct {
IS float64 `json:"is"` // Information Significance
SU float64 `json:"su"` // Strategic Utility
PA float64 `json:"pa"` // Practical Applicability
VD float64 `json:"vd"` // Validation Durability
RU float64 `json:"ru"` // Recall Usability
}
// LLMResponse LLM 完整响应(5D + 实体 + 事实)
type LLMResponse struct {
IS float64 `json:"is"`
SU float64 `json:"su"`
PA float64 `json:"pa"`
VD float64 `json:"vd"`
RU float64 `json:"ru"`
Entities []string `json:"entities"`
Facts []string `json:"facts"` // 旧格式兼容
Decisions []string `json:"decisions"` // 新格式:决策结论
Conclusions []string `json:"conclusions"` // 新格式:最终结论
ActionsTaken []string `json:"actions_taken"` // 新格式:采取的行动
OpenQuestions []string `json:"open_questions"` // 新格式:悬而未决
}
// LLM 5维权重
var Weights = FiveDScore{
IS: 0.20,
SU: 0.20,
PA: 0.15,
VD: 0.25,
RU: 0.20,
}
// ─── 蒸馏引擎 ────────────────────────────────────────────────
// Engine 蒸馏引擎
type Engine struct {
mu sync.Mutex
// LLM 配置
LLMEndpoint string
LLMModel string
APIKey string
// 队列
queue []DistillInput
batchSize int
batchTimeout time.Duration
lastDistill time.Time
// P3 双缓冲:token 积累触发(LightMem 移植)
pendingTokens int
flushTokenThreshold int
// 成本控制
dailyLimit int
dailyUsed int
dailyReset time.Time
// 并发蒸馏(2026-09-21 加)
flushing atomic.Bool // 防多轮 flush 重叠:原来 go e.flush() 无互斥,队列一满就可能叠加并发打爆本地 2B
emitMu sync.Mutex // 串行化 emitResult(存储写回不并发;LLM 调用才并发)
// AC2 (t_9b2c7943):与本地 2B 槽位匹配的有效并发(探测 /props 的 total_slots,封顶 distillConcurrencyMax)
concurrency int
// HTTP客户端
client *http.Client
}
// distillConcurrency 单轮 flush 内并发蒸馏的条数上限(**封顶值**,非固定值)。
//
// 起因(2026-09-21 实测):摄入 ~132 条/min、蒸馏仅 11.6 条/min 且队列持续积压。
// 逐条排查发现瓶颈**不是 batch 大小**(batchSize 只决定一轮取多少条,
// 实测 batch 恒为 10、token 阈值从未触发),而是 flush 内**串行**的 LLM 调用:
// 每条 1 次 callLLM5D ≈ 5.2s,10 条 = 52s,吞吐被单条延迟锁死。
// 故真正的杠杆 = 让 LLM 调用并发(本地 2B 走 8081 队列代理);
// 写回 emitResult 仍串行,避免并发写存储。
//
// AC2 (t_9b2c7943):并发不再拍脑袋写死 3,而是**与本地 2B 槽位匹配**——
// 启动/刷新时探测端点 `total_slots`,并发 = min(槽数, 封顶值)。
// 判据(小怡给):若并发 > 槽数 → 打爆槽位 → 429 不降反升,必须下调到 ≤ 槽数。
// 实测 2026-09-21:106 llama-server 是**单槽**(total_slots=1),故匹配值=1。
const distillConcurrencyMax = 3 // 并发封顶(即使槽更多也不超过 3,保护 2B)
func NewEngine(llmEndpoint, llmModel, apiKey string) *Engine {
e := &Engine{
LLMEndpoint: llmEndpoint,
LLMModel: llmModel,
APIKey: apiKey,
batchSize: 10,
batchTimeout: 5 * time.Minute,
dailyLimit: 5000,
flushTokenThreshold: 2000, // LightMem short-term buffer
client: &http.Client{Timeout: 120 * time.Second},
}
// AC2:启动即探测端点槽位,把并发降到 min(槽数, 封顶)。探测失败保守取 1
// (宁串行也不打爆未知槽位);之后每 flush 周期可 RefreshConcurrency() 再探。
e.RefreshConcurrency()
return e
}
// RefreshConcurrency 探测 LLM 端点的 llama-server 槽位数(`/props` 的 total_slots),
// 把本轮有效并发设为 min(槽数, distillConcurrencyMax)。
//
// 端点形如 http://host:8081/v1/chat/completions(队列代理或 llama-server 直连)。
// 探测:GET 到「/props」路径(取 endpoint 的 host,挂 /props)。llama-server 返回
// `total_slots`;队列代理 8081 若不透传 /props 则 404 → 保守取 1。
// 探测失败(连接不通/非 JSON)也保守取 1。这是「只改码」阶段的安全默认——
// 宁可串行,也不在未知槽位上限时并发打爆本地 2B。
func (e *Engine) RefreshConcurrency() int {
slots := probeLLMSlots(e)
c := slots
if c < 1 {
c = 1
}
if c > distillConcurrencyMax {
c = distillConcurrencyMax
}
e.mu.Lock()
e.concurrency = c
e.mu.Unlock()
log.Printf("[distill] RefreshConcurrency: endpoint=%s total_slots=%d → concurrency=%d (max=%d)",
e.LLMEndpoint, slots, c, distillConcurrencyMax)
return c
}
// currentConcurrency 返回当前有效并发(未探测前 = 1,安全默认)。
func (e *Engine) currentConcurrency() int {
e.mu.Lock()
defer e.mu.Unlock()
if e.concurrency < 1 {
return 1
}
return e.concurrency
}
// probeLLMSlots 探测 llama-server 槽位(/props 的 total_slots)。
// 取 endpoint 的 host:port,GET http://host:port/props。读不到 → 返回 1(保守)。
func probeLLMSlots(e *Engine) int {
host := e.LLMEndpoint
if i := strings.Index(host, "http"); i >= 0 {
host = host[i:]
}
// 拆出 scheme://host:port
rest := host
if i := strings.Index(rest, "://"); i >= 0 {
rest = rest[i+3:]
}
if i := strings.Index(rest, "/"); i >= 0 {
rest = rest[:i] // 去掉 /v1/chat/completions
}
propsURL := "http://" + rest + "/props"
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(propsURL)
if err != nil {
log.Printf("[distill] slot probe failed (%v) → assume 1 slot", err)
return 1
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
var p struct {
TotalSlots int `json:"total_slots"`
}
if err := json.Unmarshal(body, &p); err != nil || p.TotalSlots < 1 {
// 队列代理可能不透传 /props(404/非JSON)→ 保守 1 槽
return 1
}
return p.TotalSlots
}
// estimateTokens 粗略 token 估算(中文≈1 token/字符,英文≈1 token/4字符)
// 用于 P3 双缓冲触发,不需要精确(只影响批量时机)
func estimateTokens(s string) int {
runes := len([]rune(s))
if runes == 0 {
return 0
}
// 中文按 1 token/字符,英文按 1 token/4 字符近似
// 简单折中:rune 数 / 2
return (runes + 1) / 2
}
// maxDistillTokens 蒸馏 prompt 最大 token 数(8k token 保护本地 2B 单槽)
const maxDistillTokens = 8192
// limitDistillContent 按 token 上限截断内容,返回截断后内容及日志信息
func limitDistillContent(content string) (string, int, int) {
tokens := estimateTokens(content)
if tokens <= maxDistillTokens {
return content, tokens, 0
}
// 截断:保留前 maxDistillTokens 个 token 对应的字符
runeCount := maxDistillTokens * 2 // 粗略换算:token ≈ chars/2
if runeCount > len([]rune(content)) {
runeCount = len([]rune(content))
}
truncated := string([]rune(content)[:runeCount])
log.Printf("[distill] prompt truncated: %d→%d tokens (%d→%d chars)",
tokens, estimateTokens(truncated), len(content), runeCount)
return truncated, estimateTokens(truncated), tokens
}
// Enqueue 入队
func (e *Engine) Enqueue(input DistillInput) {
e.mu.Lock()
defer e.mu.Unlock()
if !HardRulesPass(input.Content) {
return
}
e.queue = append(e.queue, input)
e.pendingTokens += estimateTokens(input.Content)
// P3 双缓冲触发:token 积累达阈值 或 条数达 batchSize 或 超时
shouldFlush := e.pendingTokens >= e.flushTokenThreshold || len(e.queue) >= e.batchSize
timeout := time.Since(e.lastDistill) > e.batchTimeout
if shouldFlush || (timeout && len(e.queue) > 0) {
go e.flush()
}
}
// flush 批量蒸馏
func (e *Engine) flush() {
// 互斥:队列一满就 go flush(),原实现允许多轮重叠 → 并发叠加打爆本地 2B 单/双槽。
// 已有轮次在跑就直接返回,队列留给它(它 drain 时会连新来的条目一起取走)。
if !e.flushing.CompareAndSwap(false, true) {
return
}
defer e.flushing.Store(false)
e.mu.Lock()
if len(e.queue) == 0 {
e.mu.Unlock()
return
}
batch := e.queue
e.queue = nil
e.pendingTokens = 0
e.lastDistill = time.Now()
e.mu.Unlock()
log.Printf("[distill] flush START: batch=%d items, dailyUsed=%d/%d, endpoint=%s, model=%s",
len(batch), e.dailyUsed, e.dailyLimit, e.LLMEndpoint, e.LLMModel)
// Phase F: 更新 LLM 调用计数
metrics.DistillLLMCallsToday.Set(float64(e.dailyUsed))
// 成本控制检查
e.checkDailyLimit()
if e.dailyUsed >= e.dailyLimit {
log.Printf("[distill] flush FALLBACK: daily limit reached (%d/%d)", e.dailyUsed, e.dailyLimit)
results := fallbackDistill(batch)
e.emitResults(results)
return
}
// LLM 蒸馏:并发调用(吞吐杠杆),写回串行(emitMu)
// AC2:并发度与本地 2B 槽位匹配(探测 total_slots,封顶 3)。
// 启动时 NewEngine 已探测过一次;这里每轮 flush 前再 RefreshConcurrency() 探测一次,
// 以便在「部署后槽位数变化」时自动跟随。
var wg sync.WaitGroup
effConcurrency := e.RefreshConcurrency() // 探一次,拿本轮有效并发
sem := make(chan struct{}, effConcurrency)
var processed int64
for _, input := range batch {
wg.Add(1)
sem <- struct{}{} // 取槽(满则阻塞,天然限流)
go func(in DistillInput) {
defer wg.Done()
defer func() { <-sem }()
result := e.distillOne(in)
log.Printf("[distill] distillOne done: episode=%s facts=%d entities=%d",
in.EpisodeID, len(result.Facts), len(result.Entities))
atomic.AddInt64(&processed, 1)
e.emitMu.Lock()
e.emitResult(in, result)
e.emitMu.Unlock()
}(input)
}
wg.Wait()
// dailyUsed 一次性累加(原实现每条 ++ 且无锁 = 数据竞争,/stats 读同一字段)
e.mu.Lock()
e.dailyUsed += int(atomic.LoadInt64(&processed))
e.mu.Unlock()
log.Printf("[distill] flush DONE: processed %d items (concurrency=%d)", len(batch), effConcurrency)
}
// distillOne 蒸馏单条
func (e *Engine) distillOne(input DistillInput) DistillResult {
// 如果 LLM 端点不可用,降级
if e.LLMEndpoint == "" {
log.Printf("[distill] LLMEndpoint empty, fallback for %s", input.EpisodeID)
return fallbackSingle(input)
}
llmResp, err := e.callLLM5D(input.Content)
if err != nil {
log.Printf("[distill] callLLM5D err for %s: %v", input.EpisodeID, err)
return fallbackSingle(input)
}
score := FiveDScore{IS: llmResp.IS, SU: llmResp.SU, PA: llmResp.PA, VD: llmResp.VD, RU: llmResp.RU}
overall := score.IS*Weights.IS +
score.SU*Weights.SU +
score.PA*Weights.PA +
score.VD*Weights.VD +
score.RU*Weights.RU
log.Printf("[distill] score for %s: overall=%.3f is=%.2f su=%.2f pa=%.2f vd=%.2f ru=%.2f",
input.EpisodeID, overall, score.IS, score.SU, score.PA, score.VD, score.RU)
if overall < 0.7 && score.VD < 0.8 {
// 人侧短事实(画像/心迹/牵挂/偏好/习惯/目标)是用户亲口陈述,
// LLM 打分天然偏低(短、无上下文),不应因分数被丢弃——否则"牧尘不在招商局工作"
// 这类关键事实永远到不了 memories,t6 永远比对不到。
if !isSoulfulShortFact(input.Content) {
log.Printf("[distill] score below threshold for %s, skip", input.EpisodeID)
// 即使阈值未通过,仍然用 LLM 实体提取(如果有的话)
if len(llmResp.Entities) == 0 {
return DistillResult{}
}
}
}
// 优先使用 LLM 提取的实体和事实
var entities []Entity
var facts []string
if len(llmResp.Entities) > 0 {
for _, name := range llmResp.Entities {
entities = append(entities, Entity{
Name: name, Type: "entity", Properties: []string{"llm_extracted"},
})
}
} else {
// 降级:启发式提取
_, heuristicEntities := e.extractFacts(input.Content)
entities = heuristicEntities
}
// 事实:优先使用新的结构化字段(decisions/conclusions/actions_taken/open_questions)
// 降级:回退到 llmResp.Facts(旧格式)→ 再降级:启发式提取
hasStructuredFields := len(llmResp.Decisions) > 0 || len(llmResp.Conclusions) > 0 ||
len(llmResp.ActionsTaken) > 0 || len(llmResp.OpenQuestions) > 0
if hasStructuredFields {
// 新格式:合并 decisions/conclusions/actions_taken/open_questions 到 facts
facts = append(facts, llmResp.Decisions...)
facts = append(facts, llmResp.Conclusions...)
facts = append(facts, llmResp.ActionsTaken...)
facts = append(facts, llmResp.OpenQuestions...)
log.Printf("[distill] structured fields: decisions=%d conclusions=%d actions=%d open=%d",
len(llmResp.Decisions), len(llmResp.Conclusions),
len(llmResp.ActionsTaken), len(llmResp.OpenQuestions))
} else if len(llmResp.Facts) > 0 {
facts = llmResp.Facts
} else {
heuristicFacts, _ := e.extractFacts(input.Content)
facts = heuristicFacts
}
// 2026-09-07 质量门槛(t_cc07ef4b): LLM 提炼 fact 入库前过滤
// <20字/纯疑问句/状态汇报型 拒绝; 20-50字需含实体或动词短语
// 在源头过滤, 使图谱/AAAK/记忆库一律只看到质量事实
if before := len(facts); before > 0 {
facts = FilterQualityFacts(facts)
if dropped := before - len(facts); dropped > 0 {
log.Printf("[distill] quality gate dropped %d/%d facts for %s", dropped, before, input.EpisodeID)
}
}
// P4: 生成 AAAK 压缩索引(每条事实的紧凑摘要,供召回快速定位)
index := buildAAAKIndex(facts, entities, overall)
if len(index) > 0 {
logAAAKIndex(index)
}
return DistillResult{
Facts: facts,
Entities: entities,
Score5D: score,
Overall: overall,
Index: index,
}
}
// callLLM5D 调用 LLM 进行 5维评估 + 实体/事实提取
func (e *Engine) callLLM5D(content string) (LLMResponse, error) {
// 2026-09-14 限制 distill prompt ≤8k token,防止打爆本地 2B 单槽
content, sentTokens, origTokens := limitDistillContent(content)
if origTokens > maxDistillTokens {
log.Printf("[distill] content truncated for LLM call: %d→%d tokens (limit=%d)", origTokens, sentTokens, maxDistillTokens)
}
// LightMem 式逐条事实提取 prompt(2026-08-11 移植)
// 精华:逐条判断含事实 → 轻量补全独立句 → 保留全部实体细节 → 推断隐含信息 → 时间区分
prompt := fmt.Sprintf(`你是一个个人信息提取器。从以下对话内容中提取所有可能的用户事实信息,以JSON格式返回。
输入格式:
[时间戳, 星期] 说话者: 消息
...
重要指令:
1. 必须按顺序逐条处理每条消息。对每条消息,判断是否包含事实信息。
- 如果包含 → 提取并改写为独立的完整句子
- 如果不包含(纯问候、填充语、无关评论)→ 跳过
- 不要因为信息看起来微小、琐碎或不重要就跳过。即使是小细节(如"用户今早喝了咖啡")也必须保留。只有完全无意义的(如"你好"、"哈哈"、"谢谢")才跳过。
2. 进行轻量上下文补全,使每个事实成为清晰的独立陈述:
- "user: 昨天买了苹果" → "用户昨天买了苹果。"
- "user: 我的朋友John在学医" → "用户的朋友John在学医。"
- 例外:若原文以「牵挂:」「画像:」「心迹:」「偏好:」「习惯:」「目标:」等结构化前缀开头,生成的 fact 必须保留原前缀,不要改写为自然句(例:原文「牵挂: 待处理: 待办.md 里已打勾的旧条目清理」→ 生成的 fact 保留「牵挂: 待处理: 待办.md 里已打勾的旧条目清理」,不要改成「用户牵挂:待办.md 里已打勾的旧条目需要清理」)。
3. 保留所有具体实体和细节:
- 完整名称: "The Name of the Wind by Patrick Rothfuss"(不是"一本书")
- 完整地点: Galway, Ireland; 北京海淀区
- 具体事件名: 慈善篮球赛、留学项目
- 数字和数量: 4年前、下个月、上周
- 公司/组织名: 某饮料公司
4. 推断隐含信息:如果多个相关条目提到 → 可以推断一般模式(保留具体事实和推断结论为独立条目)
5. 时间处理:区分提及时间(何时说的)和事件时间(何时发生的)
- 相对时间(昨天、上周、X前、下个月)→ 保留相对时间并引用消息时间戳
- 持续/永久事实 → 无需时间标注
6. 额外提取:
- decisions: 明确的决策结论(做了什么决定、选了什么方案、拒绝了什么)
- conclusions: 最终结论或答案
- actions_taken: 采取的具体行动
- open_questions: 悬而未决的问题
- entities: 提到的关键实体(系统名、工具名、人名、技术名词)
输出格式(严格JSON):
{"facts": ["独立事实1", "独立事实2"], "decisions": ["决定1"], "conclusions": ["结论1"], "actions_taken": ["行动1"], "open_questions": ["问题1"], "entities": ["entity1", "entity2"], "is": 0.8, "su": 0.7, "pa": 0.6, "vd": 0.9, "ru": 0.7}
评分说明:is/su/pa/vd/ru 是 0.0 到 1.0 之间的浮点数(越高越好),不要用 0-10 整数。
要求:除非消息完全无意义,否则提取并输出为事实。facts 要详尽,不要只给1条摘要。
内容:
%s
`, truncate(content, 1000))
body := map[string]interface{}{
"model": e.LLMModel,
"messages": []map[string]string{
{"role": "user", "content": prompt},
},
"temperature": 0.2,
// AC3 (t_9b2c7943): 1200→2400。prompt 里"facts 要详尽"与 max_tokens 自相矛盾——
// 1200 会在 facts 数组中途截断 → 非法 JSON → 直接 parse 失败丢整条。提到 2400 给足
// 详尽 facts 的空间;即使仍截断,下方 recoverTruncatedJSON 会兜底救回。
"max_tokens": 2400,
}
jsonBody, err := json.Marshal(body)
if err != nil {
return LLMResponse{}, err
}
// AC1 (t_9b2c7943): 429/5xx 指数退避 + 抖动重试(上限 2 次额外重试,退避上限 ~8s)。
// 原实现:client.Do 失败/限流 → 直接 return err → 上层 distillOne 立刻 fallbackSingle
// (启发式降级、质量下降)。现在:遇 429 或 5xx,先退避重试,真不行再走 fallback。
// 抖动避免并发 3 条同时醒来再次撞 429(惊群)。
const (
maxRetries = 2 // 额外重试次数(首次不算)
initialDelay = 300 * time.Millisecond
maxDelay = 8 * time.Second // 单次退避上限
)
rng := newRand()
var respBody []byte
var lastStatus int
for attempt := 0; ; attempt++ {
req, reqErr := http.NewRequest("POST", e.LLMEndpoint, bytes.NewReader(jsonBody))
if reqErr != nil {
return LLMResponse{}, reqErr
}
req.Header.Set("Content-Type", "application/json")
if e.APIKey != "" {
req.Header.Set("Authorization", "Bearer "+e.APIKey)
}
resp, doErr := e.client.Do(req)
if doErr != nil {
// 网络/超时错误:可重试;到上限即上抛,让上层走 fallback。
if attempt < maxRetries {
d := backoffDelay(attempt, initialDelay, maxDelay, rng)
log.Printf("[distill] callLLM5D transient err (attempt %d/%d): %v → retry in %v",
attempt+1, maxRetries, doErr, d)
time.Sleep(d)
continue
}
return LLMResponse{}, doErr
}
status := resp.StatusCode
respBody, _ = io.ReadAll(resp.Body)
resp.Body.Close()
lastStatus = status
if status == http.StatusTooManyRequests || (status >= 500 && status <= 599) {
// 429 / 5xx:指数退避 + 抖动后重试;到上限即跳出(走 fallback,body 已读)。
if attempt < maxRetries {
d := backoffDelay(attempt, initialDelay, maxDelay, rng)
log.Printf("[distill] callLLM5D HTTP %d (attempt %d/%d) → backoff %v | body=%q",
status, attempt+1, maxRetries, d, truncate(string(respBody), 120))
time.Sleep(d)
continue
}
break // 超限:保留最后一次 body,下方按 429/5xx 上抛
}
break // 2xx 成功
}
// 退出循环:若最后仍是 429/5xx(重试上限耗尽)→ 上抛 error,让 distillOne 走 fallback。
if lastStatus == http.StatusTooManyRequests || (lastStatus >= 500 && lastStatus <= 599) {
return LLMResponse{}, fmt.Errorf("callLLM5D: HTTP %d after retries | body=%q",
lastStatus, truncate(string(respBody), 200))
}
var result struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ReasoningContent string `json:"reasoning_content"`
// OpenAI 系 reasoning 模型(gpt-oss 等)用 "reasoning" 字段,不是 "reasoning_content"
Reasoning string `json:"reasoning"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &result); err != nil {
return LLMResponse{}, err
}
if len(result.Choices) == 0 {
return LLMResponse{}, fmt.Errorf("no choices in LLM response")
}
var llmResp LLMResponse
llmContent := result.Choices[0].Message.Content
if llmContent == "" {
llmContent = result.Choices[0].Message.ReasoningContent
}
if llmContent == "" {
llmContent = result.Choices[0].Message.Reasoning
}
// 剥离 markdown code fence(minimax 等模型习惯用 ```json 包裹)
llmContent = strings.TrimSpace(llmContent)
llmContent = strings.TrimPrefix(llmContent, "```json")
llmContent = strings.TrimPrefix(llmContent, "```")
llmContent = strings.TrimSuffix(llmContent, "```")
llmContent = strings.TrimSpace(llmContent)
// 健壮剥离:找第一个 { 和最后一个 } 截取(模型可能在 JSON 后加 markdown/注释)
if idx := strings.Index(llmContent, "{"); idx > 0 {
llmContent = llmContent[idx:]
}
if idx := strings.LastIndex(llmContent, "}"); idx >= 0 && idx < len(llmContent)-1 {
llmContent = llmContent[:idx+1]
}
llmContent = strings.TrimSpace(llmContent)
if err := json.Unmarshal([]byte(llmContent), &llmResp); err != nil {
// AC3 (t_9b2c7943): 截断 JSON 容错。max_tokens 截断会把 facts 数组切到一半 →
// 尾部 "}" 缺失 → 非法 JSON。不再直接丢整条,先救回"最后完整对象"再解析。
recovered, ok := recoverTruncatedJSON(llmContent)
if ok {
log.Printf("[distill] LLM JSON truncated, recovered last complete object (%d→%d bytes)",
len(llmContent), len(recovered))
llmContent = recovered
} else {
log.Printf("[distill] LLM JSON parse error: %v | content=%q", err, truncate(llmContent, 200))
return LLMResponse{}, fmt.Errorf("parse score: %w", err)
}
}
if err := json.Unmarshal([]byte(llmContent), &llmResp); err != nil {
// 救回后仍解析失败(极端情况):记录但不静默——返回 error 让上层走
// fallbackSingle(保留启发式 fact),而不是把整条 episode 当空结果丢掉。
log.Printf("[distill] LLM JSON parse error after recovery: %v | content=%q",
err, truncate(llmContent, 200))
return LLMResponse{}, fmt.Errorf("parse score: %w", err)
}
// 记录实体和事实数量
if len(llmResp.Entities) > 0 {
log.Printf("[distill] LLM entities for content: %d entities", len(llmResp.Entities))
}
if len(llmResp.Facts) > 0 {
log.Printf("[distill] LLM facts for content: %d facts", len(llmResp.Facts))
}
return llmResp, nil
}
// AC1 辅助:指数退避 + 抖动。
// 基础为指数(initialDelay << attempt),封顶 maxDelay;叠加 ±25% 抖动避免惊群。
// 用 math/rand(Go 1.20+ 全局自动随机化,无需手动 seed)。
func newRand() *rand.Rand { return rand.New(rand.NewSource(time.Now().UnixNano())) }
// backoffDelay 返回第 attempt 次(0 基)重试前应等待的时长:
// attempt 0 → ~300ms,attempt 1 → ~600ms(指数翻倍),封顶 maxDelay,再叠 ±25% 抖动。
func backoffDelay(attempt int, initial, max time.Duration, r *rand.Rand) time.Duration {
d := initial << attempt
if d > max {
d = max
}
// 抖动:在 [d*0.75, d*1.25] 内随机,避免并发请求同时醒来再次撞 429。
jitterFactor := 0.75 + 0.5*r.Float64()
d = time.Duration(float64(d) * jitterFactor)
if d < initial {
d = initial
}
return d
}
// recoverTruncatedJSON 把被 max_tokens 截断的 JSON 救回成「最后一个完整对象」。
//
// 场景:LLM 输出 {"facts":["a","b","c 中途被 max_tokens 截断,尾部 } 缺失(甚至 [ 也缺失)
// → 直接 Unmarshal 报错。本函数从外向内逐步补齐,任一成功即返回。
//
// 策略:
// ① 先找「最后一个配平的最外层 }」:若截断发生在外层对象之外(尾部多了一段被切的
// 额外内容),截到那个 } 丢弃尾部即可,json.Valid 通过 → 直接返回。
// ② 否则(截在外层对象内部):用栈记录所有未闭合的 [ 和 {,从尾部逐个补 ] 和 }
// (栈顶先补,保证嵌套顺序正确);若截在字符串字面量中间,先补闭合引号。
// 补齐后 json.Valid 通过 → 返回。
// ③ 救不出对象骨架(连最外层 { 都没了 / 纯文本)→ 返回 ("", false),上层走 fallback。
//
// 注意:补齐后得到的可能是「截断前已完整的那些条目」,而非完整 facts——这正是容错目标
// (保留能救的部分,而不是把整条 episode 当空结果丢弃)。
func recoverTruncatedJSON(s string) (string, bool) {
s = strings.TrimSpace(s)
if s == "" {
return "", false
}
// 扫描一遍:跟踪字符串状态、栈([ { 的开闭)。同时记录「深度归 0 的最后一个 }」位置。
// 栈元素:'[' 或 '{'。
var stack []byte
inString := false
escape := false
depthZeroAt := -1 // 最外层对象({ 深度归 0)的最后结束位置
for i := 0; i < len(s); i++ {
c := s[i]
if escape {
escape = false
continue
}
switch c {
case '\\':
if inString {
escape = true
}
case '"':
inString = !inString
case '{':
if !inString {
stack = append(stack, '{')
}
case '[':
if !inString {
stack = append(stack, '[')
}
case '}':
if !inString {
if len(stack) > 0 && stack[len(stack)-1] == '{' {
stack = stack[:len(stack)-1]
}
if len(stack) == 0 {
depthZeroAt = i // 记最外层对象终点(多次则取最后一次)
}
}
case ']':
if !inString {
if len(stack) > 0 && stack[len(stack)-1] == '[' {
stack = stack[:len(stack)-1]
}
}
}
}
// ① 有完整外层对象(深度曾归 0):截到最后一个配平 } 即可,丢弃尾部半截内容。
if depthZeroAt >= 0 {
candidate := s[:depthZeroAt+1]
if json.Valid([]byte(candidate)) {
return candidate, true
}
}
// ② 截在对象内部:补齐未闭合的 [ { 与未闭合的字符串。
// 从栈尾(最内层)到栈底(最外层)逐个补对应的闭合符。
var patch strings.Builder
// 若截在字符串字面量中间(最后一个 " 之后未闭合),先补一个引号闭合它。
if inString {
patch.WriteByte('"')
}
// 栈尾 → 栈底(最内层先补)
for i := len(stack) - 1; i >= 0; i-- {
switch stack[i] {
case '{':
patch.WriteByte('}')
case '[':
patch.WriteByte(']')
}
}
candidate := s + patch.String()
if json.Valid([]byte(candidate)) {
return candidate, true
}
// 兜底:连最外层 { 都没了(骨架残缺)或补齐后仍非法 → 救不出,返回失败。
return "", false
}
// extractFacts 从内容中提取事实和实体(关键词 + 命名实体启发式)
func (e *Engine) extractFacts(content string) ([]string, []Entity) {
var facts []string
var entities []Entity
if len(content) > 20 {
facts = append(facts, truncate(content, 200))
}
// 启发式实体提取:提取大写单词、数字组合、中文命名实体
words := strings.Fields(content)
seen := make(map[string]bool)
for _, w := range words {
w = strings.Trim(w, ",.;:!?,。;:!?、\"'()()[]【】")
if len(w) < 2 {
continue
}
// 大写字母开头(英文命名实体:Hermes, ComfyUI, Redis 等)
runes := []rune(w)
if len(runes) >= 2 && runes[0] >= 'A' && runes[0] <= 'Z' {
normalized := strings.ToLower(w)
if !seen[normalized] && !isStopWord(normalized) {
seen[normalized] = true
entities = append(entities, Entity{
Name: w, Type: "entity", Properties: []string{"extracted"},
})
}
}
// 中文实体(2-20 个纯中文字符,不含标点)
cleanChinese := stripNonChinese(w)
if len(cleanChinese) >= 2 && len(cleanChinese) <= 20 {
if !seen[cleanChinese] {
seen[cleanChinese] = true
isTech := containsAny(cleanChinese, []string{"端口", "配置", "系统", "内存", "显卡", "服务", "记忆", "织忆", "飞书", "版本", "模型", "工具", "项目", "安装", "部署", "目录", "路径", "开发", "语言"})
etype := "entity"
if isTech {
etype = "fact"
}
entities = append(entities, Entity{
Name: cleanChinese, Type: etype, Properties: []string{"extracted"},
})
}
}
// 数字/字母组合或纯数字(如 3050, 4GB, 8188, 7821)
if isTechToken(w) || isAllDigits(w) {
if !seen[w] {
seen[w] = true
entities = append(entities, Entity{
Name: w, Type: "entity", Properties: []string{"technical"},
})
}
}
}
return facts, entities
}
// isChineseSequence 判断是否为连续的中文字符串(长度在 minLen 到 maxLen 之间)
func isChineseSequence(s string, minLen, maxLen int) bool {
runes := []rune(s)
if len(runes) < minLen || len(runes) > maxLen {
return false
}
for _, r := range runes {
if r < 0x4E00 || r > 0x9FFF {
return false
}
}
return true
}
// isTechToken 判断是否为技术标记(包含数字+字母组合)
func isTechToken(s string) bool {
hasDigit := false
hasLetter := false
for _, r := range s {
if r >= '0' && r <= '9' {
hasDigit = true
}
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
hasLetter = true
}
}
return hasDigit && hasLetter
}
// containsAny 判断字符串是否包含任意一个子串
func containsAny(s string, subs []string) bool {
for _, sub := range subs {
if strings.Contains(s, sub) {
return true
}
}
return false
}
// isStopWord 判断是否为停用词
func isStopWord(w string) bool {
stops := map[string]bool{
"the": true, "a": true, "an": true, "is": true, "are": true,
"was": true, "were": true, "be": true, "been": true, "being": true,
"have": true, "has": true, "had": true, "do": true, "does": true,
"did": true, "will": true, "would": true, "could": true, "should": true,
"may": true, "might": true, "can": true, "shall": true,
"this": true, "that": true, "these": true, "those": true,
"it": true, "its": true, "they": true, "them": true, "their": true,
"we": true, "our": true, "you": true, "your": true, "he": true, "she": true,
"his": true, "her": true, "and": true, "or": true, "but": true,
"not": true, "no": true, "if": true, "then": true, "else": true,
"for": true, "with": true, "as": true, "at": true, "by": true,
"from": true, "in": true, "of": true, "on": true, "to": true, "up": true,
}
return stops[w]
}
// stripNonChinese 只保留中文字符
func stripNonChinese(s string) string {
var buf []rune
for _, r := range s {
if r >= 0x4E00 && r <= 0x9FFF {
buf = append(buf, r)
}
}
return string(buf)
}
// isAllDigits 判断是否为纯数字
func isAllDigits(s string) bool {
if len(s) == 0 {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
// checkDailyLimit 每日限额检查
func (e *Engine) checkDailyLimit() {
now := time.Now()
if now.Day() != e.dailyReset.Day() || now.Month() != e.dailyReset.Month() || now.Year() != e.dailyReset.Year() {
e.dailyUsed = 0
// Reset to start of day in the same location as e.dailyReset
loc := e.dailyReset.Location()
if loc == nil {
loc = time.UTC
}
e.dailyReset = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
}
}
// emitResult 发送蒸馏结果(回调)
func (e *Engine) emitResult(input DistillInput, result DistillResult) {
if len(result.Facts) == 0 {
return
}
// 由注册的回调处理
if OnDistillComplete != nil {
OnDistillComplete(input, result)
}
// Phase F: 蒸馏完成后更新队列深度和冲突计数
metrics.DistillQueueDepth.Set(float64(e.QueueLen()))
// Phase F: 对低分记忆触发质量监控检查 (score < 0.7 的记忆视为潜在低质量)
if result.Overall > 0 && result.Overall < 0.7 {
feedbackCount := selfoptimize.Dash.UsefulCount + selfoptimize.Dash.NotUsefulCount
if record := selfoptimize.QualityMonitor.Check(input.EpisodeID, result.Overall, feedbackCount); record != nil {
log.Printf("[quality] distill low-score flagged: episode=%s score=%.2f status=%s",
input.EpisodeID, result.Overall, record.Status)
}
}
}
// emitResults 批量发送
func (e *Engine) emitResults(results map[DistillInput]DistillResult) {
for input, result := range results {
e.emitResult(input, result)
}
}
// OnDistillComplete 全局蒸馏完成回调
var OnDistillComplete func(DistillInput, DistillResult)
// ─── 辅助 ────────────────────────────────────────────────
func truncate(s string, maxLen int) string {
runes := []rune(s)
if len(runes) <= maxLen {
return s
}
return string(runes[:maxLen]) + "..."
}
// fallbackSingle 降级蒸馏(无 LLM)
func fallbackSingle(input DistillInput) DistillResult {
var facts []string
if len(input.Content) > 20 {
facts = append(facts, truncate(input.Content, 100))
}
// 质量门槛同样作用于 fallback 路径(t_cc07ef4b)
facts = FilterQualityFacts(facts)
return DistillResult{Facts: facts}
}
// fallbackDistill 批量降级蒸馏
func fallbackDistill(inputs []DistillInput) map[DistillInput]DistillResult {
results := make(map[DistillInput]DistillResult)
for _, input := range inputs {
results[input] = fallbackSingle(input)
}
return results
}
// ─── 端点导出方法(G8-G9 配套)───────────────────────────────
// QueueLen 返回当前队列长度
func (e *Engine) QueueLen() int {
e.mu.Lock()
defer e.mu.Unlock()
return len(e.queue)
}
// QueueItems 返回队列内容(摘要)
func (e *Engine) QueueItems() []map[string]string {
e.mu.Lock()
defer e.mu.Unlock()
items := make([]map[string]string, len(e.queue))
for i, q := range e.queue {
content := q.Content
if len(content) > 80 {
content = content[:80] + "..."
}
items[i] = map[string]string{
"episode_id": q.EpisodeID,
"content": content,
"category": string(q.Category),
}
}
return items
}
// GetStatus 返回引擎运行时状态
func (e *Engine) GetStatus() map[string]interface{} {
e.mu.Lock()
defer e.mu.Unlock()
return map[string]interface{}{
"queue_len": len(e.queue),
"batch_size": e.batchSize,
"last_distill": e.lastDistill.Format(time.RFC3339),
"daily_used": e.dailyUsed,
"daily_limit": e.dailyLimit,
"daily_remaining": e.dailyLimit - e.dailyUsed,
}
}
// GetQuota 返回配额(基于 Engine 自身追踪)
func (e *Engine) GetQuota() map[string]interface{} {
e.mu.Lock()
used := e.dailyUsed
limit := e.dailyLimit
e.mu.Unlock()
remain := limit - used
if remain < 0 {
remain = 0
}
pct := float64(used) / float64(limit) * 100
if limit == 0 {
pct = 0
}
status := "normal"
if used >= limit {
status = "exceeded"
} else if pct >= 80 {
status = "near"
}
return map[string]interface{}{
"remaining": remain,
"used": used,
"limit": limit,
"percent": pct,
"near_limit": pct >= 80,
"status": status,
}
}