M5MediumPart M · LLM 评测与 Agent/RAG 算子

语义缓存拦截与大小模型置信度级联路由

⚡闪卡盲测➔

结合余弦语义缓存拦截与小模型 Softmax 置信度阈值判断,仅对低置信疑难请求升级调用高成本大模型。

⏱️ 时间复杂度: O(M_cache * D + |C|)
💾 空间复杂度: O(M_cache * D)
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def route_query_with_cache_and_confidence(
query_emb: np.ndarray,
cache_embs: np.ndarray,
small_logits: np.ndarray,
cache_threshold: float = 0.92,
conf_threshold: float = 0.80,
) -> tuple:
"""
Two-stage LLM FinOps router:
1) Semantic cache lookup via normalized cosine similarity;
2) Fast small-model calibrated confidence check; escalate to frontier model only on low confidence.
"""
# Stage 1: L2-normalized semantic cache similarity
if len(cache_embs) > 0:
q_norm =
c_norms = np.maximum(np.linalg.norm(cache_embs, axis=1, keepdims=True), 1e-12)
sims = (cache_embs / c_norms) @ q_norm
best_idx = int(np.argmax(sims))
if float(sims[best_idx]) >= cache_threshold:
return "CACHE_HIT", float(sims[best_idx])
# Stage 2: Stable softmax confidence check on small model
shifted = small_logits - np.max(small_logits)
probs = np.exp(shifted) / np.sum(np.exp(shifted))
top_conf =
if top_conf >= conf_threshold:
return "SMALL_MODEL", top_conf
return "FRONTIER_MODEL", top_conf
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: 语义缓存最危险的生产事故是什么?如何避免相似但核心参数不同的查询误命中?
下一题: 队列留存矩阵与 SQL->Python 事件流归因 →
💡

实战一句话记忆口诀

先过语义缓存隔离租户,小模型高置信直出,拿不准再升级旗舰模型

📐 核心数学公式与机理推导

Route(x)={Cachemax⁡ccos⁡(ex,ec)≥τcacheSmallmax⁡yPsmall(y∣x)≥τconfFrontierotherwise\text{Route}(x) = \begin{cases} \text{Cache} & \max_c \cos(e_x, e_c) \ge \tau_{\text{cache}} \\ \text{Small} & \max_y P_{\text{small}}(y \mid x) \ge \tau_{\text{conf}} \\ \text{Frontier} & \text{otherwise} \end{cases}
### 分层漏斗拦截(Semantic Cache → Small → Frontier)
若把 100% 线上流量直接打向高价闭源大模型,简单常见问题(FAQ/意图识别)会吞噬大量预算:
1. L1 语义缓存:将 Query Embedding 归一化后与历史问答索引求余弦,高于高精度阈值(如 0.92~0.96 且同一租户与系统提示隔离)直接毫秒返回;
2. L2 级联路由(FrugalGPT 思路):先由低成本小模型推理;若其验证置信度 / Logprob Margin 满足 top_conf >= tau_conf 即采纳,仅对不确定样本升级(Escalate)给 Frontier 模型。

🔄 张量维度与形状流转说明

query_emb vs cache_embs -> cos >= cache_threshold ? CACHE_HIT : softmax(small_logits) >= conf_threshold ? SMALL : FRONTIER

🛡️ 数值稳定性自检与边界要点

  • 语义缓存的 Key 必须同时绑定 tenant_id 与工具权限状态,绝不能把租户 A 的私有答案跨租户命中返回给租户 B
  • 小模型的未校准 Raw Logits 容易“盲目自信”,上线阈值 conf_threshold 需在验证集上配合 Temperature Scaling 校准

💻 完整参考代码实现

import numpy as np

def route_query_with_cache_and_confidence(
    query_emb: np.ndarray,
    cache_embs: np.ndarray,
    small_logits: np.ndarray,
    cache_threshold: float = 0.92,
    conf_threshold: float = 0.80,
) -> tuple:
    """
    Two-stage LLM FinOps router:
    1) Semantic cache lookup via normalized cosine similarity;
    2) Fast small-model calibrated confidence check; escalate to frontier model only on low confidence.
    """
    # Stage 1: L2-normalized semantic cache similarity
    if len(cache_embs) > 0:
        q_norm = query_emb / max(float(np.linalg.norm(query_emb)), 1e-12)
        c_norms = np.maximum(np.linalg.norm(cache_embs, axis=1, keepdims=True), 1e-12)
        sims = (cache_embs / c_norms) @ q_norm
        best_idx = int(np.argmax(sims))
        if float(sims[best_idx]) >= cache_threshold:
            return "CACHE_HIT", float(sims[best_idx])

    # Stage 2: Stable softmax confidence check on small model
    shifted = small_logits - np.max(small_logits)
    probs = np.exp(shifted) / np.sum(np.exp(shifted))
    top_conf = float(np.max(probs))
    if top_conf >= conf_threshold:
        return "SMALL_MODEL", top_conf
    return "FRONTIER_MODEL", top_conf

🧪 本地测试与正确性断言

可直接复制到本地 Python / Jupyter 验证:

import numpy as np
cache = np.array([[1.0, 0.0], [0.0, 1.0]])
# 1. Near-duplicate query hits semantic cache
route1, _ = route_query_with_cache_and_confidence(np.array([0.99, 0.05]), cache, np.array([1.0, 1.0]))
assert route1 == "CACHE_HIT"
# 2. Cache miss + confident small model stays on small model
route2, _ = route_query_with_cache_and_confidence(np.array([0.6, 0.8]), cache, np.array([5.0, 0.0]))
assert route2 == "SMALL_MODEL"
# 3. Cache miss + uncertain small model escalates to frontier
route3, _ = route_query_with_cache_and_confidence(np.array([0.6, 0.8]), cache, np.array([0.2, 0.1]))
assert route3 == "FRONTIER_MODEL"
print("✓ Cascading router & semantic cache assertion passed")

🎯 核心工程追问与标准应答

Q1:语义缓存最危险的生产事故是什么?如何避免相似但核心参数不同的查询误命中?
例如两句结构几乎完全一样但关键数字/实体相反的查询(“2025年退货期限是多少天?” vs “2026年退货期限是多少天?”),向量余弦相似度往往高达 0.96,若直接命中缓存就会张冠李戴。缓解方法:设定极高余弦阈值、增加实体/数字/日期精确抽取匹配二次校验,并把缓存限定在无参数静态 FAQ 路径上。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: Agent 工具循环熔断与幂等调用护栏返回 Part M 与全部 105 题下一题: 队列留存矩阵与 SQL->Python 事件流归因 →