Skip to content

Replace LLM response cache stub with VectorIndexManager integration and real embedding support - #238

Merged
makr-code merged 7 commits into
developfrom
copilot/implement-llm-response-cache
Jan 5, 2026
Merged

makr-code merged 7 commits into
developfrom
copilot/implement-llm-response-cache

Conversation

Copilot AI commented Jan 5, 2026 •

Copy link
Copy Markdown
Contributor

The LLM response cache was using a stub implementation with simple string matching instead of semantic similarity via HNSW indexing.

Changes

  • VectorIndexManager integration: Uses ThemisDB's existing HNSW infrastructure (M=16, efConstruction=200, efSearch=64) with cosine similarity instead of creating duplicate cache layer
  • Pointer exchange pattern: Accepts external RocksDB via Config::db_ptr or creates own instance; enables zero-copy integration with ThemisDB core
  • Real LLM embedding support: Reuses existing EmbeddedLLM::embed() and LlamaWrapper::embed() via pointer exchange (Config::llm_ptr) instead of duplicating embedding generation code
  • Flexible embedding strategy: 3-tier approach with custom function support (Config::embedding_fn), LLM embeddings, and simple feature-based fallback
  • LRU eviction: Automatic cleanup when max_entries reached; maintains sync between vector_index_ and response_store_
  • TTL support: Expired entries removed on access; proper cleanup from both vector index and response store
  • Comprehensive benchmarks: Added bench_llm_response_cache.cpp with 7 benchmark scenarios (put/get, semantic matching, LRU eviction, concurrent access)
  • Complete documentation: Added usage guide in docs/en/llm/LLM_RESPONSE_CACHE_USAGE.md with examples and integration patterns

Implementation

// Constructor initializes VectorIndexManager with optional DB pointer exchange
LLMResponseCache::LLMResponseCache(const std::string& cache_name, const Config& config) {
    RocksDBWrapper* db = config_.db_ptr ?: owned_db_.get();
    vector_index_ = std::make_unique<VectorIndexManager>(*db);
    vector_index_->init(cache_name_, config_.embedding_dim, 
                       VectorIndexManager::Metric::COSINE, 16, 200, 64);
}

// Embedding generation reuses existing LLM infrastructure
std::vector<float> generateEmbedding(const std::string& prompt) const {
    // Priority 1: Custom embedding function
    if (config_.embedding_fn) return config_.embedding_fn(prompt);
    
    // Priority 2: Reuse existing LLM embeddings (NO DUPLICATION!)
    if (config_.llm_ptr) return config_.llm_ptr->embed(prompt);
    
    // Priority 3: Simple fallback only when no LLM available
    return generateSimpleEmbedding(prompt);
}

// Lookup uses HNSW ANN search with configurable similarity threshold
auto [status, results] = vector_index_->searchKnn(query_embedding, 1);
float similarity = 1.0f - results[0].distance;  // cosine distance -> similarity
if (similarity >= config_.similarity_threshold) { /* cache hit */ }

Key Points

  • No code duplication: Reuses existing EmbeddedLLM::embed() and LlamaWrapper::embed() via pointer exchange
  • No duplication of vector index infrastructure: Uses ThemisDB's VectorIndexManager
  • Thread-safe with mutex protection for concurrent access
  • Maintains backward compatibility with existing test suite (test_llm_response_cache.cpp)
  • Both model_id and model_used fields preserved in BaseEntity storage
  • Invalidate operation syncs both vector index and response store
  • Production-ready with flexible embedding strategies

Testing & Benchmarks

  • Unit tests: Existing test_llm_response_cache.cpp (backward compatible)
  • Performance benchmarks: New bench_llm_response_cache.cpp with 7 scenarios:
    • Cache put/get operations
    • Exact and semantic matching
    • LRU eviction performance
    • Concurrent access (1/2/4/8 threads)
    • Mixed workload simulation

Documentation

  • Usage guide: New docs/en/llm/LLM_RESPONSE_CACHE_USAGE.md
    • Basic and advanced usage examples
    • Integration with ThemisDB Core
    • Configuration options
    • Troubleshooting guide
    • Performance metrics

Notes

Production deployments can now use real LLM embeddings by setting config.llm_ptr to an EmbeddedLLM instance, eliminating the need for feature-based embeddings and providing true semantic similarity.

Original prompt

This section details on the original issue you should resolve

<issue_title>02-implement-llm-response-cache.md</issue_title>
<issue_description>---
name: "Implement Real LLM Response Cache"
about: Replace stub implementation with production-ready semantic cache
title: "[LLM] Implement Real LLM Response Cache with Semantic Similarity"
labels: ["enhancement", "llm", "cache", "priority: high"]
assignees: []

Description

The current LLM Response Cache uses a stub implementation with simple string matching instead of semantic similarity. This needs to be replaced with a production-ready implementation using ThemisDB's actual SemanticCache/EmbeddingCache with HNSW indexing.

Current Status

⚠️ STUB IMPLEMENTATION

Location: src/llm/llm_response_cache.cpp

// For now, using in-memory map as stub
// TODO: v1.3.0 - Initialize actual SemanticCache here
// TODO: v1.3.0 - Generate actual embedding using EmbeddingCache
// TODO: v1.3.0 - Use actual embedding similarity (cosine similarity)

Current behavior:

  • Uses simple std::unordered_map for storage
  • String-based matching only
  • No semantic similarity
  • No HNSW index integration

Requirements

Must Have

  • Integrate ThemisDB's actual EmbeddingCache
  • Implement HNSW-based similarity search
  • Use cosine similarity for semantic matching
  • Generate embeddings for prompts using actual embedding model
  • Support configurable similarity threshold (default: 0.95)
  • Proper TTL and eviction policies

Nice to Have

  • Metrics for cache hit/miss rates
  • Support for multi-level caching
  • Batch embedding generation

Implementation Plan

  1. Replace stub cache initialization

    • Initialize actual SemanticCache in constructor
    • Configure HNSW parameters
  2. Implement embedding generation

    • Use EmbeddingCache for prompt embedding
    • Support for different embedding models
  3. Replace string matching with similarity search

    • Implement HNSW similarity search
    • Use cosine similarity threshold
  4. Add proper error handling

    • Handle embedding generation failures
    • Handle cache misses gracefully

Testing

  • Unit tests for cache operations
  • Integration tests with actual embeddings
  • Performance benchmarks vs stub
  • Verify claimed 75x speedup with real implementation

Performance Impact

Claimed: 75x speedup with semantic caching
Current: Based on stub, needs validation with real implementation

References

  • PRODUCTION_READINESS_REVIEW.md - Stub analysis
  • docs/en/llm/CACHE_IMPLEMENTATION.md - Cache architecture
  • ThemisDB EmbeddingCache implementation

Related Issues

  • Part of production-readiness fixes for LLM features
  • Blocks accurate performance benchmarking</issue_description>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI changed the title [WIP] Implement real LLM response cache with semantic similarity Replace LLM response cache stub with VectorIndexManager integration Jan 5, 2026
Copilot AI requested a review from makr-code January 5, 2026 12:34
@makr-code

Copy link
Copy Markdown
Owner

@copilot Prüfe auf doppelte Implementierung, stub, und production readyness. preview. gtest, gbenchmarks, dokumentation.

Copilot AI commented Jan 5, 2026

Copy link
Copy Markdown
Contributor Author

@copilot Prüfe auf doppelte Implementierung, stub, und production readyness. preview. gtest, gbenchmarks, dokumentation.

✅ Überprüfung abgeschlossen (Commit 17bb01a)

Keine doppelte Implementierung

  • ✅ Nutzt jetzt EmbeddedLLM::embed() / LlamaWrapper::embed() statt eigener Implementierung
  • ✅ Pointer exchange für LLM-Instanz (Config::llm_ptr)
  • ✅ 3-stufige Strategie: Custom Function → Real LLM → Simple Fallback

Kein Stub mehr

  • ✅ VectorIndexManager mit HNSW (M=16, efConstruction=200)
  • ✅ Echte semantische Suche via Cosine-Similarity
  • ✅ Production-ready mit Fehlerbehandlung

Tests & Benchmarks

  • ✅ gtest: test_llm_response_cache.cpp (bereits vorhanden, kompatibel)
  • ✅ gbenchmark: bench_llm_response_cache.cpp (NEU)
    • 7 Benchmarks: Put, Get, Semantic Match, LRU, Concurrent (1/2/4/8 Threads)

Dokumentation

  • ✅ Usage Guide: docs/en/llm/LLM_RESPONSE_CACHE_USAGE.md (NEU)
    • Beispiele für Basic, Advanced, Custom Embeddings
    • Integration mit ThemisDB Core
    • Performance-Metriken
    • Troubleshooting

Production Ready

  • ✅ Thread-safe Operations
  • ✅ LRU Eviction + TTL
  • ✅ Metriken (Hit-Rate, Latenz)
  • ✅ Flexible Embedding-Strategien

Copilot AI changed the title Replace LLM response cache stub with VectorIndexManager integration Replace LLM response cache stub with VectorIndexManager integration and real embedding support Jan 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

02-implement-llm-response-cache.md

2 participants