liter_llm 1.0.0.pre.rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +239 -0
  3. data/ext/liter_llm_rb/extconf.rb +65 -0
  4. data/ext/liter_llm_rb/native/.cargo/config.toml +23 -0
  5. data/ext/liter_llm_rb/native/Cargo.lock +3713 -0
  6. data/ext/liter_llm_rb/native/Cargo.toml +32 -0
  7. data/ext/liter_llm_rb/native/build.rs +15 -0
  8. data/ext/liter_llm_rb/native/src/lib.rs +1079 -0
  9. data/lib/liter_llm.rb +8 -0
  10. data/sig/liter_llm.rbs +416 -0
  11. data/vendor/Cargo.toml +54 -0
  12. data/vendor/liter-llm/Cargo.toml +92 -0
  13. data/vendor/liter-llm/README.md +252 -0
  14. data/vendor/liter-llm/schemas/pricing.json +40 -0
  15. data/vendor/liter-llm/schemas/providers.json +1662 -0
  16. data/vendor/liter-llm/src/auth/azure_ad.rs +264 -0
  17. data/vendor/liter-llm/src/auth/bedrock_sts.rs +353 -0
  18. data/vendor/liter-llm/src/auth/mod.rs +68 -0
  19. data/vendor/liter-llm/src/auth/vertex_oauth.rs +353 -0
  20. data/vendor/liter-llm/src/client/config.rs +351 -0
  21. data/vendor/liter-llm/src/client/managed.rs +622 -0
  22. data/vendor/liter-llm/src/client/mod.rs +864 -0
  23. data/vendor/liter-llm/src/cost.rs +212 -0
  24. data/vendor/liter-llm/src/error.rs +190 -0
  25. data/vendor/liter-llm/src/http/eventstream.rs +860 -0
  26. data/vendor/liter-llm/src/http/mod.rs +12 -0
  27. data/vendor/liter-llm/src/http/request.rs +438 -0
  28. data/vendor/liter-llm/src/http/retry.rs +72 -0
  29. data/vendor/liter-llm/src/http/streaming.rs +289 -0
  30. data/vendor/liter-llm/src/lib.rs +37 -0
  31. data/vendor/liter-llm/src/provider/anthropic.rs +2250 -0
  32. data/vendor/liter-llm/src/provider/azure.rs +579 -0
  33. data/vendor/liter-llm/src/provider/bedrock.rs +1543 -0
  34. data/vendor/liter-llm/src/provider/cohere.rs +654 -0
  35. data/vendor/liter-llm/src/provider/custom.rs +404 -0
  36. data/vendor/liter-llm/src/provider/google_ai.rs +281 -0
  37. data/vendor/liter-llm/src/provider/mistral.rs +188 -0
  38. data/vendor/liter-llm/src/provider/mod.rs +616 -0
  39. data/vendor/liter-llm/src/provider/vertex.rs +1504 -0
  40. data/vendor/liter-llm/src/tests.rs +1425 -0
  41. data/vendor/liter-llm/src/tokenizer.rs +281 -0
  42. data/vendor/liter-llm/src/tower/budget.rs +599 -0
  43. data/vendor/liter-llm/src/tower/cache.rs +502 -0
  44. data/vendor/liter-llm/src/tower/cache_opendal.rs +270 -0
  45. data/vendor/liter-llm/src/tower/cooldown.rs +231 -0
  46. data/vendor/liter-llm/src/tower/cost.rs +404 -0
  47. data/vendor/liter-llm/src/tower/fallback.rs +121 -0
  48. data/vendor/liter-llm/src/tower/health.rs +219 -0
  49. data/vendor/liter-llm/src/tower/hooks.rs +369 -0
  50. data/vendor/liter-llm/src/tower/mod.rs +77 -0
  51. data/vendor/liter-llm/src/tower/rate_limit.rs +300 -0
  52. data/vendor/liter-llm/src/tower/router.rs +436 -0
  53. data/vendor/liter-llm/src/tower/service.rs +181 -0
  54. data/vendor/liter-llm/src/tower/tests.rs +539 -0
  55. data/vendor/liter-llm/src/tower/tests_common.rs +252 -0
  56. data/vendor/liter-llm/src/tower/tracing.rs +209 -0
  57. data/vendor/liter-llm/src/tower/types.rs +170 -0
  58. data/vendor/liter-llm/src/types/audio.rs +52 -0
  59. data/vendor/liter-llm/src/types/batch.rs +77 -0
  60. data/vendor/liter-llm/src/types/chat.rs +214 -0
  61. data/vendor/liter-llm/src/types/common.rs +244 -0
  62. data/vendor/liter-llm/src/types/embedding.rs +84 -0
  63. data/vendor/liter-llm/src/types/files.rs +58 -0
  64. data/vendor/liter-llm/src/types/image.rs +40 -0
  65. data/vendor/liter-llm/src/types/mod.rs +27 -0
  66. data/vendor/liter-llm/src/types/models.rs +21 -0
  67. data/vendor/liter-llm/src/types/moderation.rs +80 -0
  68. data/vendor/liter-llm/src/types/ocr.rs +87 -0
  69. data/vendor/liter-llm/src/types/rerank.rs +46 -0
  70. data/vendor/liter-llm/src/types/responses.rs +55 -0
  71. data/vendor/liter-llm/src/types/search.rs +45 -0
  72. data/vendor/liter-llm/tests/contract.rs +332 -0
  73. data/vendor/liter-llm-ffi/Cargo.toml +30 -0
  74. data/vendor/liter-llm-ffi/build.rs +66 -0
  75. data/vendor/liter-llm-ffi/cbindgen.toml +60 -0
  76. data/vendor/liter-llm-ffi/liter_llm.h +850 -0
  77. data/vendor/liter-llm-ffi/src/lib.rs +2488 -0
  78. metadata +286 -0
@@ -0,0 +1,502 @@
1
+ //! Response caching middleware.
2
+ //!
3
+ //! [`CacheLayer`] wraps any [`Service<LlmRequest>`] and caches non-streaming
4
+ //! responses keyed by a hash of the serialised request. Only
5
+ //! [`LlmResponse::Chat`] and [`LlmResponse::Embed`] responses are cached;
6
+ //! streaming, model-list, and other response variants are passed through
7
+ //! uncached.
8
+ //!
9
+ //! The default backend is an in-memory LRU ([`InMemoryStore`]) with a
10
+ //! configurable maximum entry count and TTL. Implement the [`CacheStore`]
11
+ //! trait to plug in Redis, DynamoDB, or any other storage backend.
12
+
13
+ use std::collections::{HashMap, VecDeque};
14
+ use std::future::Future;
15
+ use std::hash::{DefaultHasher, Hash, Hasher};
16
+ use std::pin::Pin;
17
+ use std::sync::{Arc, RwLock};
18
+ use std::task::{Context, Poll};
19
+ use std::time::{Duration, Instant};
20
+
21
+ use serde::{Deserialize, Serialize};
22
+ use tower::{Layer, Service};
23
+
24
+ use super::types::{LlmRequest, LlmResponse};
25
+ use crate::client::BoxFuture;
26
+ use crate::error::{LiterLlmError, Result};
27
+ use crate::types::{ChatCompletionResponse, EmbeddingResponse};
28
+
29
+ // ---- Config ----------------------------------------------------------------
30
+
31
+ /// Storage backend for the response cache.
32
+ #[derive(Debug, Clone, Default)]
33
+ pub enum CacheBackend {
34
+ /// In-memory LRU cache (default). No external dependencies.
35
+ #[default]
36
+ Memory,
37
+ /// OpenDAL-backed storage. Supports 40+ backends (S3, Redis, GCS, local FS, etc.).
38
+ #[cfg(feature = "opendal-cache")]
39
+ OpenDal {
40
+ /// OpenDAL scheme name (e.g. "s3", "redis", "fs", "gcs", "azblob").
41
+ scheme: String,
42
+ /// Backend-specific configuration as key-value pairs passed to OpenDAL.
43
+ config: std::collections::HashMap<String, String>,
44
+ },
45
+ }
46
+
47
+ /// Configuration for the response cache.
48
+ #[derive(Debug, Clone)]
49
+ pub struct CacheConfig {
50
+ /// Maximum number of cached entries.
51
+ pub max_entries: usize,
52
+ /// Time-to-live for each cached entry.
53
+ pub ttl: Duration,
54
+ /// Storage backend to use.
55
+ pub backend: CacheBackend,
56
+ }
57
+
58
+ impl Default for CacheConfig {
59
+ fn default() -> Self {
60
+ Self {
61
+ max_entries: 256,
62
+ ttl: Duration::from_secs(300),
63
+ backend: CacheBackend::Memory,
64
+ }
65
+ }
66
+ }
67
+
68
+ // ---- Cached response -------------------------------------------------------
69
+
70
+ /// The subset of [`LlmResponse`] variants that can be cached.
71
+ ///
72
+ /// Streaming responses are not cacheable because they are consumed once.
73
+ ///
74
+ /// # Performance note
75
+ ///
76
+ /// `CachedResponse` is `Clone`d on every cache hit (to return a value while
77
+ /// keeping the cache entry) and when storing (the response inner is cloned to
78
+ /// build a `CachedResponse` while the original `LlmResponse` is returned to
79
+ /// the caller). For typical chat/embedding payloads this is inexpensive, but
80
+ /// callers caching very large responses should be aware of the allocation
81
+ /// cost. An `Arc<CachedResponse>` wrapper was considered but rejected
82
+ /// because it would complicate the [`CacheStore`] trait's serialisation
83
+ /// contract (`Serialize`/`Deserialize` on `Arc` requires special handling)
84
+ /// and would not benefit external store implementations (Redis, DynamoDB)
85
+ /// that must serialise on every read anyway.
86
+ #[derive(Clone, Serialize, Deserialize)]
87
+ pub enum CachedResponse {
88
+ /// A cached chat completion response.
89
+ Chat(ChatCompletionResponse),
90
+ /// A cached embedding response.
91
+ Embed(EmbeddingResponse),
92
+ }
93
+
94
+ impl CachedResponse {
95
+ /// Convert this cached response back into the full [`LlmResponse`] enum.
96
+ pub fn into_llm_response(self) -> LlmResponse {
97
+ match self {
98
+ Self::Chat(r) => LlmResponse::Chat(r),
99
+ Self::Embed(r) => LlmResponse::Embed(r),
100
+ }
101
+ }
102
+ }
103
+
104
+ // ---- CacheStore trait ------------------------------------------------------
105
+
106
+ /// Pluggable cache backend.
107
+ ///
108
+ /// Implement this trait to provide a custom storage layer (Redis, DynamoDB,
109
+ /// disk, etc.). The default in-memory implementation is [`InMemoryStore`].
110
+ ///
111
+ /// All methods return pinned, boxed futures so the trait is object-safe and
112
+ /// can be used behind `Arc<dyn CacheStore>`.
113
+ pub trait CacheStore: Send + Sync + 'static {
114
+ /// Look up a cached response by its hash key.
115
+ ///
116
+ /// `request_body` is the serialized request used to guard against 64-bit
117
+ /// hash collisions — implementations should compare it against the stored
118
+ /// body before returning a hit.
119
+ fn get(&self, key: u64, request_body: &str) -> Pin<Box<dyn Future<Output = Option<CachedResponse>> + Send + '_>>;
120
+
121
+ /// Store a response under the given hash key.
122
+ fn put(
123
+ &self,
124
+ key: u64,
125
+ request_body: String,
126
+ response: CachedResponse,
127
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
128
+
129
+ /// Remove an entry by key (e.g. on expiry).
130
+ fn remove(&self, key: u64) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
131
+ }
132
+
133
+ // ---- In-memory store -------------------------------------------------------
134
+
135
+ /// A cached response with its insertion timestamp and the serialized request
136
+ /// body used to verify lookups (guarding against 64-bit hash collisions).
137
+ #[derive(Clone)]
138
+ struct CacheEntry {
139
+ /// Serialized request body — compared on lookup to avoid collision false positives.
140
+ request_body: String,
141
+ response: CachedResponse,
142
+ inserted_at: Instant,
143
+ }
144
+
145
+ struct InnerCache {
146
+ map: HashMap<u64, CacheEntry>,
147
+ /// Keys in insertion order (front = oldest).
148
+ order: VecDeque<u64>,
149
+ max_entries: usize,
150
+ ttl: Duration,
151
+ }
152
+
153
+ impl InnerCache {
154
+ fn new(config: &CacheConfig) -> Self {
155
+ Self {
156
+ map: HashMap::new(),
157
+ order: VecDeque::new(),
158
+ max_entries: config.max_entries,
159
+ ttl: config.ttl,
160
+ }
161
+ }
162
+
163
+ /// Try to read a cached entry without needing mutable access.
164
+ ///
165
+ /// Returns `Some(response)` when the entry exists, matches the serialized
166
+ /// request body, and has not expired. Returns `None` on miss.
167
+ fn get_if_valid(&self, key: u64, request_body: &str) -> Option<CachedResponse> {
168
+ let entry = self.map.get(&key)?;
169
+ if entry.request_body != request_body {
170
+ // Hash collision — different request mapped to the same key.
171
+ return None;
172
+ }
173
+ if entry.inserted_at.elapsed() > self.ttl {
174
+ return None;
175
+ }
176
+ // Clone is required: the cache retains ownership while the caller
177
+ // receives an independent copy. See `CachedResponse` doc comment for
178
+ // performance discussion.
179
+ Some(entry.response.clone())
180
+ }
181
+
182
+ /// Return `true` if the entry for `key` exists and is expired.
183
+ fn is_expired(&self, key: u64) -> bool {
184
+ self.map.get(&key).is_some_and(|e| e.inserted_at.elapsed() > self.ttl)
185
+ }
186
+
187
+ /// Remove an expired entry (eviction under write lock).
188
+ fn remove_expired(&mut self, key: u64) {
189
+ if self.map.get(&key).is_some_and(|e| e.inserted_at.elapsed() > self.ttl) {
190
+ self.map.remove(&key);
191
+ // Lazily cleaned from `order` during eviction.
192
+ }
193
+ }
194
+
195
+ fn insert(&mut self, key: u64, request_body: String, response: CachedResponse) {
196
+ // Remove duplicate from the LRU deque before reinserting so entries
197
+ // are not counted twice toward the capacity limit.
198
+ if self.map.contains_key(&key) {
199
+ self.order.retain(|k| *k != key);
200
+ }
201
+
202
+ // Evict oldest entries if at capacity.
203
+ while self.map.len() >= self.max_entries {
204
+ if let Some(oldest_key) = self.order.pop_front() {
205
+ self.map.remove(&oldest_key);
206
+ } else {
207
+ break;
208
+ }
209
+ }
210
+
211
+ self.map.insert(
212
+ key,
213
+ CacheEntry {
214
+ request_body,
215
+ response,
216
+ inserted_at: Instant::now(),
217
+ },
218
+ );
219
+ self.order.push_back(key);
220
+ }
221
+ }
222
+
223
+ /// In-memory LRU cache store.
224
+ ///
225
+ /// This is the default [`CacheStore`] backend used by [`CacheLayer::new`].
226
+ /// It uses a [`HashMap`] with a [`VecDeque`] for LRU eviction order.
227
+ pub struct InMemoryStore {
228
+ inner: RwLock<InnerCache>,
229
+ }
230
+
231
+ impl InMemoryStore {
232
+ /// Create a new in-memory store with the given configuration.
233
+ #[must_use]
234
+ pub fn new(config: &CacheConfig) -> Self {
235
+ Self {
236
+ inner: RwLock::new(InnerCache::new(config)),
237
+ }
238
+ }
239
+ }
240
+
241
+ impl CacheStore for InMemoryStore {
242
+ fn get(&self, key: u64, request_body: &str) -> Pin<Box<dyn Future<Output = Option<CachedResponse>> + Send + '_>> {
243
+ // Perform all synchronous work eagerly, then wrap result in a ready
244
+ // future. This avoids capturing `request_body` in an async block
245
+ // (which would require tying its lifetime to the future).
246
+ let result = self.inner.read().ok().and_then(|cache| {
247
+ let hit = cache.get_if_valid(key, request_body);
248
+ let expired = hit.is_none() && cache.is_expired(key);
249
+ drop(cache);
250
+ if expired && let Ok(mut w) = self.inner.write() {
251
+ w.remove_expired(key);
252
+ }
253
+ hit
254
+ });
255
+ Box::pin(std::future::ready(result))
256
+ }
257
+
258
+ fn put(
259
+ &self,
260
+ key: u64,
261
+ request_body: String,
262
+ response: CachedResponse,
263
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
264
+ if let Ok(mut cache) = self.inner.write() {
265
+ cache.insert(key, request_body, response);
266
+ }
267
+ Box::pin(std::future::ready(()))
268
+ }
269
+
270
+ fn remove(&self, key: u64) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
271
+ if let Ok(mut cache) = self.inner.write() {
272
+ cache.map.remove(&key);
273
+ }
274
+ Box::pin(std::future::ready(()))
275
+ }
276
+ }
277
+
278
+ // ---- Layer -----------------------------------------------------------------
279
+
280
+ /// Tower [`Layer`] that caches non-streaming LLM responses.
281
+ pub struct CacheLayer {
282
+ store: Arc<dyn CacheStore>,
283
+ }
284
+
285
+ impl CacheLayer {
286
+ /// Create a new cache layer with the given configuration.
287
+ ///
288
+ /// Uses the default [`InMemoryStore`] backend.
289
+ #[must_use]
290
+ pub fn new(config: CacheConfig) -> Self {
291
+ Self {
292
+ store: Arc::new(InMemoryStore::new(&config)),
293
+ }
294
+ }
295
+
296
+ /// Create a new cache layer with a custom [`CacheStore`] backend.
297
+ #[must_use]
298
+ pub fn with_store(store: Arc<dyn CacheStore>) -> Self {
299
+ Self { store }
300
+ }
301
+ }
302
+
303
+ impl<S> Layer<S> for CacheLayer {
304
+ type Service = CacheService<S>;
305
+
306
+ fn layer(&self, inner: S) -> Self::Service {
307
+ CacheService {
308
+ inner,
309
+ store: Arc::clone(&self.store),
310
+ }
311
+ }
312
+ }
313
+
314
+ // ---- Service ---------------------------------------------------------------
315
+
316
+ /// Tower service produced by [`CacheLayer`].
317
+ pub struct CacheService<S> {
318
+ inner: S,
319
+ store: Arc<dyn CacheStore>,
320
+ }
321
+
322
+ impl<S: Clone> Clone for CacheService<S> {
323
+ fn clone(&self) -> Self {
324
+ Self {
325
+ inner: self.inner.clone(),
326
+ store: Arc::clone(&self.store),
327
+ }
328
+ }
329
+ }
330
+
331
+ /// Compute a cache key and serialized body from the request.
332
+ ///
333
+ /// Only `Chat` and `Embed` requests are cacheable. Returns `None` for all
334
+ /// other request variants (streaming, `ListModels`, image, audio, etc.).
335
+ ///
336
+ /// The returned tuple contains the 64-bit hash key and the serialized request
337
+ /// body. The body is stored alongside the cached response so lookups can
338
+ /// verify against hash collisions.
339
+ fn cache_key(req: &LlmRequest) -> Option<(u64, String)> {
340
+ let json = match req {
341
+ LlmRequest::Chat(r) => serde_json::to_string(r).ok()?,
342
+ LlmRequest::Embed(r) => serde_json::to_string(r).ok()?,
343
+ // Not cacheable.
344
+ _ => return None,
345
+ };
346
+
347
+ let mut hasher = DefaultHasher::new();
348
+ json.hash(&mut hasher);
349
+ Some((hasher.finish(), json))
350
+ }
351
+
352
+ impl<S> Service<LlmRequest> for CacheService<S>
353
+ where
354
+ S: Service<LlmRequest, Response = LlmResponse, Error = LiterLlmError> + Send + 'static,
355
+ S::Future: Send + 'static,
356
+ {
357
+ type Response = LlmResponse;
358
+ type Error = LiterLlmError;
359
+ type Future = BoxFuture<'static, LlmResponse>;
360
+
361
+ fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<()>> {
362
+ self.inner.poll_ready(cx)
363
+ }
364
+
365
+ fn call(&mut self, req: LlmRequest) -> Self::Future {
366
+ let key_and_body = cache_key(&req);
367
+
368
+ let store = Arc::clone(&self.store);
369
+ let fut = self.inner.call(req);
370
+
371
+ Box::pin(async move {
372
+ // Check cache for a hit.
373
+ if let Some((k, ref body)) = key_and_body
374
+ && let Some(cached) = store.get(k, body).await
375
+ {
376
+ return Ok(cached.into_llm_response());
377
+ }
378
+
379
+ let resp = fut.await?;
380
+
381
+ // Store cacheable responses.
382
+ if let Some((k, body)) = key_and_body {
383
+ let cached = match &resp {
384
+ LlmResponse::Chat(r) => Some(CachedResponse::Chat(r.clone())),
385
+ LlmResponse::Embed(r) => Some(CachedResponse::Embed(r.clone())),
386
+ _ => None,
387
+ };
388
+ if let Some(cached) = cached {
389
+ store.put(k, body, cached).await;
390
+ }
391
+ }
392
+
393
+ Ok(resp)
394
+ })
395
+ }
396
+ }
397
+
398
+ // ---- Tests -----------------------------------------------------------------
399
+
400
+ #[cfg(test)]
401
+ mod tests {
402
+ use std::sync::atomic::Ordering;
403
+
404
+ use tower::{Layer as _, Service as _};
405
+
406
+ use super::*;
407
+ use crate::tower::service::LlmService;
408
+ use crate::tower::tests_common::{MockClient, chat_req};
409
+ use crate::tower::types::LlmRequest;
410
+
411
+ #[tokio::test]
412
+ async fn cache_returns_cached_response_on_second_call() {
413
+ let config = CacheConfig {
414
+ backend: CacheBackend::default(),
415
+ max_entries: 10,
416
+ ttl: Duration::from_secs(60),
417
+ };
418
+ let layer = CacheLayer::new(config);
419
+ let client = MockClient::ok();
420
+ let call_count = Arc::clone(&client.call_count);
421
+ let inner = LlmService::new(client);
422
+ let mut svc = layer.layer(inner);
423
+
424
+ // First call — cache miss.
425
+ svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await.unwrap();
426
+ assert_eq!(call_count.load(Ordering::SeqCst), 1);
427
+
428
+ // Second call — cache hit.
429
+ svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await.unwrap();
430
+ assert_eq!(call_count.load(Ordering::SeqCst), 1, "second call should hit cache");
431
+ }
432
+
433
+ #[tokio::test]
434
+ async fn cache_does_not_cache_streaming_requests() {
435
+ let config = CacheConfig {
436
+ backend: CacheBackend::default(),
437
+ max_entries: 10,
438
+ ttl: Duration::from_secs(60),
439
+ };
440
+ let layer = CacheLayer::new(config);
441
+ let client = MockClient::ok();
442
+ let call_count = Arc::clone(&client.call_count);
443
+ let inner = LlmService::new(client);
444
+ let mut svc = layer.layer(inner);
445
+
446
+ svc.call(LlmRequest::ChatStream(chat_req("gpt-4"))).await.unwrap();
447
+ svc.call(LlmRequest::ChatStream(chat_req("gpt-4"))).await.unwrap();
448
+ assert_eq!(call_count.load(Ordering::SeqCst), 2, "streaming should not be cached");
449
+ }
450
+
451
+ #[tokio::test]
452
+ async fn cache_evicts_oldest_when_full() {
453
+ let config = CacheConfig {
454
+ backend: CacheBackend::default(),
455
+ max_entries: 1,
456
+ ttl: Duration::from_secs(60),
457
+ };
458
+ let layer = CacheLayer::new(config);
459
+ let client = MockClient::ok();
460
+ let call_count = Arc::clone(&client.call_count);
461
+ let inner = LlmService::new(client);
462
+ let mut svc = layer.layer(inner);
463
+
464
+ // Fill cache with model-a.
465
+ svc.call(LlmRequest::Chat(chat_req("model-a"))).await.unwrap();
466
+ assert_eq!(call_count.load(Ordering::SeqCst), 1);
467
+
468
+ // Insert model-b, evicting model-a.
469
+ svc.call(LlmRequest::Chat(chat_req("model-b"))).await.unwrap();
470
+ assert_eq!(call_count.load(Ordering::SeqCst), 2);
471
+
472
+ // model-a should be evicted — cache miss.
473
+ svc.call(LlmRequest::Chat(chat_req("model-a"))).await.unwrap();
474
+ assert_eq!(
475
+ call_count.load(Ordering::SeqCst),
476
+ 3,
477
+ "evicted entry should be a cache miss"
478
+ );
479
+ }
480
+
481
+ #[tokio::test]
482
+ async fn cache_different_requests_have_different_keys() {
483
+ let config = CacheConfig {
484
+ backend: CacheBackend::default(),
485
+ max_entries: 10,
486
+ ttl: Duration::from_secs(60),
487
+ };
488
+ let layer = CacheLayer::new(config);
489
+ let client = MockClient::ok();
490
+ let call_count = Arc::clone(&client.call_count);
491
+ let inner = LlmService::new(client);
492
+ let mut svc = layer.layer(inner);
493
+
494
+ svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await.unwrap();
495
+ svc.call(LlmRequest::Chat(chat_req("gpt-3.5-turbo"))).await.unwrap();
496
+ assert_eq!(
497
+ call_count.load(Ordering::SeqCst),
498
+ 2,
499
+ "different models should be cache misses"
500
+ );
501
+ }
502
+ }