Skip to content

[AI优化] 动态 Token 预算分配 - 按意图类型自适应调整 #93

@hrygo

Description

@hrygo

问题描述

当前 BudgetAllocator 使用固定比例分配 Token 预算:

// ai/context/budget.go
if hasRetrieval {
    budget.ShortTermMemory = int(float64(remaining) * 0.40)
    budget.LongTermMemory = int(float64(remaining) * 0.15)
    budget.Retrieval = int(float64(remaining) * 0.45)
}

这种固定比例不适合所有场景:

  • 查询类 (如 "明天有什么会议") - 应给检索更多空间,减少闲聊历史
  • 创建类 (如 "帮我安排明天开会") - 应给历史上下文更多空间以理解完整需求
  • 闲聊类 (如 "你好呀") - 几乎不需要检索空间

建议方案

实现意图感知的动态预算分配:

type AdaptiveBudgetAllocator struct {
    profiles map[Intent]*BudgetProfile
}

type BudgetProfile struct {
    ShortTermRatio float64
    LongTermRatio  float64
    RetrievalRatio float64
    UserPrefsRatio float64
}

var defaultProfiles = map[Intent]*BudgetProfile{
    IntentQuery:  {0.25, 0.10, 0.55, 0.10}, // 查询: 检索优先
    IntentCreate: {0.50, 0.20, 0.20, 0.10}, // 创建: 上下文优先
    IntentUpdate: {0.45, 0.15, 0.30, 0.10}, // 更新: 平衡
    IntentChat:   {0.60, 0.25, 0.05, 0.10}, // 闲聊: 最小化检索
    IntentDelete: {0.40, 0.10, 0.40, 0.10}, // 删除: 确认上下文
}

func (a *AdaptiveBudgetAllocator) Allocate(total int, intent Intent) *TokenBudget {
    profile := a.profiles[intent]
    if profile == nil {
        profile = a.profiles[IntentChat] // fallback
    }
    
    remaining := total - DefaultSystemPrompt
    return &TokenBudget{
        Total:           total,
        SystemPrompt:    DefaultSystemPrompt,
        ShortTermMemory: int(float64(remaining) * profile.ShortTermRatio),
        LongTermMemory:  int(float64(remaining) * profile.LongTermRatio),
        Retrieval:       int(float64(remaining) * profile.RetrievalRatio),
        UserPrefs:       int(float64(remaining) * profile.UserPrefsRatio),
    }
}

文件变更

  • ai/context/budget.go - 重构为自适应分配
  • ai/context/budget_test.go - 单元测试
  • ai/context/builder_impl.go - 传递 Intent 信息
  • ai/router/interface.go - 确保 Intent 传递到 ContextBuilder

验收标准

  • 支持按 Intent 动态分配
  • Profile 配置化 (支持环境变量/配置文件覆盖)
  • 单元测试覆盖各种 Intent 场景
  • 向后兼容: 未识别 Intent 时使用默认 Profile
  • 日志记录实际分配结果

预估工时

2-3 天

相关 Issue

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions