agentleFS
28672032962867203296/hermes-agent/skills/software-development/semantic-cache/SKILL.md

semantic-cache

Skill0 starsChanged 3 months agoMITView on GitHub

语义缓存:相似查询复用,省 40-60% token。借鉴 GPTCache/Redis 的语义相似匹配 + Claude Code prompt-cache 保留策略

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

Files
SKILL.md

Semantic Cache — 语义缓存

每次相似问题都重新推理 = 浪费 40-60% token。语义缓存让"这个之前查过了"自动复用。

一、原理

不是精确匹配("TTS不工作" 和 "TTS出问题了" 是同一个意思),而是语义相似匹配。

查询 → 提取语义向量(本地embedding或关键词hash)
     ↓
  缓存命中?(相似度 > 0.85)
  ├─ 是 → 直接返回缓存结果(省 100% token)
  └─ 否 → 正常推理 → 结果存入缓存

二、三级缓存

级别匹配方式命中速度节省有效期
L1 精确查询字符串完全相同< 1ms100%1小时
L2 语义关键词Jaccard相似 > 0.7< 10ms100%6小时
L3 弱语义TF-IDF余弦相似 > 0.5< 50ms60%(需验证)24小时

三、适用场景(高命中率)

场景示例预计节省
配置查询"voice配置在哪" → "TTS配置文件路径"80%
错误排查"edge-tts报错" → "TTS播报失败"60%
工具用法"怎么用session_search"90%
环境信息"Python路径" "CUDA版本"95%

四、不适用(不要缓存)

  • 涉及实时状态的查询("现在几点""当前git状态")
  • 需要执行操作的查询("帮我改这个文件")
  • 用户明确说"重新查"
  • 安全/隐私相关查询

五、实现

# D:/Hermes/scripts/semantic_cache.py
import json, hashlib, time
from pathlib import Path

CACHE_DIR = Path("D:/Hermes/cache/semantic")
CACHE_DIR.mkdir(parents=True, exist_ok=True)

def get_cache_key(query, context=""):
    """生成语义缓存键:关键词提取 + hash"""
    # 提取有意义的词(去掉停用词)
    words = [w for w in query.lower().split() 
             if w not in STOP_WORDS and len(w) > 1]
    key = "|".join(sorted(words[:5]))  # 取前5个关键词
    return hashlib.md5(key.encode()).hexdigest()[:12]

def check(query, max_age_hours=6):
    """检查缓存"""
    key = get_cache_key(query)
    cache_file = CACHE_DIR / f"{key}.json"
    if cache_file.exists():
        data = json.loads(cache_file.read_text())
        age = time.time() - data["timestamp"]
        if age < max_age_hours * 3600:
            return data["result"]  # 命中!
    return None  # 未命中

def store(query, result):
    """存入缓存"""
    key = get_cache_key(query)
    cache_file = CACHE_DIR / f"{key}.json"
    cache_file.write_text(json.dumps({
        "query": query[:200],
        "result": result[:5000],
        "timestamp": time.time()
    }))

六、Agent 使用模式

每次回答用户前:
1. cache = check(user_query)
2. if cache:
     answer = cache + " [缓存命中]"
   else:
     answer = think_and_answer(user_query)
     store(user_query, answer)

七、与 context-engine 联动

  • context-engine 的 prompt-cache 保留策略 = API 层面的缓存
  • semantic-cache = 应用层面的缓存
  • 两层叠加 → 总节省 60-80%

八、监控

# 缓存命中率
python D:/Hermes/scripts/semantic_cache.py --stats
# 输出: 命中率 47% | 已省 ~120K token | 节省 ~$0.35

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.