返回 CodeWhale
llm_response_cache.rs
根目录 / crates / runtime / src / llm_response_cache.rs
1 //! Small in-process cache for deterministic non-streaming chat responses.
2
3 use std::num::NonZeroUsize;
4 use std::sync::{Mutex, OnceLock};
5
6 use lru::LruCache;
7 use sha2::{Digest, Sha256};
8
9 use codewhale_models::{MessageRequest, MessageResponse, Usage};
10
11 const DEFAULT_CAPACITY: usize = 256;
12
13 static RESPONSE_CACHE: OnceLock<ResponseCache> = OnceLock::new();
14
15 pub fn response_cache() -> &'static ResponseCache {
16 RESPONSE_CACHE.get_or_init(ResponseCache::new)
17 }
18
19 pub fn request_is_cacheable(request: &MessageRequest) -> bool {
20 request.stream != Some(true)
21 && request.tools.as_ref().is_none_or(Vec::is_empty)
22 && request.tool_choice.is_none()
23 && request.temperature == Some(0.0)
24 && request.top_p.is_none_or(|top_p| top_p == 1.0)
25 }
26
27 pub struct ResponseCache {
28 inner: Mutex<LruCache<[u8; 32], MessageResponse>>,
29 }
30
31 impl ResponseCache {
32 fn new() -> Self {
33 Self::with_capacity(NonZeroUsize::new(DEFAULT_CAPACITY).expect("non-zero capacity"))
34 }
35
36 fn with_capacity(capacity: NonZeroUsize) -> Self {
37 Self {
38 inner: Mutex::new(LruCache::new(capacity)),
39 }
40 }
41
42 pub fn make_key(
43 provider: &str,
44 base_url: &str,
45 path_suffix: Option<&str>,
46 api_key: &str,
47 wire_body: &[u8],
48 ) -> [u8; 32] {
49 let mut hasher = Sha256::new();
50 update_field(&mut hasher, provider.as_bytes());
51 update_field(&mut hasher, base_url.as_bytes());
52 update_field(&mut hasher, path_suffix.unwrap_or("").as_bytes());
53 update_field(&mut hasher, &Sha256::digest(api_key.as_bytes()));
54 update_field(&mut hasher, wire_body);
55 hasher.finalize().into()
56 }
57
58 pub fn get(&self, key: &[u8; 32]) -> Option<MessageResponse> {
59 let mut cache = self.inner.lock().ok()?;
60 cache.get(key).cloned().map(|mut response| {
61 response.usage = Usage::default();
62 response
63 })
64 }
65
66 pub fn put(&self, key: [u8; 32], value: MessageResponse) {
67 if let Ok(mut cache) = self.inner.lock() {
68 cache.put(key, value);
69 }
70 }
71 }
72
73 fn update_field(hasher: &mut Sha256, bytes: &[u8]) {
74 hasher.update((bytes.len() as u64).to_le_bytes());
75 hasher.update(bytes);
76 }
77
78 #[cfg(test)]
79 mod tests {
80 use super::*;
81
82 fn response_with_usage(id: &str) -> MessageResponse {
83 MessageResponse {
84 tool_projection_warning: None,
85 id: id.to_string(),
86 r#type: "message".to_string(),
87 role: "assistant".to_string(),
88 content: Vec::new(),
89 model: "test-model".to_string(),
90 stop_reason: Some("end_turn".to_string()),
91 stop_sequence: None,
92 container: None,
93 title: None,
94 stop_details: None,
95 refusal: None,
96 usage: Usage {
97 input_tokens: 42,
98 output_tokens: 7,
99 prompt_cache_hit_tokens: Some(3),
100 prompt_cache_miss_tokens: Some(39),
101 prompt_cache_write_tokens: None,
102 reasoning_tokens: Some(5),
103 reasoning_replay_tokens: Some(2),
104 server_tool_use: None,
105
106 input_audio_tokens: None,
107 output_audio_tokens: None,
108
109 request_usages: Vec::new(),
110 safety_tokens: None,
111 },
112 }
113 }
114
115 fn request() -> MessageRequest {
116 MessageRequest {
117 model: "test-model".to_string(),
118 messages: Vec::new(),
119 max_tokens: 16,
120 system: None,
121 tools: None,
122 tool_choice: None,
123 metadata: None,
124 thinking: None,
125 reasoning_effort: None,
126 stream: None,
127 temperature: Some(0.0),
128 top_p: None,
129 safety_check: None,
130 title: None,
131 }
132 }
133
134 #[test]
135 fn cache_key_separates_provider_route_account_and_wire_body() {
136 let base = ResponseCache::make_key(
137 "deepseek",
138 "https://api.example.com/v1",
139 None,
140 "key-a",
141 br#"{"model":"m","messages":[]}"#,
142 );
143
144 assert_ne!(
145 base,
146 ResponseCache::make_key(
147 "openai",
148 "https://api.example.com/v1",
149 None,
150 "key-a",
151 br#"{"model":"m","messages":[]}"#
152 )
153 );
154 assert_ne!(
155 base,
156 ResponseCache::make_key(
157 "deepseek",
158 "https://proxy.example.com/v1",
159 None,
160 "key-a",
161 br#"{"model":"m","messages":[]}"#
162 )
163 );
164 assert_ne!(
165 base,
166 ResponseCache::make_key(
167 "deepseek",
168 "https://api.example.com/v1",
169 Some("responses"),
170 "key-a",
171 br#"{"model":"m","messages":[]}"#
172 )
173 );
174 assert_ne!(
175 base,
176 ResponseCache::make_key(
177 "deepseek",
178 "https://api.example.com/v1",
179 None,
180 "key-b",
181 br#"{"model":"m","messages":[]}"#
182 )
183 );
184 assert_ne!(
185 base,
186 ResponseCache::make_key(
187 "deepseek",
188 "https://api.example.com/v1",
189 None,
190 "key-a",
191 br#"{"model":"m","messages":[],"reasoning_effort":"high"}"#
192 )
193 );
194 }
195
196 #[test]
197 fn cache_hit_zeroes_usage_to_avoid_fake_spend() {
198 let cache = ResponseCache::with_capacity(NonZeroUsize::new(2).unwrap());
199 let key =
200 ResponseCache::make_key("deepseek", "https://api.example.com", None, "key", b"{}");
201
202 cache.put(key, response_with_usage("cached"));
203
204 let hit = cache.get(&key).expect("cache hit");
205 assert_eq!(hit.id, "cached");
206 assert_eq!(hit.usage, Usage::default());
207 }
208
209 #[test]
210 fn capacity_evicts_oldest_entry() {
211 let cache = ResponseCache::with_capacity(NonZeroUsize::new(2).unwrap());
212 let key1 =
213 ResponseCache::make_key("deepseek", "https://api.example.com", None, "key", b"one");
214 let key2 =
215 ResponseCache::make_key("deepseek", "https://api.example.com", None, "key", b"two");
216 let key3 =
217 ResponseCache::make_key("deepseek", "https://api.example.com", None, "key", b"three");
218
219 cache.put(key1, response_with_usage("one"));
220 cache.put(key2, response_with_usage("two"));
221 cache.put(key3, response_with_usage("three"));
222
223 assert!(cache.get(&key1).is_none());
224 assert!(cache.get(&key2).is_some());
225 assert!(cache.get(&key3).is_some());
226 }
227
228 #[test]
229 fn cacheability_requires_deterministic_tool_free_non_streaming_request() {
230 let mut req = request();
231 assert!(request_is_cacheable(&req));
232
233 req.temperature = None;
234 assert!(!request_is_cacheable(&req));
235
236 req = request();
237 req.temperature = Some(0.2);
238 assert!(!request_is_cacheable(&req));
239
240 req = request();
241 req.stream = Some(true);
242 assert!(!request_is_cacheable(&req));
243
244 req = request();
245 req.top_p = Some(0.5);
246 assert!(!request_is_cacheable(&req));
247
248 req = request();
249 req.tool_choice = Some(serde_json::json!("auto"));
250 assert!(!request_is_cacheable(&req));
251 }
252 }
253
253 lines RUST