1use crate::config::constants::prompt_cache;
2use crate::config::core::PromptCachingConfig;
3use crate::llm::provider::{Message, MessageContent, MessageRole};
4use hashbrown::HashMap;
5use serde::{Deserialize, Serialize};
6use std::fmt::Write;
7use std::path::{Path, PathBuf};
8use tokio::fs;
9use vtcode_commons::VtCodePaths;
10use vtcode_commons::utils::current_timestamp;
11
12use crate::utils::tokens::estimate_tokens;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct CachedPrompt {
17 pub prompt_hash: String,
19 pub original_prompt: String,
21 pub optimized_prompt: String,
23 pub model_used: String,
25 pub tokens_saved: Option<u32>,
27 pub quality_score: Option<f64>,
29 pub created_at: u64,
31 pub last_used: u64,
33 pub usage_count: u32,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct PromptCacheConfig {
40 pub enabled: bool,
42 pub cache_dir: PathBuf,
44 pub max_cache_size: usize,
46 pub max_age_days: u64,
48 pub enable_auto_cleanup: bool,
50 pub min_quality_threshold: f64,
52}
53
54impl Default for PromptCacheConfig {
55 fn default() -> Self {
56 let cache_dir = default_cache_dir();
57 Self {
58 enabled: prompt_cache::DEFAULT_ENABLED && !cache_dir.as_os_str().is_empty(),
59 cache_dir,
60 max_cache_size: prompt_cache::DEFAULT_MAX_ENTRIES,
61 max_age_days: prompt_cache::DEFAULT_MAX_AGE_DAYS,
62 enable_auto_cleanup: prompt_cache::DEFAULT_AUTO_CLEANUP,
63 min_quality_threshold: prompt_cache::DEFAULT_MIN_QUALITY_THRESHOLD,
64 }
65 }
66}
67
68impl PromptCacheConfig {
69 pub fn from_settings(settings: &PromptCachingConfig, workspace_root: Option<&Path>) -> Self {
71 let cache_dir = settings.resolve_cache_dir(workspace_root);
72 Self {
73 enabled: settings.enabled && !cache_dir.as_os_str().is_empty(),
74 cache_dir,
75 max_cache_size: settings.max_entries,
76 max_age_days: settings.max_age_days,
77 enable_auto_cleanup: settings.enable_auto_cleanup,
78 min_quality_threshold: settings.min_quality_threshold,
79 }
80 }
81
82 pub fn is_enabled(&self) -> bool {
84 self.enabled
85 }
86}
87
88fn default_cache_dir() -> PathBuf {
89 VtCodePaths::resolve()
90 .map(|paths| paths.cache_dir().join("prompts"))
91 .unwrap_or_default()
92}
93
94pub struct PromptCache {
96 config: PromptCacheConfig,
97 cache: HashMap<String, CachedPrompt>,
98 dirty: bool,
99}
100
101impl PromptCache {
102 pub async fn new() -> Self {
104 Self::with_config(PromptCacheConfig::default()).await
105 }
106
107 pub async fn with_config(config: PromptCacheConfig) -> Self {
109 let mut config = config;
110 if config.cache_dir.as_os_str().is_empty() {
111 config.enabled = false;
112 }
113 let mut cache = Self { config, cache: HashMap::new(), dirty: false };
114
115 if cache.config.enabled {
117 let _ = cache.load_cache().await;
118
119 if cache.config.enable_auto_cleanup {
121 let _ = cache.cleanup_expired();
122 }
123 }
124
125 cache
126 }
127
128 pub fn get(&mut self, prompt_hash: &str) -> Option<CachedPrompt> {
130 if !self.config.enabled {
131 return None;
132 }
133 self.cache.get_mut(prompt_hash).map(|entry| {
134 entry.last_used = current_timestamp();
135 entry.usage_count += 1;
136 self.dirty = true;
137 entry.clone()
138 })
139 }
140
141 pub fn put(&mut self, entry: CachedPrompt) -> Result<(), PromptCacheError> {
143 if !self.config.enabled {
144 return Ok(());
145 }
146 if entry
148 .quality_score
149 .is_some_and(|quality| quality < self.config.min_quality_threshold)
150 {
151 return Ok(()); }
153
154 if self.cache.len() >= self.config.max_cache_size {
156 self.evict_oldest()?;
157 }
158
159 self.cache.insert(entry.prompt_hash.clone(), entry);
160 self.dirty = true;
161
162 Ok(())
163 }
164
165 pub fn contains(&self, prompt_hash: &str) -> bool {
167 self.config.enabled && self.cache.contains_key(prompt_hash)
168 }
169
170 pub fn stats(&self) -> CacheStats {
172 if !self.config.enabled {
173 return CacheStats::default();
174 }
175 let total_entries = self.cache.len();
176 let total_usage = self.cache.values().map(|e| e.usage_count).sum::<u32>();
177 let total_tokens_saved = self.cache.values().filter_map(|e| e.tokens_saved).sum::<u32>();
178 let avg_quality = if !self.cache.is_empty() {
179 self.cache.values().filter_map(|e| e.quality_score).sum::<f64>() / self.cache.len() as f64
180 } else {
181 0.0
182 };
183
184 CacheStats {
185 total_entries,
186 total_usage,
187 total_tokens_saved,
188 avg_quality,
189 }
190 }
191
192 pub async fn clear(&mut self) -> Result<(), PromptCacheError> {
194 if !self.config.enabled {
195 return Ok(());
196 }
197 self.cache.clear();
198 self.dirty = true;
199 self.save_cache().await
200 }
201
202 pub fn hash_prompt(prompt: &str) -> String {
204 vtcode_commons::utils::calculate_sha256(prompt.as_bytes())
205 }
206
207 pub async fn save_cache(&self) -> Result<(), PromptCacheError> {
209 if !self.config.enabled || self.config.cache_dir.as_os_str().is_empty() || !self.dirty {
210 return Ok(());
211 }
212
213 let is_global_cache = VtCodePaths::resolve()
217 .ok()
218 .is_some_and(|paths| self.config.cache_dir.starts_with(paths.cache_dir()));
219 if is_global_cache {
220 VtCodePaths::ensure_user_dir(&self.config.cache_dir)
221 .map_err(|error| PromptCacheError::Io(std::io::Error::other(error)))?;
222 } else {
223 fs::create_dir_all(&self.config.cache_dir).await.map_err(PromptCacheError::Io)?;
224 }
225
226 let cache_path = self.config.cache_dir.join("prompt_cache.json");
227 let data = serde_json::to_string_pretty(&self.cache).map_err(PromptCacheError::Serialization)?;
228
229 if is_global_cache {
230 vtcode_commons::fs::write_private_file_atomic(&cache_path, data.as_bytes())
231 .await
232 .map_err(|error| PromptCacheError::Io(std::io::Error::other(error)))?;
233 } else {
234 fs::write(cache_path, data).await.map_err(PromptCacheError::Io)?;
235 }
236
237 Ok(())
238 }
239
240 async fn load_cache(&mut self) -> Result<(), PromptCacheError> {
242 if !self.config.enabled || self.config.cache_dir.as_os_str().is_empty() {
243 return Ok(());
244 }
245 let cache_path = self.config.cache_dir.join("prompt_cache.json");
246
247 if !fs::try_exists(&cache_path).await.unwrap_or(false) {
248 return Ok(());
249 }
250
251 let data = if VtCodePaths::resolve()
252 .ok()
253 .is_some_and(|paths| self.config.cache_dir.starts_with(paths.cache_dir()))
254 {
255 String::from_utf8(
256 vtcode_commons::fs::read_private_file_no_follow(&cache_path)
257 .await
258 .map_err(|error| PromptCacheError::Io(std::io::Error::other(error.to_string())))?,
259 )
260 .map_err(|error| PromptCacheError::Io(std::io::Error::other(error)))?
261 } else {
262 fs::read_to_string(cache_path).await.map_err(PromptCacheError::Io)?
263 };
264
265 self.cache = serde_json::from_str(&data).map_err(PromptCacheError::Serialization)?;
266
267 Ok(())
268 }
269
270 fn cleanup_expired(&mut self) -> Result<(), PromptCacheError> {
272 if !self.config.enabled {
273 return Ok(());
274 }
275 let now = current_timestamp();
276 let max_age_seconds = self.config.max_age_days * 24 * 60 * 60;
277
278 self.cache.retain(|_, entry| now - entry.created_at < max_age_seconds);
279
280 self.dirty = true;
281 Ok(())
282 }
283
284 fn evict_oldest(&mut self) -> Result<(), PromptCacheError> {
286 if !self.config.enabled {
287 return Ok(());
288 }
289 if self.cache.is_empty() {
290 return Ok(());
291 }
292
293 let Some(oldest_key) = self
295 .cache
296 .iter()
297 .min_by_key(|(_, entry)| entry.last_used)
298 .map(|(key, _)| key.clone())
299 else {
300 return Ok(());
301 };
302
303 self.cache.remove(&oldest_key);
304 self.dirty = true;
305
306 Ok(())
307 }
308}
309
310#[derive(Debug, Clone, Default, Serialize, Deserialize)]
319pub struct CacheStats {
320 pub total_entries: usize,
322 pub total_usage: u32,
324 pub total_tokens_saved: u32,
326 pub avg_quality: f64,
328}
329
330#[derive(Debug, thiserror::Error)]
332pub enum PromptCacheError {
333 #[error("IO error: {0}")]
334 Io(#[from] std::io::Error),
335
336 #[error("Serialization error: {0}")]
337 Serialization(#[from] serde_json::Error),
338
339 #[error("Cache full")]
340 CacheFull,
341}
342
343pub struct PromptOptimizer {
345 cache: PromptCache,
346 llm_provider: Box<dyn crate::llm::provider::LLMProvider>,
347}
348
349impl PromptOptimizer {
350 pub async fn new(llm_provider: Box<dyn crate::llm::provider::LLMProvider>) -> Self {
352 Self { cache: PromptCache::new().await, llm_provider }
353 }
354
355 pub fn with_cache(mut self, cache: PromptCache) -> Self {
357 self.cache = cache;
358 self
359 }
360
361 pub async fn save_cache(&self) -> Result<(), PromptCacheError> {
363 self.cache.save_cache().await
364 }
365
366 pub async fn optimize_prompt(
368 &mut self,
369 original_prompt: &str,
370 target_model: &str,
371 context: Option<&str>,
372 ) -> Result<String, PromptOptimizationError> {
373 let prompt_hash = PromptCache::hash_prompt(original_prompt);
374
375 if let Some(cached) = self.cache.get(&prompt_hash) {
377 return Ok(cached.optimized_prompt);
378 }
379
380 let optimized = self.generate_optimized_prompt(original_prompt, target_model, context).await?;
382
383 let original_tokens = estimate_tokens(original_prompt);
385 let optimized_tokens = estimate_tokens(&optimized);
386 let tokens_saved = original_tokens.saturating_sub(optimized_tokens);
387
388 let entry = CachedPrompt {
390 prompt_hash: prompt_hash.clone(),
391 original_prompt: original_prompt.to_string(),
392 optimized_prompt: optimized.clone(),
393 model_used: target_model.to_string(),
394 tokens_saved: Some(tokens_saved.min(u32::MAX as usize) as u32),
395 quality_score: Some(0.8), created_at: current_timestamp(),
397 last_used: current_timestamp(),
398 usage_count: 1,
399 };
400
401 self.cache.put(entry)?;
403
404 Ok(optimized)
405 }
406
407 async fn generate_optimized_prompt(
409 &self,
410 original_prompt: &str,
411 target_model: &str,
412 context: Option<&str>,
413 ) -> Result<String, PromptOptimizationError> {
414 let system_prompt = format!(
415 "You are an expert prompt engineer. Your task is to optimize prompts for {target_model} \
416 to make them more effective, clearer, and more likely to produce high-quality responses. \
417 Focus on improving clarity, specificity, structure, and effectiveness while preserving \
418 the original intent and requirements."
419 );
420
421 let mut user_prompt = format!(
422 "Please optimize the following prompt for {target_model}:\n\nORIGINAL PROMPT:\n{original_prompt}\n\n"
423 );
424
425 if let Some(ctx) = context {
426 let _ = write!(user_prompt, "CONTEXT:\n{ctx}\n\n");
427 }
428
429 user_prompt.push_str(
430 "OPTIMIZATION REQUIREMENTS:\n\
431 1. Make the prompt clearer and more specific\n\
432 2. Improve structure and formatting\n\
433 3. Add relevant context or examples if helpful\n\
434 4. Ensure the prompt is appropriate for the target model\n\
435 5. Maintain the original intent and requirements\n\
436 6. Keep the optimized prompt concise but comprehensive\n\n\
437 Provide only the optimized prompt without any explanation or additional text.",
438 );
439
440 let request = crate::llm::provider::LLMRequest {
441 messages: std::sync::Arc::new(vec![
442 Message {
443 role: MessageRole::System,
444 content: MessageContent::Text(system_prompt),
445 ..Default::default()
446 },
447 Message {
448 role: MessageRole::User,
449 content: MessageContent::Text(user_prompt),
450 ..Default::default()
451 },
452 ]),
453 model: target_model.to_string(),
454 max_tokens: Some(2000),
455 temperature: Some(0.3),
456 ..Default::default()
457 };
458
459 let response = self
460 .llm_provider
461 .generate(request)
462 .await
463 .map_err(|e| PromptOptimizationError::LLMError(e.to_string()))?;
464
465 Ok(response.content.unwrap_or_else(|| original_prompt.to_string()))
466 }
467
468 pub fn cache_stats(&self) -> CacheStats {
470 self.cache.stats()
471 }
472
473 pub async fn clear_cache(&mut self) -> Result<(), PromptCacheError> {
475 self.cache.clear().await
476 }
477}
478
479#[derive(Debug, thiserror::Error)]
481pub enum PromptOptimizationError {
482 #[error("LLM error: {0}")]
483 LLMError(String),
484
485 #[error("Cache error: {0}")]
486 CacheError(#[from] PromptCacheError),
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 #[test]
494 fn test_prompt_hash() {
495 let prompt = "Test prompt";
496 let hash1 = PromptCache::hash_prompt(prompt);
497 let hash2 = PromptCache::hash_prompt(prompt);
498 assert_eq!(hash1, hash2);
499 assert!(!hash1.is_empty());
500 }
501
502 #[tokio::test]
503 async fn test_cache_operations() {
504 let mut cache = PromptCache::new().await;
505
506 let entry = CachedPrompt {
507 prompt_hash: "test_hash".to_owned(),
508 original_prompt: "original".to_owned(),
509 optimized_prompt: "optimized".to_owned(),
510 model_used: crate::config::constants::models::google::GEMINI_3_FLASH_PREVIEW.to_owned(),
511 tokens_saved: Some(100),
512 quality_score: Some(0.9),
513 created_at: 1000,
514 last_used: 1000,
515 usage_count: 0,
516 };
517
518 cache.put(entry).unwrap();
519 assert!(cache.contains("test_hash"));
520
521 let retrieved = cache.get("test_hash");
522 assert!(retrieved.is_some());
523 assert_eq!(retrieved.unwrap().usage_count, 1);
524 }
525
526 #[tokio::test]
527 async fn disabled_cache_config_is_no_op() {
528 let settings = PromptCachingConfig {
529 enabled: false,
530 cache_dir: "relative/cache".to_owned(),
531 ..PromptCachingConfig::default()
532 };
533 let cfg = PromptCacheConfig::from_settings(&settings, None);
534 assert!(!cfg.is_enabled());
535
536 let mut cache = PromptCache::with_config(cfg).await;
537 assert!(!cache.contains("missing"));
538 assert_eq!(cache.stats().total_entries, 0);
539
540 let entry = CachedPrompt {
541 prompt_hash: "noop".to_owned(),
542 original_prompt: "original".to_owned(),
543 optimized_prompt: "optimized".to_owned(),
544 model_used: crate::config::constants::models::google::GEMINI_3_FLASH_PREVIEW.to_owned(),
545 tokens_saved: Some(10),
546 quality_score: Some(0.9),
547 created_at: 1,
548 last_used: 1,
549 usage_count: 0,
550 };
551
552 cache.put(entry).unwrap();
553 assert!(!cache.contains("noop"));
554 assert_eq!(cache.stats().total_entries, 0);
555 }
556}