-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaching.go
More file actions
247 lines (206 loc) · 5.3 KB
/
caching.go
File metadata and controls
247 lines (206 loc) · 5.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package sdk
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"sync"
"time"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// SemanticCache provides similarity-based caching with embeddings.
type SemanticCache struct {
vectorStore VectorStore
cacheStore CacheStore
logger logger.Logger
metrics metrics.Metrics
// Configuration
similarityThreshold float64
ttl time.Duration
maxCacheSize int
// Stats
hits int64
misses int64
mu sync.RWMutex
}
// SemanticCacheConfig configures semantic caching.
type SemanticCacheConfig struct {
SimilarityThreshold float64 // Minimum similarity score (0-1)
TTL time.Duration // Cache entry TTL
MaxCacheSize int // Maximum number of entries
EnableMetrics bool
}
// CachedEntry represents a cached result.
type CachedEntry struct {
Query string
Response string
Embedding []float64
Usage Usage
Timestamp time.Time
Hits int
Similarity float64
}
// NewSemanticCache creates a new semantic cache.
func NewSemanticCache(
vectorStore VectorStore,
cacheStore CacheStore,
logger logger.Logger,
metrics metrics.Metrics,
config SemanticCacheConfig,
) *SemanticCache {
if config.SimilarityThreshold == 0 {
config.SimilarityThreshold = 0.95
}
if config.TTL == 0 {
config.TTL = 1 * time.Hour
}
if config.MaxCacheSize == 0 {
config.MaxCacheSize = 10000
}
return &SemanticCache{
vectorStore: vectorStore,
cacheStore: cacheStore,
logger: logger,
metrics: metrics,
similarityThreshold: config.SimilarityThreshold,
ttl: config.TTL,
maxCacheSize: config.MaxCacheSize,
}
}
// Get retrieves from cache using semantic similarity.
func (sc *SemanticCache) Get(ctx context.Context, query string, embedding []float64) (*CachedEntry, error) {
// First try exact match in cache store
cacheKey := sc.generateKey(query)
if sc.cacheStore != nil {
if data, found, err := sc.cacheStore.Get(ctx, cacheKey); err == nil && found {
var entry CachedEntry
if err := json.Unmarshal(data, &entry); err == nil {
sc.recordHit()
return &entry, nil
}
}
}
// Try semantic similarity search
if sc.vectorStore != nil && len(embedding) > 0 {
matches, err := sc.vectorStore.Query(ctx, embedding, 1, map[string]any{
"type": "cache",
})
if err == nil && len(matches) > 0 {
match := matches[0]
if match.Score >= sc.similarityThreshold {
// Found similar query
if entryData, ok := match.Metadata["entry"].(string); ok {
var entry CachedEntry
if err := json.Unmarshal([]byte(entryData), &entry); err == nil {
entry.Similarity = match.Score
sc.recordHit()
if sc.logger != nil {
sc.logger.Debug("semantic cache hit",
F("query", query),
F("similarity", match.Score),
)
}
return &entry, nil
}
}
}
}
}
sc.recordMiss()
return nil, nil
}
// Set stores in cache with semantic indexing.
func (sc *SemanticCache) Set(ctx context.Context, query string, response string, embedding []float64, usage Usage) error {
entry := CachedEntry{
Query: query,
Response: response,
Embedding: embedding,
Usage: usage,
Timestamp: time.Now(),
Hits: 0,
}
// Store in cache store
cacheKey := sc.generateKey(query)
if sc.cacheStore != nil {
data, err := json.Marshal(entry)
if err != nil {
return fmt.Errorf("failed to marshal entry: %w", err)
}
if err := sc.cacheStore.Set(ctx, cacheKey, data, sc.ttl); err != nil {
return fmt.Errorf("failed to set cache: %w", err)
}
}
// Store embedding in vector store for similarity search
if sc.vectorStore != nil && len(embedding) > 0 {
entryJSON, _ := json.Marshal(entry)
vector := Vector{
ID: cacheKey,
Values: embedding,
Metadata: map[string]any{
"query": query,
"entry": string(entryJSON),
"type": "cache",
"timestamp": time.Now().Unix(),
},
}
if err := sc.vectorStore.Upsert(ctx, []Vector{vector}); err != nil {
return fmt.Errorf("failed to index vector: %w", err)
}
}
if sc.logger != nil {
sc.logger.Debug("cached entry",
F("query", query),
F("response_length", len(response)),
)
}
return nil
}
// Clear clears the cache.
func (sc *SemanticCache) Clear(ctx context.Context) error {
if sc.cacheStore != nil {
return sc.cacheStore.Clear(ctx)
}
return nil
}
// GetStats returns cache statistics.
func (sc *SemanticCache) GetStats() CacheStats {
sc.mu.RLock()
defer sc.mu.RUnlock()
total := sc.hits + sc.misses
hitRate := 0.0
if total > 0 {
hitRate = float64(sc.hits) / float64(total)
}
return CacheStats{
Hits: sc.hits,
Misses: sc.misses,
HitRate: hitRate,
}
}
// CacheStats contains cache statistics.
type CacheStats struct {
Hits int64
Misses int64
HitRate float64
}
func (sc *SemanticCache) recordHit() {
sc.mu.Lock()
defer sc.mu.Unlock()
sc.hits++
if sc.metrics != nil {
sc.metrics.Counter("ai-sdk.cache.hits").Inc()
}
}
func (sc *SemanticCache) recordMiss() {
sc.mu.Lock()
defer sc.mu.Unlock()
sc.misses++
if sc.metrics != nil {
sc.metrics.Counter("ai-sdk.cache.misses").Inc()
}
}
func (sc *SemanticCache) generateKey(query string) string {
hash := sha256.Sum256([]byte(query))
return fmt.Sprintf("cache:%x", hash)
}