bindings_generat/llm/
cache.rs1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use sha2::{Digest, Sha256};
4use std::fs;
5use std::path::PathBuf;
6use tracing::{debug, info};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct CachedResponse {
11 pub prompt_hash: String,
12 pub model: String,
13 pub response: String,
14 pub timestamp: i64,
15}
16
17pub struct Cache {
19 cache_dir: PathBuf,
20}
21
22impl Cache {
23 pub fn new(cache_dir: Option<PathBuf>) -> Result<Self> {
25 let cache_dir = if let Some(dir) = cache_dir {
26 dir
27 } else {
28 let mut dir = dirs::cache_dir().context("Failed to get system cache directory")?;
30 dir.push("bindings-generat");
31 dir.push("llm-cache");
32 dir
33 };
34
35 if !cache_dir.exists() {
37 fs::create_dir_all(&cache_dir).context("Failed to create cache directory")?;
38 info!("Created LLM cache directory: {}", cache_dir.display());
39 }
40
41 Ok(Self { cache_dir })
42 }
43
44 fn cache_key(&self, prompt: &str, model: &str) -> String {
46 let mut hasher = Sha256::new();
47 hasher.update(prompt.as_bytes());
48 hasher.update(model.as_bytes());
49 format!("{:x}", hasher.finalize())
50 }
51
52 fn cache_path(&self, key: &str) -> PathBuf {
54 self.cache_dir.join(format!("{}.json", key))
55 }
56
57 pub fn get(&self, prompt: &str, model: &str) -> Option<String> {
59 let key = self.cache_key(prompt, model);
60 let path = self.cache_path(&key);
61
62 if !path.exists() {
63 debug!("Cache miss: {} not found", key);
64 return None;
65 }
66
67 let content = fs::read_to_string(&path).ok()?;
69 let cached: CachedResponse = serde_json::from_str(&content).ok()?;
70
71 if cached.model != model {
73 debug!("Cache miss: model mismatch");
74 return None;
75 }
76
77 info!("Cache hit: {}", key);
78 Some(cached.response)
79 }
80
81 pub fn set(&self, prompt: &str, model: &str, response: String) -> Result<()> {
83 let key = self.cache_key(prompt, model);
84 let path = self.cache_path(&key);
85
86 let cached = CachedResponse {
87 prompt_hash: key.clone(),
88 model: model.to_string(),
89 response,
90 timestamp: chrono::Utc::now().timestamp(),
91 };
92
93 let content =
94 serde_json::to_string_pretty(&cached).context("Failed to serialize cached response")?;
95
96 fs::write(&path, content).context("Failed to write cache file")?;
97
98 debug!("Cached response: {}", key);
99 Ok(())
100 }
101
102 pub fn clear(&self) -> Result<()> {
104 if self.cache_dir.exists() {
105 fs::remove_dir_all(&self.cache_dir).context("Failed to clear cache directory")?;
106 fs::create_dir_all(&self.cache_dir).context("Failed to recreate cache directory")?;
107 info!("Cleared LLM cache");
108 }
109 Ok(())
110 }
111
112 pub fn size(&self) -> Result<u64> {
114 let mut total_size = 0u64;
115
116 if self.cache_dir.exists() {
117 for entry in fs::read_dir(&self.cache_dir)? {
118 let entry = entry?;
119 if entry.file_type()?.is_file() {
120 total_size += entry.metadata()?.len();
121 }
122 }
123 }
124
125 Ok(total_size)
126 }
127
128 pub fn count(&self) -> Result<usize> {
130 let mut count = 0;
131
132 if self.cache_dir.exists() {
133 for entry in fs::read_dir(&self.cache_dir)? {
134 let entry = entry?;
135 if entry.file_type()?.is_file() {
136 count += 1;
137 }
138 }
139 }
140
141 Ok(count)
142 }
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148 use tempfile::TempDir;
149
150 #[test]
151 fn test_cache_basic_operations() {
152 let temp_dir = TempDir::new().unwrap();
153 let cache = Cache::new(Some(temp_dir.path().to_path_buf())).unwrap();
154
155 let prompt = "Test prompt";
156 let model = "test-model";
157 let response = "Test response";
158
159 assert!(cache.get(prompt, model).is_none());
161 assert_eq!(cache.count().unwrap(), 0);
162
163 cache.set(prompt, model, response.to_string()).unwrap();
165
166 assert_eq!(cache.get(prompt, model).unwrap(), response);
168 assert_eq!(cache.count().unwrap(), 1);
169 }
170
171 #[test]
172 fn test_cache_model_differentiation() {
173 let temp_dir = TempDir::new().unwrap();
174 let cache = Cache::new(Some(temp_dir.path().to_path_buf())).unwrap();
175
176 let prompt = "Same prompt";
177 let model1 = "model1";
178 let model2 = "model2";
179
180 cache.set(prompt, model1, "Response 1".to_string()).unwrap();
181 cache.set(prompt, model2, "Response 2".to_string()).unwrap();
182
183 assert_eq!(cache.get(prompt, model1).unwrap(), "Response 1");
185 assert_eq!(cache.get(prompt, model2).unwrap(), "Response 2");
186 assert_eq!(cache.count().unwrap(), 2);
187 }
188
189 #[test]
190 fn test_cache_clear() {
191 let temp_dir = TempDir::new().unwrap();
192 let cache = Cache::new(Some(temp_dir.path().to_path_buf())).unwrap();
193
194 cache
195 .set("prompt", "model", "response".to_string())
196 .unwrap();
197 assert_eq!(cache.count().unwrap(), 1);
198
199 cache.clear().unwrap();
200 assert_eq!(cache.count().unwrap(), 0);
201 }
202}