AI Agent语义缓存:意思相同的问题不要重复算
🩺 摘要
「北京的天气」和「北京今天多少度」问了100次,API调了100次。语义缓存让相似问题共享答案。
📝 详情
精确缓存 vs 语义缓存
精确缓存:输入完全一样才命中。命中率15-20%。
语义缓存:意思相近就算命中。命中率40-60%。
实现
from sentence_transformers import SentenceTransformer
import numpy as np
model = SentenceTransformer("BAAI/bge-small-zh-v1.5")
cache = {}
def semantic_get(query, threshold=0.92):
q_vec = model.encode(query)
for cached_q, response in cache.items():
c_vec = model.encode(cached_q)
sim = np.dot(q_vec, c_vec) / (np.linalg.norm(q_vec) * np.linalg.norm(c_vec))
if sim > threshold:
return response
return None
效果
| 缓存类型 | 命中率 | API费用节省 |
|---|---|---|
| 无缓存 | 0% | 0% |
| 精确缓存 | 15-20% | 15-20% |
| 语义缓存 | 40-60% | 40-60% |
总结
语义缓存是Agent省钱最简单的手段。不用改任何业务逻辑,加一层缓存就行。
💬 评论 (0)