-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
76 lines (63 loc) · 1.94 KB
/
cache.go
File metadata and controls
76 lines (63 loc) · 1.94 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
package ai
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"sync"
)
// ═══════════════════════════════════════════════════════════════════════════
// Response Caching
// ═══════════════════════════════════════════════════════════════════════════
var (
cache = make(map[string]string)
cacheLock sync.RWMutex
)
// cacheKey generates a unique key for a request.
func cacheKey(model Model, messages []Message, opts SendOptions) string {
data, _ := json.Marshal(struct {
Model string `json:"m"`
Messages []Message `json:"msgs"`
Temp *float64 `json:"t,omitempty"`
Thinking string `json:"r,omitempty"`
}{
Model: string(model),
Messages: messages,
Temp: opts.Temperature,
Thinking: string(opts.Thinking),
})
hash := sha256.Sum256(data)
return hex.EncodeToString(hash[:])
}
// getCached returns a cached response if available.
func getCached(model Model, messages []Message, opts SendOptions) (string, bool) {
if !Cache {
return "", false
}
cacheLock.RLock()
defer cacheLock.RUnlock()
key := cacheKey(model, messages, opts)
resp, ok := cache[key]
return resp, ok
}
// setCached stores a response in cache.
func setCached(model Model, messages []Message, opts SendOptions, response string) {
if !Cache {
return
}
cacheLock.Lock()
defer cacheLock.Unlock()
key := cacheKey(model, messages, opts)
cache[key] = response
}
// ClearCache empties the in-memory cache.
func ClearCache() {
cacheLock.Lock()
defer cacheLock.Unlock()
cache = make(map[string]string)
}
// CacheSize returns the number of cached responses.
func CacheSize() int {
cacheLock.RLock()
defer cacheLock.RUnlock()
return len(cache)
}