api_ollama 0.2.0

Ollama local LLM runtime API client for HTTP communication.
Documentation
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! Cached Content functionality for the Ollama API client
//!
//! This module provides advanced content caching capabilities including:
//! - Intelligent content caching for repeated queries
//! - Cache invalidation and management operations
//! - Performance optimization through content-aware caching
//! - Memory-efficient storage with intelligent eviction
//!
//! All functionality follows the "Thin Client, Rich API" governing principle,
//! providing explicit control with transparent cache management operations.

use serde::{ Serialize, Deserialize };
use std::collections::HashMap;
use std::time::{ Duration, Instant };

/// Request structure for caching content operations
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct CachedContentRequest
{
  /// Unique identifier for the content to cache
  pub content_id : String,
  /// Model name associated with this content
  pub model : String,
  /// Content to be cached
  pub content : String,
  /// Content type for intelligent caching decisions
  pub content_type : ContentType,
  /// Custom cache TTL for this content
  pub ttl : Option< Duration >,
  /// Cache priority level
  pub priority : CachePriority,
  /// Additional metadata for cache optimization
  pub metadata : Option< serde_json::Value >,
}

/// Response structure for cached content operations
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct CachedContentResponse
{
  /// Unique identifier for the cached content
  pub content_id : String,
  /// Cached content data
  pub content : String,
  /// Model name associated with the content
  pub model : String,
  /// Content type
  pub content_type : ContentType,
  /// When the content was cached
  pub cached_at : u64, // Unix timestamp
  /// When the content expires (if applicable)
  pub expires_at : Option< u64 >,
  /// Number of times this content has been accessed
  pub access_count : u64,
  /// Cache hit performance metrics
  pub performance_metrics : Option< CachePerformanceMetrics >,
  /// Additional cached metadata
  pub metadata : Option< serde_json::Value >,
}

/// Content types for intelligent caching decisions
#[ derive( Debug, Clone, PartialEq, Serialize, Deserialize ) ]
pub enum ContentType
{
  /// Chat conversation content
  ChatConversation,
  /// Model response content
  ModelResponse,
  /// System instruction content
  SystemInstruction,
  /// User prompt content
  UserPrompt,
  /// Function call result content
  FunctionCallResult,
  /// Embeddings data content
  EmbeddingsData,
  /// Generated code content
  GeneratedCode,
  /// Document or text content
  DocumentContent,
  /// Custom content type
  Custom( String ),
}

/// Cache priority levels for intelligent management
#[ derive( Debug, Clone, PartialEq, Serialize, Deserialize ) ]
pub enum CachePriority
{
  /// Low priority - first to be evicted
  Low,
  /// Normal priority - standard caching behavior
  Normal,
  /// High priority - kept longer in cache
  High,
  /// Critical priority - only evicted when absolutely necessary
  Critical,
}

/// Configuration for content caching behavior
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ContentCacheConfig
{
  /// Maximum number of cached content items
  max_content_items : usize,
  /// Default TTL for cached content
  default_ttl : Duration,
  /// Maximum size per content item (bytes)
  max_content_size : usize,
  /// Total memory limit for cache (bytes)
  memory_limit : usize,
  /// Enable intelligent cache management
  intelligent_management : bool,
  /// Auto-cleanup interval
  cleanup_interval : Duration,
  /// Performance tracking enabled
  performance_tracking : bool,
}

/// Request structure for cache invalidation operations
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct CacheInvalidationRequest
{
  /// Specific content IDs to invalidate (if any)
  pub content_ids : Option< Vec< String > >,
  /// Model name to invalidate all content for (if any)
  pub model : Option< String >,
  /// Content type to invalidate (if any)
  pub content_type : Option< ContentType >,
  /// Invalidate content older than this timestamp
  pub older_than : Option< u64 >,
  /// Priority levels to invalidate
  pub priorities : Option< Vec< CachePriority > >,
  /// Force invalidation (ignore critical priority)
  pub force : bool,
}

/// Response structure for cache invalidation operations
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct CacheInvalidationResponse
{
  /// Number of content items invalidated
  pub invalidated_count : u64,
  /// Content IDs that were invalidated
  pub invalidated_ids : Vec< String >,
  /// Total memory freed (bytes)
  pub memory_freed : usize,
  /// Operation duration in milliseconds
  pub duration_ms : u64,
  /// Whether all requested invalidations succeeded
  pub success : bool,
  /// Error messages (if any)
  pub errors : Vec< String >,
}

/// Performance metrics for cache operations
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct CachePerformanceMetrics
{
  /// Cache hit ratio (0.0 to 1.0)
  pub hit_ratio : f64,
  /// Average retrieval time in microseconds
  pub avg_retrieval_time_us : u64,
  /// Average storage time in microseconds
  pub avg_storage_time_us : u64,
  /// Memory usage efficiency (0.0 to 1.0)
  pub memory_efficiency : f64,
  /// Cache pressure level (0.0 to 1.0)
  pub cache_pressure : f64,
  /// Number of evictions in current session
  pub evictions : u64,
}

/// Intelligent cache manager for advanced caching strategies
#[ derive( Debug, Clone ) ]
pub struct IntelligentCacheManager
{
  config : ContentCacheConfig,
  content_store : HashMap<  String, CachedContentResponse  >,
  access_patterns : HashMap<  String, AccessPattern  >,
  performance_metrics : CachePerformanceMetrics,
  #[ allow(dead_code) ]
  last_cleanup : Instant,
}

/// Access pattern tracking for intelligent cache decisions
#[ derive( Debug, Clone ) ]
struct AccessPattern
{
  access_count : u64,
  last_accessed : Instant,
  access_frequency : f64, // Accesses per hour
  #[ allow(dead_code) ]
  content_type : ContentType,
  priority : CachePriority,
}

impl CachedContentRequest
{
  /// Create a new cached content request
  #[ inline ]
  #[ must_use ]
  pub fn new( content_id : String, model : String, content : String, content_type : ContentType ) -> Self
  {
    Self
    {
      content_id,
      model,
      content,
      content_type,
      ttl : None,
      priority : CachePriority::Normal,
      metadata : None,
    }
  }

  /// Set the cache TTL
  #[ inline ]
  #[ must_use ]
  pub fn with_ttl( mut self, ttl : Duration ) -> Self
  {
    self.ttl = Some( ttl );
    self
  }

  /// Set the cache priority
  #[ inline ]
  #[ must_use ]
  pub fn with_priority( mut self, priority : CachePriority ) -> Self
  {
    self.priority = priority;
    self
  }

  /// Set metadata
  #[ inline ]
  #[ must_use ]
  pub fn with_metadata( mut self, metadata : serde_json::Value ) -> Self
  {
    self.metadata = Some( metadata );
    self
  }

  /// Estimate content size in bytes
  #[ inline ]
  #[ must_use ]
  pub fn estimate_size( &self ) -> usize
  {
    self.content_id.len() +
    self.model.len() +
    self.content.len() +
    std ::mem::size_of::< ContentType >() +
    std ::mem::size_of::< CachePriority >() +
    self.metadata.as_ref().map_or( 0, | m | m.to_string().len() )
  }
}

impl ContentType
{
  /// Get the default TTL for this content type
  #[ inline ]
  #[ must_use ]
  pub fn default_ttl( &self ) -> Duration
  {
    match self
    {
      ContentType::ChatConversation => Duration::from_secs( 3600 ), // 1 hour
      ContentType::ModelResponse => Duration::from_secs( 1800 ), // 30 minutes
      ContentType::SystemInstruction => Duration::from_secs( 7200 ), // 2 hours
      ContentType::UserPrompt => Duration::from_secs( 1200 ), // 20 minutes
      ContentType::FunctionCallResult => Duration::from_secs( 900 ), // 15 minutes
      ContentType::EmbeddingsData => Duration::from_secs( 14400 ), // 4 hours
      ContentType::GeneratedCode => Duration::from_secs( 2400 ), // 40 minutes
      ContentType::DocumentContent => Duration::from_secs( 10800 ), // 3 hours
      ContentType::Custom( _ ) => Duration::from_secs( 1800 ), // 30 minutes default
    }
  }

  /// Get the cache priority for this content type
  #[ inline ]
  #[ must_use ]
  pub fn default_priority( &self ) -> CachePriority
  {
    match self
    {
      ContentType::SystemInstruction => CachePriority::High,
      ContentType::EmbeddingsData => CachePriority::High,
      ContentType::DocumentContent => CachePriority::Normal,
      ContentType::GeneratedCode => CachePriority::Normal,
      ContentType::ChatConversation => CachePriority::Normal,
      ContentType::ModelResponse => CachePriority::Low,
      ContentType::UserPrompt => CachePriority::Low,
      ContentType::FunctionCallResult => CachePriority::Normal,
      ContentType::Custom( _ ) => CachePriority::Normal,
    }
  }
}

impl CachePriority
{
  /// Get the eviction weight (lower values are evicted first)
  #[ inline ]
  #[ must_use ]
  pub fn eviction_weight( &self ) -> u32
  {
    match self
    {
      CachePriority::Low => 1,
      CachePriority::Normal => 10,
      CachePriority::High => 100,
      CachePriority::Critical => 1000,
    }
  }
}

impl ContentCacheConfig
{
  /// Create a new content cache configuration with defaults
  #[ inline ]
  #[ must_use ]
  pub fn new() -> Self
  {
    Self
    {
      max_content_items : 1000,
      default_ttl : Duration::from_secs( 1800 ), // 30 minutes
      max_content_size : 1024 * 1024, // 1MB per item
      memory_limit : 100 * 1024 * 1024, // 100MB total
      intelligent_management : true,
      cleanup_interval : Duration::from_secs( 300 ), // 5 minutes
      performance_tracking : true,
    }
  }

  /// Set maximum content items
  #[ inline ]
  #[ must_use ]
  pub fn with_max_items( mut self, max_items : usize ) -> Self
  {
    self.max_content_items = max_items;
    self
  }

  /// Set default TTL
  #[ inline ]
  #[ must_use ]
  pub fn with_default_ttl( mut self, ttl : Duration ) -> Self
  {
    self.default_ttl = ttl;
    self
  }

  /// Set memory limit
  #[ inline ]
  #[ must_use ]
  pub fn with_memory_limit( mut self, limit : usize ) -> Self
  {
    self.memory_limit = limit;
    self
  }

  /// Enable or disable intelligent management
  #[ inline ]
  #[ must_use ]
  pub fn with_intelligent_management( mut self, enabled : bool ) -> Self
  {
    self.intelligent_management = enabled;
    self
  }

  /// Set cleanup interval
  #[ inline ]
  #[ must_use ]
  pub fn with_cleanup_interval( mut self, interval : Duration ) -> Self
  {
    self.cleanup_interval = interval;
    self
  }

  /// Getters for configuration values
  #[ inline ]
  #[ must_use ]
  pub fn max_content_items( &self ) -> usize { self.max_content_items }

  /// Get the default TTL for cached content
  #[ inline ]
  #[ must_use ]
  pub fn default_ttl( &self ) -> Duration { self.default_ttl }

  /// Get the maximum content size for cached items
  #[ inline ]
  #[ must_use ]
  pub fn max_content_size( &self ) -> usize { self.max_content_size }

  /// Get the memory limit for the cache
  #[ inline ]
  #[ must_use ]
  pub fn memory_limit( &self ) -> usize { self.memory_limit }

  /// Check if intelligent cache management is enabled
  #[ inline ]
  #[ must_use ]
  pub fn intelligent_management( &self ) -> bool { self.intelligent_management }

  /// Get the cleanup interval for the cache
  #[ inline ]
  #[ must_use ]
  pub fn cleanup_interval( &self ) -> Duration { self.cleanup_interval }

  /// Check if performance tracking is enabled
  #[ inline ]
  #[ must_use ]
  pub fn performance_tracking( &self ) -> bool { self.performance_tracking }
}

impl Default for ContentCacheConfig
{
  fn default() -> Self
  {
    Self::new()
  }
}

impl IntelligentCacheManager
{
  /// Create a new intelligent cache manager
  #[ inline ]
  #[ must_use ]
  pub fn new( config : ContentCacheConfig ) -> Self
  {
    Self
    {
      config,
      content_store : HashMap::new(),
      access_patterns : HashMap::new(),
      performance_metrics : CachePerformanceMetrics
      {
        hit_ratio : 0.0,
        avg_retrieval_time_us : 0,
        avg_storage_time_us : 0,
        memory_efficiency : 1.0,
        cache_pressure : 0.0,
        evictions : 0,
      },
      last_cleanup : Instant::now(),
    }
  }

  /// Store content in the cache
  #[ inline ]
  pub fn store_content( &mut self, request : CachedContentRequest ) -> Result< (), String >
  {
    let start_time = Instant::now();

    // Check content size limits
    let content_size = request.estimate_size();
    if content_size > self.config.max_content_size
    {
      return Err( format!( "Content size {} exceeds limit {}", content_size, self.config.max_content_size ) );
    }

    // Check if we need to make room
    if self.needs_eviction( content_size )
    {
      self.intelligent_eviction( content_size )?;
    }

    // Create cached content response
    let cached_content = CachedContentResponse
    {
      content_id : request.content_id.clone(),
      content : request.content,
      model : request.model,
      content_type : request.content_type.clone(),
      cached_at : std::time::SystemTime::now().duration_since( std::time::UNIX_EPOCH ).unwrap().as_secs(),
      expires_at : request.ttl.map( | ttl |
        std ::time::SystemTime::now().duration_since( std::time::UNIX_EPOCH ).unwrap().as_secs() + ttl.as_secs()
      ),
      access_count : 0,
      performance_metrics : None,
      metadata : request.metadata,
    };

    // Store content
    self.content_store.insert( request.content_id.clone(), cached_content );

    // Update access patterns
    self.access_patterns.insert( request.content_id, AccessPattern
    {
      access_count : 0,
      last_accessed : Instant::now(),
      access_frequency : 0.0,
      content_type : request.content_type,
      priority : request.priority,
    } );

    // Update performance metrics
    self.performance_metrics.avg_storage_time_us = start_time.elapsed().as_micros() as u64;

    Ok( () )
  }

  /// Retrieve content from the cache
  #[ inline ]
  pub fn retrieve_content( &mut self, content_id : &str ) -> Option< CachedContentResponse >
  {
    let start_time = Instant::now();

    if let Some( mut content ) = self.content_store.get( content_id ).cloned()
    {
      // Check if content has expired
      if let Some( expires_at ) = content.expires_at
      {
        let now = std::time::SystemTime::now().duration_since( std::time::UNIX_EPOCH ).unwrap().as_secs();
        if now > expires_at
        {
          // Content expired, remove it
          self.content_store.remove( content_id );
          self.access_patterns.remove( content_id );
          return None;
        }
      }

      // Update access patterns
      if let Some( pattern ) = self.access_patterns.get_mut( content_id )
      {
        pattern.access_count += 1;
        pattern.last_accessed = Instant::now();

        // Calculate access frequency (accesses per hour)
        let hours_since_first_access = pattern.last_accessed.duration_since( Instant::now() - Duration::from_secs( 3600 ) ).as_secs_f64() / 3600.0;
        if hours_since_first_access > 0.0
        {
          pattern.access_frequency = pattern.access_count as f64 / hours_since_first_access;
        }
      }

      // Update content access count
      content.access_count += 1;
      self.content_store.insert( content_id.to_string(), content.clone() );

      // Update performance metrics
      self.performance_metrics.avg_retrieval_time_us = start_time.elapsed().as_micros() as u64;

      Some( content )
    }
    else
    {
      None
    }
  }

  /// Invalidate content based on criteria
  #[ inline ]
  pub fn invalidate_content( &mut self, request : CacheInvalidationRequest ) -> CacheInvalidationResponse
  {
    let start_time = Instant::now();
    let mut invalidated_ids = Vec::new();
    let mut memory_freed = 0usize;
    let mut errors = Vec::new();

    // Collect IDs to invalidate
    let mut ids_to_remove = Vec::new();

    for ( content_id, content ) in &self.content_store
    {
      let mut should_invalidate = false;

      // Check specific content IDs
      if let Some( ref target_ids ) = request.content_ids
      {
        if target_ids.contains( content_id )
        {
          should_invalidate = true;
        }
      }

      // Check model name
      if let Some( ref target_model ) = request.model
      {
        if content.model == *target_model
        {
          should_invalidate = true;
        }
      }

      // Check content type
      if let Some( ref target_type ) = request.content_type
      {
        if content.content_type == *target_type
        {
          should_invalidate = true;
        }
      }

      // Check age
      if let Some( older_than ) = request.older_than
      {
        if content.cached_at < older_than
        {
          should_invalidate = true;
        }
      }

      // Check priority levels
      if let Some( ref target_priorities ) = request.priorities
      {
        if let Some( pattern ) = self.access_patterns.get( content_id )
        {
          if target_priorities.contains( &pattern.priority )
          {
            should_invalidate = true;
          }
        }
      }

      // Check force flag and critical priority
      if should_invalidate
      {
        if let Some( pattern ) = self.access_patterns.get( content_id )
        {
          if pattern.priority == CachePriority::Critical && !request.force
          {
            should_invalidate = false;
            errors.push( format!( "Cannot invalidate critical content '{}' without force flag", content_id ) );
          }
        }
      }

      if should_invalidate
      {
        ids_to_remove.push( content_id.clone() );
        memory_freed += content.content.len() + content_id.len() + content.model.len();
      }
    }

    // Remove invalidated content
    for content_id in &ids_to_remove
    {
      self.content_store.remove( content_id );
      self.access_patterns.remove( content_id );
      invalidated_ids.push( content_id.clone() );
    }

    CacheInvalidationResponse
    {
      invalidated_count : invalidated_ids.len() as u64,
      invalidated_ids,
      memory_freed,
      duration_ms : start_time.elapsed().as_millis() as u64,
      success : errors.is_empty(),
      errors,
    }
  }

  /// Get current performance metrics
  #[ inline ]
  #[ must_use ]
  pub fn performance_metrics( &self ) -> &CachePerformanceMetrics
  {
    &self.performance_metrics
  }

  /// Get cache utilization information
  #[ inline ]
  #[ must_use ]
  pub fn cache_utilization( &self ) -> ( usize, usize, f64 )
  {
    let current_items = self.content_store.len();
    let max_items = self.config.max_content_items;
    let utilization = current_items as f64 / max_items as f64;
    ( current_items, max_items, utilization )
  }

  /// Check if eviction is needed
  #[ inline ]
  #[ must_use ]
  fn needs_eviction( &self, additional_size : usize ) -> bool
  {
    let current_items = self.content_store.len();
    let current_memory = self.estimate_memory_usage();

    current_items >= self.config.max_content_items ||
    current_memory + additional_size > self.config.memory_limit
  }

  /// Perform intelligent eviction
  #[ inline ]
  fn intelligent_eviction( &mut self, space_needed : usize ) -> Result< (), String >
  {
    let mut eviction_candidates = Vec::new();

    // Score each item for eviction (higher score = more likely to evict)
    for ( content_id, _content ) in &self.content_store
    {
      if let Some( pattern ) = self.access_patterns.get( content_id )
      {
        let age_factor = pattern.last_accessed.elapsed().as_secs() as f64 / 3600.0; // Hours since last access
        let frequency_factor = 1.0 / ( pattern.access_frequency + 1.0 ); // Lower frequency = higher score
        let priority_factor = 1.0 / pattern.priority.eviction_weight() as f64; // Lower priority = higher score

        let eviction_score = age_factor * frequency_factor * priority_factor;

        eviction_candidates.push( ( content_id.clone(), eviction_score ) );
      }
    }

    // Sort by eviction score (highest first)
    eviction_candidates.sort_by( | a, b | b.1.partial_cmp( &a.1 ).unwrap() );

    // Evict items until we have enough space
    let mut freed_space = 0usize;
    let mut evicted_count = 0usize;

    for ( content_id, _score ) in eviction_candidates
    {
      if let Some( content ) = self.content_store.get( &content_id )
      {
        freed_space += content.content.len() + content_id.len() + content.model.len();
        self.content_store.remove( &content_id );
        self.access_patterns.remove( &content_id );
        evicted_count += 1;

        if freed_space >= space_needed
        {
          break;
        }
      }
    }

    // Update performance metrics
    self.performance_metrics.evictions += evicted_count as u64;

    if freed_space >= space_needed
    {
      Ok( () )
    }
    else
    {
      Err( format!( "Could not free enough space : needed {}, freed {}", space_needed, freed_space ) )
    }
  }

  /// Estimate current memory usage
  #[ inline ]
  #[ must_use ]
  fn estimate_memory_usage( &self ) -> usize
  {
    self.content_store.iter().map( | ( id, content ) |
      id.len() + content.content.len() + content.model.len() +
      std ::mem::size_of::< CachedContentResponse >()
    ).sum()
  }
}