内存语义缓存 (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
配置选项
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
enabled | boolean | false | 全局启用/禁用语义缓存 |
backend_type | string | "memory" | 缓存后端类型(必须为 "memory") |
similarity_threshold | float | 0.8 | 全局缓存命中的最小相似度 (0.0-1.0) |
max_entries | integer | 1000 | 缓存条目的最大数量 |
ttl_seconds | integer | 3600 | 缓存条目的生存时间(秒,0 = 永不过期) |
eviction_policy | string | "fifo" | 驱逐策略:"fifo", "lru", "lfu" |
use_hnsw | boolean | false | 启用 HNSW 索引进行相似度搜索 |
hnsw_m | integer | 16 | HNSW M 参数(每个节点的双向链路数) |
hnsw_ef_construction | integer | 200 | HNSW efConstruction 参数(构建质量) |
HNSW 参数
内存缓存支持 HNSW (Hierarchical Navigable Small World) 索引,可显著加快相似度搜索速度,尤其在缓存规模较大时效果显著。