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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Model tuning functionality for Ollama API client.

#[ cfg( feature = "model_tuning" ) ]
mod private
{
  use serde::{ Serialize, Deserialize };
  use core::time::Duration;
  use error_tools::untyped::Result;
  use std::collections::HashMap;

  // =====================================
  // Model Tuning Types
  // =====================================

  /// Status of a model tuning job
  #[ derive( Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize ) ]
  pub enum TuningJobStatus
  {
    /// Job is pending and waiting to start
    Pending,
    /// Job is currently running
    Running,
    /// Job is paused
    Paused,
    /// Job completed successfully
    Completed,
    /// Job was cancelled
    Cancelled,
    /// Job failed with an error
    Failed,
  }

  /// Fine-tuning methods available
  #[ derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize ) ]
  pub enum TuningMethod
  {
    /// Full fine-tuning of all parameters
    FullFineTuning,
    /// Low-Rank Adaptation (`LoRA`)
    LoRA,
    /// Adapter-based tuning
    Adapter,
    /// Prefix tuning
    PrefixTuning,
    /// Prompt tuning
    PromptTuning,
    /// P-tuning v2
    PTuningV2,
  }

  /// Training objectives for different tasks
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub enum TrainingObjective
  {
    /// Text generation objective
    TextGeneration
    {
      /// Maximum generation length
      max_length : usize,
      /// Temperature for sampling
      temperature : f32,
      /// Top-p nucleus sampling parameter
      top_p : f32,
    },
    /// Classification objective
    Classification
    {
      /// Number of classes
      num_classes : usize,
      /// Optional class weights for imbalanced data
      class_weights : Option< Vec< f32 > >,
    },
    /// Question answering objective
    QuestionAnswering
    {
      /// Maximum answer length
      max_answer_length : usize,
      /// Threshold for impossible answers
      impossible_answer_threshold : f32,
    },
    /// Named entity recognition
    NamedEntityRecognition
    {
      /// Entity types
      entity_types : Vec< String >,
      /// Use BIO tagging scheme
      use_bio_tagging : bool,
    },
  }

  /// Hyperparameters for model training
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct HyperParameters
  {
    /// Learning rate
    pub learning_rate : f32,
    /// Batch size
    pub batch_size : usize,
    /// Maximum number of training epochs
    pub max_epochs : usize,
    /// Warmup steps for learning rate scheduling
    pub warmup_steps : usize,
    /// Weight decay for regularization
    pub weight_decay : f32,
    /// Gradient clipping norm
    pub gradient_clip_norm : f32,
    /// `LoRA` rank (for `LoRA` tuning)
    pub lora_rank : Option< u32 >,
    /// `LoRA` alpha parameter
    pub lora_alpha : Option< f32 >,
    /// `LoRA` dropout rate
    pub lora_dropout : Option< f32 >,
    /// Target modules for `LoRA`
    pub target_modules : Vec< String >,
    /// Adapter size (for adapter tuning)
    pub adapter_size : Option< usize >,
    /// Adapter activation function
    pub adapter_activation : Option< String >,
  }

  /// Training progress information
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct TrainingProgress
  {
    /// Current epoch
    pub current_epoch : usize,
    /// Total epochs
    pub total_epochs : usize,
    /// Current step within epoch
    pub current_step : usize,
    /// Total steps per epoch
    pub steps_per_epoch : usize,
    /// Elapsed training time
    pub elapsed_time : Duration,
    /// Estimated remaining time
    pub estimated_remaining : Option< Duration >,
    /// Current training metrics
    pub metrics : HashMap<  String, f32  >,
    /// Validation metrics (if available)
    pub validation_metrics : Option< HashMap<  String, f32  > >,
  }

  /// Model checkpoint information
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct ModelCheckpoint
  {
    /// Checkpoint ID
    pub id : String,
    /// Step number at which checkpoint was created
    pub step : usize,
    /// Epoch number
    pub epoch : usize,
    /// Training loss at checkpoint
    pub training_loss : f32,
    /// Validation loss at checkpoint
    pub validation_loss : f32,
    /// Timestamp when checkpoint was created
    pub created_at : std::time::SystemTime,
    /// Checkpoint file size in bytes
    pub size_bytes : u64,
    /// Best checkpoint indicator
    pub is_best : bool,
  }

  /// Resource usage metrics during training
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct ResourceUsage
  {
    /// GPU memory used in MB
    pub gpu_memory_used_mb : u64,
    /// GPU utilization percentage
    pub gpu_utilization_percent : f32,
    /// CPU utilization percentage
    pub cpu_utilization_percent : f32,
    /// System memory used in MB
    pub memory_used_mb : u64,
    /// Disk I/O read in MB
    pub disk_io_read_mb : u64,
    /// Disk I/O write in MB
    pub disk_io_write_mb : u64,
    /// Network I/O read in MB
    pub network_io_read_mb : u64,
    /// Network I/O write in MB
    pub network_io_write_mb : u64,
  }

  /// Model evaluation metrics
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct ModelEvaluation
  {
    /// Perplexity score
    pub perplexity : f32,
    /// BLEU score for text generation
    pub bleu_score : f32,
    /// ROUGE scores
    pub rouge_scores : HashMap<  String, f32  >,
    /// Custom evaluation metrics
    pub custom_metrics : HashMap<  String, f32  >,
    /// Evaluation timestamp
    pub evaluated_at : std::time::SystemTime,
  }

  /// Model version information
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct ModelVersion
  {
    /// Version ID
    pub id : String,
    /// Version name
    pub name : String,
    /// Version description
    pub description : String,
    /// Base model name
    pub base_model : String,
    /// Tuning method used
    pub tuning_method : TuningMethod,
    /// Creation timestamp
    pub created_at : std::time::SystemTime,
    /// Model size in bytes
    pub size_bytes : u64,
    /// Performance metrics
    pub performance_metrics : HashMap<  String, f32  >,
  }

  /// Training data sample
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct TrainingSample
  {
    /// Input text
    pub input : String,
    /// Output text
    pub output : String,
    /// Optional metadata
    pub metadata : Option< HashMap<  String, serde_json::Value  > >,
  }

  /// Training data validation result
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct ValidationResult
  {
    /// Whether the data is valid
    pub is_valid : bool,
    /// Total number of samples
    pub total_samples : usize,
    /// Validation warnings
    pub warnings : Vec< String >,
    /// Validation errors
    pub errors : Vec< String >,
    /// Data statistics
    pub statistics : HashMap<  String, serde_json::Value  >,
  }

  /// Training data upload result
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct DataUploadResult
  {
    /// Data ID
    pub data_id : String,
    /// Size in bytes
    pub size_bytes : u64,
    /// Number of samples
    pub sample_count : usize,
    /// Upload timestamp
    pub uploaded_at : std::time::SystemTime,
  }

  /// Benchmark task result
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct BenchmarkTaskResult
  {
    /// Task accuracy score
    pub accuracy : f32,
    /// Average latency in milliseconds
    pub latency_ms : f32,
    /// Throughput in tokens per second
    pub throughput_tokens_per_sec : f32,
    /// Memory usage in MB
    pub memory_usage_mb : u64,
  }

  /// Benchmark results for multiple tasks
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct BenchmarkResults
  {
    /// Results for each benchmark task
    pub tasks : HashMap<  String, BenchmarkTaskResult  >,
    /// Overall benchmark score
    pub overall_score : f32,
    /// Benchmark timestamp
    pub benchmarked_at : std::time::SystemTime,
  }

  /// Model tuning configuration
  #[ derive( Debug, Clone, Serialize, Deserialize ) ]
  pub struct ModelTuningConfig
  {
    /// Base model name
    pub model_name : String,
    /// Tuning method
    pub tuning_method : TuningMethod,
    /// Training objective
    pub training_objective : TrainingObjective,
    /// Hyperparameters
    pub hyperparameters : HyperParameters,
    /// Validation split ratio
    pub validation_split : f32,
    /// Checkpoint frequency (steps)
    pub checkpoint_frequency : usize,
    /// Number of best checkpoints to keep
    pub keep_best_checkpoints : usize,
    /// Enable early stopping
    pub early_stopping : bool,
    /// Early stopping patience (epochs)
    pub early_stopping_patience : usize,
    /// Memory optimization settings
    pub memory_optimization : bool,
    /// Gradient checkpointing
    pub gradient_checkpointing : bool,
    /// Mixed precision training
    pub mixed_precision : bool,
    /// Version name for the resulting model
    pub version_name : Option< String >,
    /// Version description
    pub version_description : Option< String >,
  }

  /// Training data container
  #[ derive( Debug, Clone ) ]
  pub struct TrainingData
  {
    /// Training samples
    pub samples : Vec< TrainingSample >,
    /// Data format metadata
    pub metadata : HashMap<  String, serde_json::Value  >,
  }

  /// Data preprocessing utilities
  #[ derive( Debug ) ]
  pub struct DataPreprocessor
  {
    /// Tokenizer settings
    pub tokenizer_config : HashMap<  String, serde_json::Value  >,
    /// Normalization settings
    pub normalization_config : HashMap<  String, bool  >,
  }

  /// Model benchmark configuration
  #[ derive( Debug, Clone ) ]
  pub struct ModelBenchmark
  {
    /// Benchmark tasks to run
    pub tasks : Vec< String >,
    /// Test data size for each task
    pub test_data_size : usize,
    /// Benchmark configuration
    pub config : HashMap<  String, serde_json::Value  >,
  }

  /// Model tuning job
  #[ derive( Debug ) ]
  pub struct ModelTuningJob
  {
    /// Job ID
    pub id : String,
    /// Job configuration
    pub config : ModelTuningConfig,
    /// Training data
    pub training_data : TrainingData,
    /// Validation data
    pub validation_data : Option< TrainingData >,
    /// Current job status
    pub status : TuningJobStatus,
    /// Job creation timestamp
    pub created_at : std::time::SystemTime,
    /// Job start timestamp
    pub started_at : Option< std::time::SystemTime >,
    /// Job completion timestamp
    pub completed_at : Option< std::time::SystemTime >,
    /// Latest checkpoint ID
    pub latest_checkpoint_id : Option< String >,
    /// Current training progress
    pub progress : Option< TrainingProgress >,
    /// Resource usage metrics
    pub resource_usage : Option< ResourceUsage >,
  }

  /// Model tuning configuration builder
  #[ derive( Debug, Default ) ]
  pub struct ModelTuningConfigBuilder
  {
    model_name : Option< String >,
    tuning_method : Option< TuningMethod >,
  }

  // =====================================
  // Implementation blocks
  // =====================================

  impl ModelTuningConfig
  {
    /// Create a new configuration builder
    #[ inline ]
    pub fn builder() -> ModelTuningConfigBuilder
    {
      ModelTuningConfigBuilder::new()
    }

    /// Create with default values
    #[ inline ]
    #[ must_use ]
    pub fn default() -> Self
    {
      Self
      {
        model_name : "llama2".to_string(),
        tuning_method : TuningMethod::FullFineTuning,
        training_objective : TrainingObjective::TextGeneration
        {
          max_length : 512,
          temperature : 0.7,
          top_p : 0.9,
        },
        hyperparameters : HyperParameters::new(),
        validation_split : 0.1,
        checkpoint_frequency : 1000,
        keep_best_checkpoints : 3,
        early_stopping : true,
        early_stopping_patience : 5,
        memory_optimization : true,
        gradient_checkpointing : false,
        mixed_precision : false,
        version_name : None,
        version_description : None,
      }
    }

    /// Set model name
    #[ inline ]
    #[ must_use ]
    pub fn with_model_name( mut self, name : &str ) -> Self
    {
      self.model_name = name.to_string();
      self
    }
  }

  impl ModelTuningConfigBuilder
  {
    /// Create new builder
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self::default()
    }

    /// Set model name
    #[ inline ]
    #[ must_use ]
    pub fn model_name( mut self, name : &str ) -> Self
    {
      self.model_name = Some( name.to_string() );
      self
    }

    /// Set tuning method
    #[ inline ]
    #[ must_use ]
    pub fn tuning_method( mut self, method : TuningMethod ) -> Self
    {
      self.tuning_method = Some( method );
      self
    }

    /// Build the configuration
    #[ inline ]
    pub fn build( self ) -> Result< ModelTuningConfig >
    {
      Ok( ModelTuningConfig
      {
        model_name : self.model_name.unwrap_or( "llama2".to_string() ),
        tuning_method : self.tuning_method.unwrap_or( TuningMethod::FullFineTuning ),
        training_objective : TrainingObjective::TextGeneration
        {
          max_length : 512,
          temperature : 0.7,
          top_p : 0.9,
        },
        hyperparameters : HyperParameters::new(),
        validation_split : 0.1,
        checkpoint_frequency : 1000,
        keep_best_checkpoints : 3,
        early_stopping : true,
        early_stopping_patience : 5,
        memory_optimization : true,
        gradient_checkpointing : false,
        mixed_precision : false,
        version_name : None,
        version_description : None,
      } )
    }
  }

  impl TrainingData
  {
    /// Create new training data
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        samples : Vec::new(),
        metadata : HashMap::new(),
      }
    }

    /// Load from JSONL file
    #[ inline ]
    pub fn from_jsonl_file( _path : &str ) -> Result< Self >
    {
      // Placeholder implementation
      Ok( Self::new() )
    }

    /// Create from samples
    #[ inline ]
    pub fn from_samples( samples : Vec< TrainingSample > ) -> Result< Self >
    {
      Ok( Self
      {
        samples,
        metadata : HashMap::new(),
      } )
    }

    /// Load from text file
    #[ inline ]
    pub fn from_text_file( _path : &str ) -> Result< Self >
    {
      Ok( Self::new() )
    }

    /// Create from text
    #[ inline ]
    pub fn from_text( _text : &str ) -> Result< Self >
    {
      Ok( Self::new() )
    }

    /// Add sample to the training data
    #[ inline ]
    pub fn add_sample( &mut self, _prompt : &str, _completion : &str )
    {
      // Placeholder implementation
    }

    /// Add validation sample
    #[ inline ]
    pub fn add_validation_sample( &mut self, _prompt : &str, _completion : &str )
    {
      // Placeholder implementation
    }
  }

  impl Default for TrainingData
  {
    #[ inline ]
    fn default() -> Self
    {
      Self::new()
    }
  }

  impl DataPreprocessor
  {
    /// Create new preprocessor
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        tokenizer_config : HashMap::new(),
        normalization_config : HashMap::new(),
      }
    }

    /// Configure tokenization
    #[ inline ]
    pub fn configure_tokenization( &mut self, _settings : HashMap<  String, serde_json::Value  > )
    {
      // Placeholder implementation
    }

    /// Set normalization
    #[ inline ]
    pub fn set_normalization( &mut self, _enabled : bool )
    {
      // Placeholder implementation
    }

    /// Preprocess data
    #[ inline ]
    pub fn preprocess( &self, _data : &mut TrainingData ) -> Result< () >
    {
      Ok( () )
    }
  }

  impl ModelBenchmark
  {
    /// Create new benchmark
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        tasks : Vec::new(),
        test_data_size : 1000,
        config : HashMap::new(),
      }
    }

    /// Add benchmark task
    #[ inline ]
    #[ must_use ]
    pub fn add_task( mut self, task : &str ) -> Self
    {
      self.tasks.push( task.to_string() );
      self
    }

    /// Set test data size
    #[ inline ]
    #[ must_use ]
    pub fn test_data_size( mut self, size : usize ) -> Self
    {
      self.test_data_size = size;
      self
    }
  }

  impl HyperParameters
  {
    /// Create new hyperparameters
    #[ inline ]
    #[ must_use ]
    pub fn new() -> Self
    {
      Self
      {
        learning_rate : 0.001,
        batch_size : 32,
        max_epochs : 10,
        warmup_steps : 1000,
        weight_decay : 0.01,
        gradient_clip_norm : 1.0,
        lora_rank : None,
        lora_alpha : None,
        lora_dropout : None,
        target_modules : vec![ "query".to_string(), "value".to_string() ],
        adapter_size : None,
        adapter_activation : None,
      }
    }

    /// Set learning rate
    #[ inline ]
    pub fn set_learning_rate( &mut self, lr : f32 )
    {
      self.learning_rate = lr;
    }

    /// Set batch size
    #[ inline ]
    pub fn set_batch_size( &mut self, size : usize )
    {
      self.batch_size = size;
    }

    /// Set epochs
    #[ inline ]
    pub fn set_epochs( &mut self, epochs : usize )
    {
      self.max_epochs = epochs;
    }
  }

  impl ModelTuningJob
  {
    /// Get the model ID from this tuning job
    #[ inline ]
    pub fn model_id( &self ) -> &str
    {
      &self.config.model_name
    }

    /// Check if the job is completed
    #[ inline ]
    #[ must_use ]
    pub fn is_completed( &self ) -> bool
    {
      matches!( self.status, TuningJobStatus::Completed )
    }

    /// Get progress percentage (0-100)
    #[ inline ]
    #[ must_use ]
    pub fn progress_percentage( &self ) -> f32
    {
      self.progress.as_ref().map( | p |
        if p.total_epochs > 0
        {
          ( p.current_epoch as f32 / p.total_epochs as f32 ) * 100.0
        }
        else
        {
          0.0
        }
      ).unwrap_or( 0.0 )
    }

    /// Wait for job completion with monitoring
    #[ inline ]
    pub async fn wait_for_completion( &mut self ) -> Result< () >
    {
      // Placeholder implementation - simulate completion
      tokio ::time::sleep( core::time::Duration::from_millis( 100 ) ).await;
      self.status = TuningJobStatus::Completed;
      self.completed_at = Some( std::time::SystemTime::now() );
      Ok( () )
    }

    /// Get current resource usage
    #[ inline ]
    #[ must_use ]
    pub fn get_resource_usage( &self ) -> Option< &ResourceUsage >
    {
      self.resource_usage.as_ref()
    }
  }
}

#[ cfg( feature = "model_tuning" ) ]
crate ::mod_interface!
{
  exposed use private::TuningJobStatus;
  exposed use private::TuningMethod;
  exposed use private::TrainingObjective;
  exposed use private::HyperParameters;
  exposed use private::TrainingProgress;
  exposed use private::ModelCheckpoint;
  exposed use private::ResourceUsage;
  exposed use private::ModelEvaluation;
  exposed use private::ModelVersion;
  exposed use private::TrainingSample;
  exposed use private::ValidationResult;
  exposed use private::DataUploadResult;
  exposed use private::BenchmarkTaskResult;
  exposed use private::BenchmarkResults;
  exposed use private::ModelTuningConfig;
  exposed use private::TrainingData;
  exposed use private::DataPreprocessor;
  exposed use private::ModelBenchmark;
  exposed use private::ModelTuningJob;
  exposed use private::ModelTuningConfigBuilder;
}