内存语义缓存 (In-Memory Semantic Cache)
内存缓存后端直接在内存中存储语义嵌入和缓存的响应,以实现快速的本地缓存。
概览
内存缓存将所有缓存数据存储在应用程序的内存中,提供低延迟访问,且无需外部依赖。
架构
工作原理
写入路径 (Write Path)
缓存响应时:
- 使用配置的嵌入模型为查询生成嵌入
- 在内存中存储嵌入和响应
- 应用 TTL(如果已配置)
- 如果达到
max_entries限制,驱逐最早/最少使用的条目
读取路径 (Read Path)
搜索缓存的响应时:
- 为传入的查询生 成嵌入
- 在内存缓存中搜索相似的嵌入
- 如果相似度超过阈值,返回缓存的响应(缓存命中)
- 否则,转发到 LLM 并缓存新的响应(缓存未命中)
搜索方法
该缓存支持两种搜索方法:
- 线性搜索:将查询嵌入与所有缓存的嵌入进行对比
- HNSW 索引:使用分层图结构实现更快的近似最近邻搜索
配置
基础配置
# config/config.yaml
semantic_cache:
enabled: true
backend_type: "memory"
similarity_threshold: 0.8 # 全局默认阈值
max_entries: 1000
ttl_seconds: 3600
eviction_policy: "fifo"
带有 HNSW 的配置
semantic_cache:
enabled: true
backend_type: "memory"
similarity_threshold: 0.8
max_entries: 1000
ttl_seconds: 3600
eviction_policy: "fifo"
# 使用 HNSW 索引以实现更快的搜索
use_hnsw: true
hnsw_m: 16
hnsw_ef_construction: 200
类别级配置(新功能)
按类别配置缓存设置,以实现精细控制:
semantic_cache:
enabled: true
backend_type: "memory"
similarity_threshold: 0.8 # 全局默认值
max_entries: 1000
ttl_seconds: 3600
eviction_policy: "fifo"
categories:
- name: health
system_prompt: "你是一位健康专家..."
semantic_cache_enabled: true
semantic_cache_similarity_threshold: 0.95 # 对医疗准确性要求非常严格
model_scores:
- model: your-model
score: 0.5
use_reasoning: false
- name: general_chat
system_prompt: "你是一位乐于助人的助手..."
semantic_cache_similarity_threshold: 0.75 # 放宽以获得更好的命中率
model_scores:
- model: your-model
score: 0.7
use_reasoning: false
- name: troubleshooting
# 无缓存设置 - 使用全局默认值 (0.8)
model_scores:
- model: your-model
score: 0.7
use_reasoning: false