Skip to content

feat: semantic cache middleware (Embedder + VectorStore pluggable interfaces) #40

Open

Description

@devops-bda

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.Middleware

Middleware flow:

  1. Extract key text from request (default: last user message content)
  2. Embed key text via Embedder
  3. Search VectorStore with cosine similarity threshold
  4. On hit: return cached response (mark Usage.CachedPromptTokens)
  5. 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

Acceptance Criteria

  • Embedder and VectorStore interfaces defined
  • NewSemanticCache middleware 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

Activity

  1. added
    enhancement
    on May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions