fuzhengwei / fuzhengwei/WaLiAPI
语义缓存:exact + semantic 两层响应缓存(默认关闭,三层风险收敛)
- Dominant language
- Rust
- Stars
- 128
- Forks
- 39
- Avg merge
- 15h 25m
- Merged PRs (30d)
- 44
Description
### 现状
代理路径无「请求 → 规范化 → 查相似 → 命中短路」环节,重复语义的请求每次全价过模型。上游 prompt cache 统计(迁移 026/029 的 cached_tokens)是**上游前缀缓存命中统计**,与本条的网关侧响应缓存互补。可复用设施已备:渠道做 embedding 的路径(KB embedder)、SQLite 存向量模式。
### 方案
**两层缓存**:
- **exact**:messages 规范化(提取 (role, 纯文本) 序列、合并连续空白;多段内容全为 text 型才可缓存)SHA-256 → 键含 model + 温度档(≤0.3 同档)+ max_tokens 档——参数档位不同不共享命中;O(1)。
- **semantic**:请求 embedding(复用渠道嵌入路径)与缓存条目 embedding **暴力余弦** ≥ 阈值(默认 0.95 保守)命中;缓存条目量级 ≪ KB chunk,暴力扫可接受。
**三层风险收敛**:① 默认关闭(`cache.semantic_enabled`,关闭时拦截/写入/清理全旁路);② 可缓存判定(无 tools/tool_choice、temperature ≤ 0.3、安全审计无命中、消息全纯文本——**带 tools 永不入缓存也永不命中**);③ 保守阈值。
**接线**:拦截在 chat completions 的 Key 鉴权与安全门之后、路由候选之前;命中非流式返回 JSON、流式按标准增量分块回放 SSE(既有客户端零改造),响应头 `X-Cache: hit`;命中照常写请求日志(记账口径不变)。写入在响应完整落账后异步 best-effort;TTL 默认 24h + 后台清理 + 手动清空命令(按模型/全部);设置页缓存区。
### 设计修正(如实声明)
1. 原设想「渠道级覆盖」——拦截点在路由候选解析**之前**,此时渠道未知,改为**模型粒度**(cache_key 含 model);
2. 本 PR 只拦截 chat completions(主协议);responses/messages 协议与流式响应自身的渐进写入列为后续(流式命中回放已支持);
3. 不做自动语义失效(复杂度高)——TTL 自然过期 + 手动清空兜底。
### 测试
规范化/判定/键稳定性/余弦/编解码往返纯函数;exact 命中-miss-TTL 过期-清理;清空按模型/全清;回放体与 SSE 帧形态;router 端到端(命中短路——测试库无渠道,若拦截失效请求必 503,命中 200 即证明未过上游——+ X-Cache 头 + 记账行;关闭时 503 直通)。
### 开放点
1. 阈值 0.95 / TTL 24h 默认值是否合适?
2. 是否需要 HNSW 复用(当前暴力余弦在缓存量级下延迟可接受)?
3. 自动语义失效(答案因上游更新而过期)是否值得做?
---
对应分支:`feat/capability-c02-semantic-cache`(迁移 035)。
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the chat completions authentication, safety gate, and router path, then inspect migration 035 and the existing embedding and SQLite facilities. Run the proposed normalization, eligibility, key, cosine, codec, TTL, cleanup, replay/SSE, and router end-to-end tests. Done means disabled passthrough still works, enabled exact and semantic hits return 200 with X-Cache, logs are recorded, and misses retain normal routing.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react, rust, sqlite
- Domain
- api, backend-api-design, databases, frontend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100