Repository navigation
Open
Labels
enhancementNew feature or request
Description
Wave 4 — Large Effort, High Long-Term Impact
Problem
Exact-match result caching (#35) handles repeated identical requests. Semantic caching handles similar requests — same intent, different wording — which is the majority of real-world LLM traffic. At 0.95 cosine similarity threshold, semantic caching can eliminate an additional ~15% of API calls (on top of the ~10% from result caching).
Reference: docs/LLM-COST-OPTIMIZATION.md Layer 2 — Semantic Caching.
Proposed Design
New file middleware/semanticcache.go:
type Embedder interface {
Embed(ctx context.Context, text string) ([]float32, error)
}
type VectorStore interface {
Search(ctx context.Context, vec []float32, threshold float64) (*llmrouter.Response, bool)
Store(ctx context.Context, vec []float32, resp *llmrouter.Response, ttl time.Duration) error
}
type SemanticCacheOptions struct {
SimilarityThreshold float64 // default 0.95
TTL time.Duration // default 1h
KeyText func(*llmrouter.Request) string // default: last user message
}
func NewSemanticCache(embedder Embedder, store VectorStore, opts SemanticCacheOptions) llmrouter.MiddlewareMiddleware flow:
- Extract key text from request (default: last user message content)
- Embed key text via
Embedder - Search
VectorStorewith cosine similarity threshold - On hit: return cached response (mark
Usage.CachedPromptTokens) - On miss: call inner provider, store embedding + response
The library ships no concrete implementations of Embedder or VectorStore — callers plug in:
- Embedder: OpenAI
text-embedding-3-small, local model, etc. - VectorStore: pgvector, Qdrant, Redis VSS, NATS JetStream KV, in-memory flat scan
Dependencies on other issues
- Builds on result cache patterns from feat: result cache middleware (exact-match SHA-256, pluggable TTL store) #35
Usage.CachedPromptTokenscost signal established in feat: USD cost calculation per request (price table + Response.Cost field) #34
Acceptance Criteria
-
EmbedderandVectorStoreinterfaces defined -
NewSemanticCachemiddleware implemented - Similarity threshold and TTL configurable
- Streaming requests bypass semantic cache (non-deterministic responses)
- Unit tests with mock embedder and vector store
- No vector DB or embedding model imported as a library dependency
Metadata
Metadata
Assignees
Labels
enhancementNew feature or request
Activity