Class: RubyLLM::SemanticRouter::EmbeddingCache
- Inherits:
-
Object
- Object
- RubyLLM::SemanticRouter::EmbeddingCache
- Defined in:
- lib/rubyllm/semantic_router/embedding_cache.rb
Overview
Simple in-memory cache for embeddings with TTL support
Defined Under Namespace
Classes: CacheEntry
Instance Method Summary collapse
-
#cleanup! ⇒ Object
Remove expired entries from cache.
-
#clear! ⇒ Object
Clear all cached entries.
-
#fetch(key) { ... } ⇒ Array
Get embedding from cache or compute it.
-
#get(key) ⇒ Array?
Get embedding from cache.
-
#initialize(ttl:) ⇒ EmbeddingCache
constructor
A new instance of EmbeddingCache.
-
#set(key, embedding) ⇒ Object
Store embedding in cache.
-
#size ⇒ Object
Number of entries in cache.
Constructor Details
#initialize(ttl:) ⇒ EmbeddingCache
Returns a new instance of EmbeddingCache.
9 10 11 12 13 |
# File 'lib/rubyllm/semantic_router/embedding_cache.rb', line 9 def initialize(ttl:) @ttl = ttl @cache = {} @mutex = Mutex.new end |
Instance Method Details
#cleanup! ⇒ Object
Remove expired entries from cache
54 55 56 57 58 59 |
# File 'lib/rubyllm/semantic_router/embedding_cache.rb', line 54 def cleanup! @mutex.synchronize do now = Time.now @cache.delete_if { |_, entry| entry.expires_at < now } end end |
#clear! ⇒ Object
Clear all cached entries
62 63 64 65 66 |
# File 'lib/rubyllm/semantic_router/embedding_cache.rb', line 62 def clear! @mutex.synchronize do @cache.clear end end |
#fetch(key) { ... } ⇒ Array
Get embedding from cache or compute it
44 45 46 47 48 49 50 51 |
# File 'lib/rubyllm/semantic_router/embedding_cache.rb', line 44 def fetch(key) cached = get(key) return cached if cached = yield set(key, ) end |
#get(key) ⇒ Array?
Get embedding from cache
18 19 20 21 22 23 24 25 26 |
# File 'lib/rubyllm/semantic_router/embedding_cache.rb', line 18 def get(key) @mutex.synchronize do entry = @cache[key] return nil unless entry return nil if entry.expires_at < Time.now entry. end end |
#set(key, embedding) ⇒ Object
Store embedding in cache
31 32 33 34 35 36 37 38 |
# File 'lib/rubyllm/semantic_router/embedding_cache.rb', line 31 def set(key, ) @mutex.synchronize do @cache[key] = CacheEntry.new( embedding: , expires_at: Time.now + @ttl ) end end |
#size ⇒ Object
Number of entries in cache
69 70 71 |
# File 'lib/rubyllm/semantic_router/embedding_cache.rb', line 69 def size @mutex.synchronize { @cache.size } end |