Skip to content

[AI优化] 工具级检索结果缓存 - 减少重复数据库查询 #92

@hrygo

Description

@hrygo

问题描述

日程查询 (ScheduleQueryTool) 和笔记搜索 (MemoSearchTool) 的结果没有缓存:

  • 相同时间范围的日程查询每次都会访问数据库
  • 相同关键词的笔记搜索每次都会计算向量相似度
  • 短时间内用户多次问类似问题时,重复执行相同查询

相关代码:

  • ai/agent/tools/scheduler.go
  • ai/agent/tools/memo_search.go

建议方案

添加工具级别的结果缓存(L3 Cache):

type ToolResultCache struct {
    cache *lru.Cache
    mu    sync.RWMutex
}

type CachedResult struct {
    Result    string
    CachedAt  time.Time
    TTL       time.Duration
}

type CacheKey struct {
    ToolName  string
    UserID    int32
    InputHash string
}

// 针对不同工具的 TTL 策略
var toolTTLs = map[string]time.Duration{
    "schedule_query": 30 * time.Second,  // 日程变化较少
    "memo_search":    5 * time.Minute,   // 笔记搜索结果稳定
    "find_free_time": 1 * time.Minute,   // 空闲时间需要较新
    "schedule_add":   0,                 // 不缓存写操作
    "schedule_update": 0,                // 不缓存写操作
}

缓存失效策略

// 当日程发生变更时,失效相关缓存
func (c *ToolResultCache) InvalidateScheduleCache(userID int32) {
    c.mu.Lock()
    defer c.mu.Unlock()
    
    c.cache.Remove(CacheKey{ToolName: "schedule_query", UserID: userID, ...})
    c.cache.Remove(CacheKey{ToolName: "find_free_time", UserID: userID, ...})
}

文件变更

  • ai/agent/tools/cache.go - 新增工具结果缓存实现
  • ai/agent/tools/cache_test.go - 单元测试
  • ai/agent/tools/scheduler.go - 集成缓存
  • ai/agent/tools/memo_search.go - 集成缓存

验收标准

  • 配置化的 TTL 策略
  • 缓存失效机制 (日程/笔记变更时失效)
  • 日志记录命中/未命中
  • 支持手动清除缓存
  • 单元测试覆盖率 >80%

预估工时

1-2 天

相关 Issue

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions