Files
memoryweave/go/internal/api/routes/tuning.go
T
xiaowei 2a350cf781 fix(distill): max_tokens 800→1200 — Agnes推理token预算不足
Agnes 2.0-flash是推理模型,推理token占大量预算。
800仍不够→JSON截断(parse error: unexpected end of JSON input)。
1200确保推理+正文都够用。
2026-08-20 01:13:06 +08:00

182 lines
5.6 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 — 自调参闭环(Auto-tuning)
package routes
import (
"net/http"
"sync"
"time"
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
)
// TuningConfig 可自动调优的参数
type TuningConfig struct {
mu sync.RWMutex
Diversity float64 `json:"diversity"` // MMR diversity 参数 (0-1)
DecayRate float64 `json:"decay_rate"` // 遗忘衰减率
GapThreshold int `json:"gap_threshold"` // 缺口感测阈值 (miss 次数)
DistillInterval int `json:"distill_interval"` // 蒸馏间隔 (分钟)
ConsolidateAfter int `json:"consolidate_after"` // N 条蒸馏后触发整合
// 历史调参记录
history []TuningEvent
}
type TuningEvent struct {
Parameter string `json:"parameter"`
OldValue float64 `json:"old_value"`
NewValue float64 `json:"new_value"`
Reason string `json:"reason"`
Timestamp time.Time `json:"timestamp"`
}
var Tuner = &TuningConfig{
Diversity: 0.5,
DecayRate: 0.015,
GapThreshold: 3,
DistillInterval: 5,
ConsolidateAfter: 50,
}
// AutoTune 基于仪表盘指标自动调参
func (tc *TuningConfig) AutoTune(metrics map[string]float64) []TuningEvent {
tc.mu.Lock()
defer tc.mu.Unlock()
var events []TuningEvent
// 1. 召回命中率 < 0.5 → 提高 diversity(扩大搜索范围)
if hitRate, ok := metrics["recall_hit_rate"]; ok && hitRate < 0.5 {
newDiversity := tc.Diversity + 0.1
if newDiversity > 1.0 {
newDiversity = 1.0
}
events = append(events, recordTuning(tc, "diversity", tc.Diversity, newDiversity, "recall_hit_rate < 0.5"))
tc.Diversity = newDiversity
}
// 2. 召回有用率 > 0.9 → 降低 diversity(更精准)
if usefulRate, ok := metrics["recall_usefulness_rate"]; ok && usefulRate > 0.9 {
newDiversity := tc.Diversity - 0.05
if newDiversity < 0.1 {
newDiversity = 0.1
}
events = append(events, recordTuning(tc, "diversity", tc.Diversity, newDiversity, "recall_usefulness_rate > 0.9"))
tc.Diversity = newDiversity
}
// 3. 废弃率 > 5/day → 提高衰减率(加快清理)
if deprecated, ok := metrics["deprecated_per_day"]; ok && deprecated > 5 {
newDecay := tc.DecayRate * 1.2
if newDecay > 0.05 {
newDecay = 0.05
}
events = append(events, recordTuning(tc, "decay_rate", tc.DecayRate, newDecay, "deprecated_per_day > 5"))
tc.DecayRate = newDecay
}
// 4. 缺口闭环率 < 0.5 → 降低 gap 阈值
if gapRate, ok := metrics["gap_closure_rate"]; ok && gapRate < 0.5 {
newThreshold := tc.GapThreshold - 1
if newThreshold < 2 {
newThreshold = 2
}
events = append(events, recordTuningInt(tc, "gap_threshold", tc.GapThreshold, newThreshold, "gap_closure_rate < 0.5"))
tc.GapThreshold = newThreshold
}
// 5. 蒸馏损失 > 0.3 → 更频繁蒸馏
if loss, ok := metrics["avg_distill_loss"]; ok && loss > 0.3 {
newInterval := tc.DistillInterval - 1
if newInterval < 1 {
newInterval = 1
}
events = append(events, recordTuningInt(tc, "distill_interval", tc.DistillInterval, newInterval, "avg_distill_loss > 0.3"))
tc.DistillInterval = newInterval
}
tc.history = append(tc.history, events...)
return events
}
func recordTuning(tc *TuningConfig, param string, oldVal, newVal float64, reason string) TuningEvent {
return TuningEvent{
Parameter: param,
OldValue: oldVal,
NewValue: newVal,
Reason: reason,
Timestamp: time.Now(),
}
}
func recordTuningInt(tc *TuningConfig, param string, oldVal, newVal int, reason string) TuningEvent {
return TuningEvent{
Parameter: param,
OldValue: float64(oldVal),
NewValue: float64(newVal),
Reason: reason,
Timestamp: time.Now(),
}
}
// ─── API ──────────────────────────────────────────────────
// GET /api/v1/tuning/status
func (tc *TuningConfig) StatusHandler(w http.ResponseWriter, r *http.Request) {
tc.mu.RLock()
defer tc.mu.RUnlock()
respond(w, 200, map[string]interface{}{
"config": map[string]interface{}{
"diversity": tc.Diversity,
"decay_rate": tc.DecayRate,
"gap_threshold": tc.GapThreshold,
"distill_interval": tc.DistillInterval,
"consolidate_after": tc.ConsolidateAfter,
},
"history": tc.history,
})
}
// POST /api/v1/tuning/run — 手动触发一次自动调参
func (tc *TuningConfig) RunHandler(w http.ResponseWriter, r *http.Request) {
metrics := selfoptimize.Dash.Metrics()
events := tc.AutoTune(metrics)
if len(events) == 0 {
respond(w, 200, map[string]string{"status": "no_changes_needed"})
} else {
respond(w, 200, map[string]interface{}{
"status": "tuned",
"events": events,
"count": len(events),
})
}
}
// POST /api/v1/tuning/analytics — 运行因果分析
func (tc *TuningConfig) AnalyticsHandler(w http.ResponseWriter, r *http.Request) {
// 基于指标间的关系给出建议
m := selfoptimize.Dash.Metrics()
suggestions := []string{}
if m["recall_hit_rate"] < 0.5 && m["avg_distill_loss"] > 0.3 {
suggestions = append(suggestions, "蒸馏质量低导致召回率低 — 建议检查 Embedding 模型")
}
if m["deprecated_per_day"] > 10 {
suggestions = append(suggestions, "废弃率过高 — 正在流失大量记忆,检查冲突检测阈值")
}
if m["gap_closure_rate"] < 0.3 {
suggestions = append(suggestions, "缺口闭环率过低 — Agent 未回应缺口学习请求")
}
if m["auto_resolve_rate"] < 0.5 {
suggestions = append(suggestions, "自动裁决率低 — 规则覆盖不全,考虑扩展策略")
}
respond(w, 200, map[string]interface{}{
"metrics": m,
"suggestions": suggestions,
})
}