Skip to main content

oxirs_chat/finetuning/
mod.rs

1//! Fine-tuning support for OxiRS Chat models
2//!
3//! This module provides infrastructure for model fine-tuning based on
4//! conversation history, user feedback, and domain-specific datasets.
5//!
6//! # Features
7//! - Training data collection from conversation history
8//! - JSONL export format for OpenAI/HuggingFace fine-tuning
9//! - Data quality filtering and deduplication
10//! - Feedback collection and annotation
11//! - Domain-specific dataset management
12//! - Training job tracking and status management
13//! - Model performance evaluation utilities
14
15use chrono::{DateTime, Utc};
16use serde::{Deserialize, Serialize};
17use std::{
18    collections::HashMap,
19    fs,
20    path::{Path, PathBuf},
21};
22use thiserror::Error;
23use tracing::{debug, info, warn};
24use uuid::Uuid;
25
26/// Errors that can occur during fine-tuning operations
27#[derive(Debug, Error)]
28pub enum FinetuningError {
29    #[error("IO error: {0}")]
30    IoError(#[from] std::io::Error),
31    #[error("Serialization error: {0}")]
32    SerializationError(#[from] serde_json::Error),
33    #[error("Dataset not found: {0}")]
34    DatasetNotFound(String),
35    #[error("Insufficient training data: need {needed}, have {available}")]
36    InsufficientData { needed: usize, available: usize },
37    #[error("Training job not found: {0}")]
38    JobNotFound(String),
39    #[error("Invalid configuration: {0}")]
40    ConfigurationError(String),
41    #[error("Data quality error: {0}")]
42    DataQualityError(String),
43}
44
45/// Result type for fine-tuning operations
46pub type FinetuningResult<T> = Result<T, FinetuningError>;
47
48/// Supported export formats for fine-tuning datasets
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub enum ExportFormat {
51    /// OpenAI Chat Completions JSONL format
52    OpenAiChatJsonl,
53    /// HuggingFace instruction format
54    HuggingFaceInstruct,
55    /// Alpaca instruction format
56    AlpacaInstruct,
57    /// Raw conversation pairs (input/output)
58    ConversationPairs,
59    /// Full conversation JSON
60    FullConversationJson,
61}
62
63/// A single training example (conversation turn or exchange)
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct TrainingExample {
66    /// Unique identifier for this example
67    pub id: String,
68    /// The system prompt context
69    pub system_prompt: Option<String>,
70    /// The human/user message
71    pub human_message: String,
72    /// The expected assistant response
73    pub assistant_response: String,
74    /// Domain/topic category for this example
75    pub domain: Option<String>,
76    /// Quality score (0.0 - 1.0, higher is better)
77    pub quality_score: f32,
78    /// Whether this was reviewed and approved by a human
79    pub human_reviewed: bool,
80    /// User feedback rating (1-5)
81    pub user_rating: Option<u8>,
82    /// Tags for filtering and categorization
83    pub tags: Vec<String>,
84    /// Source session ID
85    pub source_session_id: Option<String>,
86    /// When this example was collected
87    pub collected_at: DateTime<Utc>,
88    /// Additional metadata
89    pub metadata: HashMap<String, String>,
90}
91
92impl TrainingExample {
93    /// Create a new training example
94    pub fn new(human_message: String, assistant_response: String) -> Self {
95        Self {
96            id: Uuid::new_v4().to_string(),
97            system_prompt: None,
98            human_message,
99            assistant_response,
100            domain: None,
101            quality_score: 0.5,
102            human_reviewed: false,
103            user_rating: None,
104            tags: Vec::new(),
105            source_session_id: None,
106            collected_at: Utc::now(),
107            metadata: HashMap::new(),
108        }
109    }
110
111    /// Check if this example meets the minimum quality threshold
112    pub fn meets_quality_threshold(&self, threshold: f32) -> bool {
113        self.quality_score >= threshold
114    }
115
116    /// Export as OpenAI chat completion format
117    pub fn to_openai_format(&self) -> serde_json::Value {
118        let mut messages = Vec::new();
119
120        if let Some(ref system) = self.system_prompt {
121            messages.push(serde_json::json!({
122                "role": "system",
123                "content": system
124            }));
125        }
126
127        messages.push(serde_json::json!({
128            "role": "user",
129            "content": self.human_message
130        }));
131
132        messages.push(serde_json::json!({
133            "role": "assistant",
134            "content": self.assistant_response
135        }));
136
137        serde_json::json!({ "messages": messages })
138    }
139
140    /// Export as Alpaca instruction format
141    pub fn to_alpaca_format(&self) -> serde_json::Value {
142        serde_json::json!({
143            "instruction": self.human_message,
144            "input": "",
145            "output": self.assistant_response
146        })
147    }
148
149    /// Calculate a quality score based on various heuristics
150    pub fn compute_quality_score(&mut self) {
151        let mut score = 0.5f32;
152
153        // Boost for longer, more detailed responses
154        let response_len = self.assistant_response.len();
155        if response_len > 100 {
156            score += 0.1;
157        }
158        if response_len > 500 {
159            score += 0.1;
160        }
161
162        // Boost for user rating
163        if let Some(rating) = self.user_rating {
164            score += (rating as f32 - 3.0) * 0.1;
165        }
166
167        // Boost for human review
168        if self.human_reviewed {
169            score += 0.2;
170        }
171
172        // Penalize very short responses (likely unhelpful)
173        if response_len < 20 {
174            score -= 0.3;
175        }
176
177        // Penalize very short user messages (may lack context)
178        if self.human_message.len() < 10 {
179            score -= 0.1;
180        }
181
182        self.quality_score = score.clamp(0.0, 1.0);
183    }
184}
185
186/// A dataset of training examples
187#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct TrainingDataset {
189    /// Unique identifier for this dataset
190    pub id: String,
191    /// Human-readable name
192    pub name: String,
193    /// Description of what this dataset covers
194    pub description: String,
195    /// Domain/topic focus (e.g., "sparql", "rdf", "general")
196    pub domain: Option<String>,
197    /// All training examples in this dataset
198    pub examples: Vec<TrainingExample>,
199    /// When this dataset was created
200    pub created_at: DateTime<Utc>,
201    /// When this dataset was last updated
202    pub updated_at: DateTime<Utc>,
203    /// Dataset version
204    pub version: String,
205    /// Tags for organization
206    pub tags: Vec<String>,
207    /// Dataset statistics
208    pub stats: DatasetStats,
209}
210
211/// Statistics about a training dataset
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct DatasetStats {
214    pub total_examples: usize,
215    pub high_quality_examples: usize,
216    pub human_reviewed_examples: usize,
217    pub average_quality_score: f32,
218    pub average_human_len: f32,
219    pub average_assistant_len: f32,
220    pub unique_domains: usize,
221}
222
223impl TrainingDataset {
224    /// Create a new empty dataset
225    pub fn new(id: String, name: String) -> Self {
226        let now = Utc::now();
227        Self {
228            id,
229            name,
230            description: String::new(),
231            domain: None,
232            examples: Vec::new(),
233            created_at: now,
234            updated_at: now,
235            version: "1.0.0".to_string(),
236            tags: Vec::new(),
237            stats: DatasetStats {
238                total_examples: 0,
239                high_quality_examples: 0,
240                human_reviewed_examples: 0,
241                average_quality_score: 0.0,
242                average_human_len: 0.0,
243                average_assistant_len: 0.0,
244                unique_domains: 0,
245            },
246        }
247    }
248
249    /// Add a training example.
250    ///
251    /// If the example's `quality_score` is exactly 0.5 (the default),
252    /// it will be recomputed from heuristics. Otherwise the caller's
253    /// explicitly set score is preserved.
254    pub fn add_example(&mut self, mut example: TrainingExample) {
255        if (example.quality_score - 0.5).abs() < f32::EPSILON {
256            example.compute_quality_score();
257        }
258        self.examples.push(example);
259        self.updated_at = Utc::now();
260        self.recompute_stats();
261    }
262
263    /// Get examples filtered by minimum quality score
264    pub fn examples_above_quality(&self, threshold: f32) -> Vec<&TrainingExample> {
265        self.examples
266            .iter()
267            .filter(|e| e.quality_score >= threshold)
268            .collect()
269    }
270
271    /// Deduplicate examples by exact human_message match
272    pub fn deduplicate(&mut self) -> usize {
273        let before = self.examples.len();
274        let mut seen_messages = std::collections::HashSet::new();
275        self.examples.retain(|e| {
276            let key = e.human_message.trim().to_lowercase();
277            seen_messages.insert(key)
278        });
279        let removed = before - self.examples.len();
280        if removed > 0 {
281            info!("Deduplicated {} examples from dataset {}", removed, self.id);
282            self.recompute_stats();
283        }
284        removed
285    }
286
287    /// Export examples in the specified format as JSONL string
288    pub fn export_jsonl(
289        &self,
290        format: &ExportFormat,
291        quality_threshold: f32,
292    ) -> FinetuningResult<String> {
293        let examples = self.examples_above_quality(quality_threshold);
294
295        if examples.is_empty() {
296            return Err(FinetuningError::InsufficientData {
297                needed: 1,
298                available: 0,
299            });
300        }
301
302        let mut lines = Vec::with_capacity(examples.len());
303        for example in &examples {
304            let json = match format {
305                ExportFormat::OpenAiChatJsonl => example.to_openai_format(),
306                ExportFormat::AlpacaInstruct => example.to_alpaca_format(),
307                ExportFormat::HuggingFaceInstruct => serde_json::json!({
308                    "prompt": example.human_message,
309                    "response": example.assistant_response,
310                }),
311                ExportFormat::ConversationPairs => serde_json::json!({
312                    "input": example.human_message,
313                    "output": example.assistant_response,
314                }),
315                ExportFormat::FullConversationJson => serde_json::to_value(example)?,
316            };
317            lines.push(serde_json::to_string(&json)?);
318        }
319
320        Ok(lines.join("\n"))
321    }
322
323    /// Recompute dataset statistics
324    pub fn recompute_stats(&mut self) {
325        let total = self.examples.len();
326        if total == 0 {
327            self.stats = DatasetStats {
328                total_examples: 0,
329                high_quality_examples: 0,
330                human_reviewed_examples: 0,
331                average_quality_score: 0.0,
332                average_human_len: 0.0,
333                average_assistant_len: 0.0,
334                unique_domains: 0,
335            };
336            return;
337        }
338
339        let high_quality = self
340            .examples
341            .iter()
342            .filter(|e| e.quality_score >= 0.7)
343            .count();
344        let reviewed = self.examples.iter().filter(|e| e.human_reviewed).count();
345        let total_quality: f32 = self.examples.iter().map(|e| e.quality_score).sum();
346        let total_human_len: usize = self.examples.iter().map(|e| e.human_message.len()).sum();
347        let total_assistant_len: usize = self
348            .examples
349            .iter()
350            .map(|e| e.assistant_response.len())
351            .sum();
352        let unique_domains: std::collections::HashSet<&str> = self
353            .examples
354            .iter()
355            .filter_map(|e| e.domain.as_deref())
356            .collect();
357
358        self.stats = DatasetStats {
359            total_examples: total,
360            high_quality_examples: high_quality,
361            human_reviewed_examples: reviewed,
362            average_quality_score: total_quality / total as f32,
363            average_human_len: total_human_len as f32 / total as f32,
364            average_assistant_len: total_assistant_len as f32 / total as f32,
365            unique_domains: unique_domains.len(),
366        };
367    }
368}
369
370/// Status of a fine-tuning job
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
372pub enum JobStatus {
373    /// Job is waiting to be processed
374    Pending,
375    /// Training data is being prepared
376    PreparingData,
377    /// Job is actively training
378    Training,
379    /// Job has completed successfully
380    Completed,
381    /// Job has failed
382    Failed,
383    /// Job was cancelled
384    Cancelled,
385}
386
387/// Configuration for a fine-tuning job
388#[derive(Debug, Clone, Serialize, Deserialize)]
389pub struct FinetuningJobConfig {
390    /// Base model to fine-tune (e.g., "gpt-3.5-turbo", "llama-2-7b")
391    pub base_model: String,
392    /// Target model name/suffix
393    pub suffix: String,
394    /// Number of training epochs
395    pub epochs: u32,
396    /// Batch size for training
397    pub batch_size: u32,
398    /// Learning rate multiplier
399    pub learning_rate_multiplier: f32,
400    /// Minimum quality threshold for training examples
401    pub quality_threshold: f32,
402    /// Export format for training data
403    pub export_format: ExportFormat,
404    /// Maximum number of training examples to use
405    pub max_examples: Option<usize>,
406    /// Whether to validate the model after training
407    pub run_validation: bool,
408    /// Validation split ratio (0.0 - 0.3)
409    pub validation_split: f32,
410}
411
412impl Default for FinetuningJobConfig {
413    fn default() -> Self {
414        Self {
415            base_model: "gpt-3.5-turbo".to_string(),
416            suffix: "oxirs-chat".to_string(),
417            epochs: 3,
418            batch_size: 4,
419            learning_rate_multiplier: 1.0,
420            quality_threshold: 0.6,
421            export_format: ExportFormat::OpenAiChatJsonl,
422            max_examples: None,
423            run_validation: true,
424            validation_split: 0.1,
425        }
426    }
427}
428
429/// A fine-tuning job record
430#[derive(Debug, Clone, Serialize, Deserialize)]
431pub struct FinetuningJob {
432    /// Unique job identifier
433    pub id: String,
434    /// Dataset used for this job
435    pub dataset_id: String,
436    /// Job configuration
437    pub config: FinetuningJobConfig,
438    /// Current job status
439    pub status: JobStatus,
440    /// When the job was created
441    pub created_at: DateTime<Utc>,
442    /// When the job started training
443    pub started_at: Option<DateTime<Utc>>,
444    /// When the job completed or failed
445    pub completed_at: Option<DateTime<Utc>>,
446    /// External job ID from the fine-tuning provider (e.g., OpenAI job ID)
447    pub external_job_id: Option<String>,
448    /// Resulting fine-tuned model name
449    pub result_model: Option<String>,
450    /// Number of training examples used
451    pub training_examples: usize,
452    /// Number of validation examples
453    pub validation_examples: usize,
454    /// Current training step
455    pub current_step: Option<u64>,
456    /// Total training steps
457    pub total_steps: Option<u64>,
458    /// Training loss history
459    pub training_loss: Vec<f32>,
460    /// Validation loss history
461    pub validation_loss: Vec<f32>,
462    /// Error message if failed
463    pub error_message: Option<String>,
464    /// Job metadata
465    pub metadata: HashMap<String, String>,
466}
467
468impl FinetuningJob {
469    /// Create a new fine-tuning job
470    pub fn new(dataset_id: String, config: FinetuningJobConfig) -> Self {
471        Self {
472            id: Uuid::new_v4().to_string(),
473            dataset_id,
474            config,
475            status: JobStatus::Pending,
476            created_at: Utc::now(),
477            started_at: None,
478            completed_at: None,
479            external_job_id: None,
480            result_model: None,
481            training_examples: 0,
482            validation_examples: 0,
483            current_step: None,
484            total_steps: None,
485            training_loss: Vec::new(),
486            validation_loss: Vec::new(),
487            error_message: None,
488            metadata: HashMap::new(),
489        }
490    }
491
492    /// Mark the job as started
493    pub fn start(&mut self) {
494        self.status = JobStatus::Training;
495        self.started_at = Some(Utc::now());
496        info!("Fine-tuning job {} started", self.id);
497    }
498
499    /// Record a training step
500    pub fn record_step(&mut self, step: u64, train_loss: f32, val_loss: Option<f32>) {
501        self.current_step = Some(step);
502        self.training_loss.push(train_loss);
503        if let Some(vl) = val_loss {
504            self.validation_loss.push(vl);
505        }
506        debug!(
507            "Job {} step {}: train_loss={:.4}",
508            self.id, step, train_loss
509        );
510    }
511
512    /// Mark the job as completed
513    pub fn complete(&mut self, result_model: String) {
514        self.status = JobStatus::Completed;
515        self.completed_at = Some(Utc::now());
516        self.result_model = Some(result_model.clone());
517        info!(
518            "Fine-tuning job {} completed. Model: {}",
519            self.id, result_model
520        );
521    }
522
523    /// Mark the job as failed
524    pub fn fail(&mut self, error: String) {
525        self.status = JobStatus::Failed;
526        self.completed_at = Some(Utc::now());
527        self.error_message = Some(error.clone());
528        warn!("Fine-tuning job {} failed: {}", self.id, error);
529    }
530
531    /// Get the duration of the job
532    pub fn duration(&self) -> Option<chrono::Duration> {
533        match (self.started_at, self.completed_at) {
534            (Some(start), Some(end)) => Some(end - start),
535            _ => None,
536        }
537    }
538
539    /// Get progress as a percentage (0.0 - 1.0)
540    pub fn progress(&self) -> f32 {
541        match (self.current_step, self.total_steps) {
542            (Some(current), Some(total)) if total > 0 => current as f32 / total as f32,
543            _ => match self.status {
544                JobStatus::Completed => 1.0,
545                JobStatus::Pending => 0.0,
546                _ => 0.5,
547            },
548        }
549    }
550
551    /// Check if the job is currently active
552    pub fn is_active(&self) -> bool {
553        matches!(
554            self.status,
555            JobStatus::Pending | JobStatus::PreparingData | JobStatus::Training
556        )
557    }
558}
559
560/// Feedback collected from users about conversation quality
561#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct ConversationFeedback {
563    /// Unique feedback ID
564    pub id: String,
565    /// Session ID this feedback is for
566    pub session_id: String,
567    /// Message ID this feedback is for
568    pub message_id: Option<String>,
569    /// Rating (1-5, with 5 being best)
570    pub rating: u8,
571    /// Optional text feedback
572    pub comment: Option<String>,
573    /// Whether the user flagged this as incorrect
574    pub flagged_incorrect: bool,
575    /// Whether the user flagged this as harmful
576    pub flagged_harmful: bool,
577    /// Specific issue categories
578    pub issue_categories: Vec<FeedbackIssue>,
579    /// When this feedback was submitted
580    pub submitted_at: DateTime<Utc>,
581    /// User identifier (anonymized)
582    pub user_id: Option<String>,
583}
584
585/// Categories of issues in feedback
586#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
587pub enum FeedbackIssue {
588    Inaccurate,
589    Unhelpful,
590    TooLong,
591    TooShort,
592    OffTopic,
593    Confusing,
594    Biased,
595    Outdated,
596    MissingContext,
597}
598
599impl ConversationFeedback {
600    /// Create new feedback for a session
601    pub fn new(session_id: String, rating: u8) -> Self {
602        let rating = rating.clamp(1, 5);
603        Self {
604            id: Uuid::new_v4().to_string(),
605            session_id,
606            message_id: None,
607            rating,
608            comment: None,
609            flagged_incorrect: false,
610            flagged_harmful: false,
611            issue_categories: Vec::new(),
612            submitted_at: Utc::now(),
613            user_id: None,
614        }
615    }
616
617    /// Convert rating to a quality score component
618    pub fn rating_to_quality(&self) -> f32 {
619        (self.rating as f32 - 1.0) / 4.0 // Maps 1-5 to 0.0-1.0
620    }
621}
622
623/// Configuration for the fine-tuning data manager
624#[derive(Debug, Clone, Serialize, Deserialize)]
625pub struct FinetuningManagerConfig {
626    /// Directory for storing datasets and jobs
627    pub storage_dir: PathBuf,
628    /// Minimum examples required before export
629    pub min_examples_for_export: usize,
630    /// Default quality threshold for training data
631    pub default_quality_threshold: f32,
632    /// Whether to auto-deduplicate on save
633    pub auto_deduplicate: bool,
634    /// Maximum dataset size (0 = unlimited)
635    pub max_dataset_size: usize,
636}
637
638impl Default for FinetuningManagerConfig {
639    fn default() -> Self {
640        Self {
641            storage_dir: PathBuf::from("data/finetuning"),
642            min_examples_for_export: 10,
643            default_quality_threshold: 0.5,
644            auto_deduplicate: true,
645            max_dataset_size: 100_000,
646        }
647    }
648}
649
650/// Manages training datasets, jobs, and feedback for fine-tuning
651pub struct FinetuningManager {
652    config: FinetuningManagerConfig,
653    datasets: HashMap<String, TrainingDataset>,
654    jobs: HashMap<String, FinetuningJob>,
655    feedback: Vec<ConversationFeedback>,
656}
657
658impl FinetuningManager {
659    /// Create a new fine-tuning manager
660    pub fn new(config: FinetuningManagerConfig) -> FinetuningResult<Self> {
661        fs::create_dir_all(&config.storage_dir)?;
662        Ok(Self {
663            config,
664            datasets: HashMap::new(),
665            jobs: HashMap::new(),
666            feedback: Vec::new(),
667        })
668    }
669
670    /// Create a new dataset
671    pub fn create_dataset(
672        &mut self,
673        name: String,
674        description: String,
675    ) -> FinetuningResult<String> {
676        let id = Uuid::new_v4().to_string();
677        let mut dataset = TrainingDataset::new(id.clone(), name);
678        dataset.description = description;
679        info!("Created fine-tuning dataset: {}", dataset.id);
680        self.datasets.insert(id.clone(), dataset);
681        Ok(id)
682    }
683
684    /// Get a dataset by ID
685    pub fn get_dataset(&self, id: &str) -> FinetuningResult<&TrainingDataset> {
686        self.datasets
687            .get(id)
688            .ok_or_else(|| FinetuningError::DatasetNotFound(id.to_string()))
689    }
690
691    /// Get a mutable dataset by ID
692    pub fn get_dataset_mut(&mut self, id: &str) -> FinetuningResult<&mut TrainingDataset> {
693        self.datasets
694            .get_mut(id)
695            .ok_or_else(|| FinetuningError::DatasetNotFound(id.to_string()))
696    }
697
698    /// Add a training example to a dataset
699    pub fn add_example(
700        &mut self,
701        dataset_id: &str,
702        example: TrainingExample,
703    ) -> FinetuningResult<()> {
704        let max_size = self.config.max_dataset_size;
705        let auto_dedup = self.config.auto_deduplicate;
706
707        let dataset = self.get_dataset_mut(dataset_id)?;
708
709        if max_size > 0 && dataset.examples.len() >= max_size {
710            warn!(
711                "Dataset {} is at maximum size ({}), dropping oldest example",
712                dataset_id, max_size
713            );
714            dataset.examples.remove(0);
715        }
716
717        dataset.add_example(example);
718
719        if auto_dedup && dataset.examples.len() % 1000 == 0 {
720            dataset.deduplicate();
721        }
722
723        Ok(())
724    }
725
726    /// Submit user feedback
727    pub fn submit_feedback(&mut self, feedback: ConversationFeedback) -> FinetuningResult<String> {
728        let id = feedback.id.clone();
729        debug!(
730            "Received feedback for session {}: rating={}",
731            feedback.session_id, feedback.rating
732        );
733        self.feedback.push(feedback);
734        Ok(id)
735    }
736
737    /// Get all feedback for a session
738    pub fn get_session_feedback(&self, session_id: &str) -> Vec<&ConversationFeedback> {
739        self.feedback
740            .iter()
741            .filter(|f| f.session_id == session_id)
742            .collect()
743    }
744
745    /// Create a fine-tuning job from a dataset
746    pub fn create_job(
747        &mut self,
748        dataset_id: &str,
749        config: FinetuningJobConfig,
750    ) -> FinetuningResult<String> {
751        // Validate dataset has enough examples
752        let dataset = self.get_dataset(dataset_id)?;
753        let available = dataset
754            .examples_above_quality(config.quality_threshold)
755            .len();
756
757        if available < self.config.min_examples_for_export {
758            return Err(FinetuningError::InsufficientData {
759                needed: self.config.min_examples_for_export,
760                available,
761            });
762        }
763
764        let job = FinetuningJob::new(dataset_id.to_string(), config);
765        let job_id = job.id.clone();
766        info!(
767            "Created fine-tuning job {} for dataset {}",
768            job_id, dataset_id
769        );
770        self.jobs.insert(job_id.clone(), job);
771        Ok(job_id)
772    }
773
774    /// Get a job by ID
775    pub fn get_job(&self, job_id: &str) -> FinetuningResult<&FinetuningJob> {
776        self.jobs
777            .get(job_id)
778            .ok_or_else(|| FinetuningError::JobNotFound(job_id.to_string()))
779    }
780
781    /// Get a mutable job by ID
782    pub fn get_job_mut(&mut self, job_id: &str) -> FinetuningResult<&mut FinetuningJob> {
783        self.jobs
784            .get_mut(job_id)
785            .ok_or_else(|| FinetuningError::JobNotFound(job_id.to_string()))
786    }
787
788    /// Export a dataset to a file in the specified format
789    pub fn export_dataset(
790        &self,
791        dataset_id: &str,
792        output_path: &Path,
793        format: &ExportFormat,
794        quality_threshold: Option<f32>,
795    ) -> FinetuningResult<usize> {
796        let dataset = self.get_dataset(dataset_id)?;
797        let threshold = quality_threshold.unwrap_or(self.config.default_quality_threshold);
798        let jsonl = dataset.export_jsonl(format, threshold)?;
799
800        let line_count = jsonl.lines().count();
801        fs::write(output_path, &jsonl)?;
802
803        info!(
804            "Exported {} examples from dataset {} to {:?}",
805            line_count, dataset_id, output_path
806        );
807        Ok(line_count)
808    }
809
810    /// Get manager statistics
811    pub fn statistics(&self) -> FinetuningManagerStats {
812        let total_examples: usize = self.datasets.values().map(|d| d.examples.len()).sum();
813        let active_jobs = self.jobs.values().filter(|j| j.is_active()).count();
814        let completed_jobs = self
815            .jobs
816            .values()
817            .filter(|j| j.status == JobStatus::Completed)
818            .count();
819
820        FinetuningManagerStats {
821            total_datasets: self.datasets.len(),
822            total_examples,
823            total_jobs: self.jobs.len(),
824            active_jobs,
825            completed_jobs,
826            failed_jobs: self
827                .jobs
828                .values()
829                .filter(|j| j.status == JobStatus::Failed)
830                .count(),
831            total_feedback: self.feedback.len(),
832            average_rating: if self.feedback.is_empty() {
833                0.0
834            } else {
835                self.feedback.iter().map(|f| f.rating as f32).sum::<f32>()
836                    / self.feedback.len() as f32
837            },
838        }
839    }
840
841    /// List all datasets
842    pub fn list_datasets(&self) -> Vec<&TrainingDataset> {
843        self.datasets.values().collect()
844    }
845
846    /// List all jobs, optionally filtered by status
847    pub fn list_jobs(&self, status_filter: Option<&JobStatus>) -> Vec<&FinetuningJob> {
848        match status_filter {
849            Some(status) => self.jobs.values().filter(|j| &j.status == status).collect(),
850            None => self.jobs.values().collect(),
851        }
852    }
853}
854
855/// Statistics about the fine-tuning manager
856#[derive(Debug, Clone, Serialize, Deserialize)]
857pub struct FinetuningManagerStats {
858    pub total_datasets: usize,
859    pub total_examples: usize,
860    pub total_jobs: usize,
861    pub active_jobs: usize,
862    pub completed_jobs: usize,
863    pub failed_jobs: usize,
864    pub total_feedback: usize,
865    pub average_rating: f32,
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871    use std::env;
872
873    fn make_example(human: &str, assistant: &str) -> TrainingExample {
874        TrainingExample::new(human.to_string(), assistant.to_string())
875    }
876
877    #[test]
878    fn test_training_example_quality_score() {
879        let mut example = make_example(
880            "How do I write a SPARQL query to find all classes?",
881            "To find all classes in a SPARQL endpoint, you can use the following query:\n\nSELECT ?class WHERE { ?class a owl:Class }",
882        );
883        example.compute_quality_score();
884        assert!(example.quality_score > 0.0);
885        assert!(example.quality_score <= 1.0);
886    }
887
888    #[test]
889    fn test_openai_format_export() {
890        let example = make_example("What is RDF?", "RDF (Resource Description Framework) is a standard model for data interchange on the Web.");
891        let json = example.to_openai_format();
892        assert!(json.get("messages").is_some());
893        let messages = json["messages"].as_array().expect("messages array");
894        assert!(!messages.is_empty());
895    }
896
897    #[test]
898    fn test_alpaca_format_export() {
899        let example = make_example("Explain SPARQL", "SPARQL is a query language for RDF data.");
900        let json = example.to_alpaca_format();
901        assert!(json.get("instruction").is_some());
902        assert!(json.get("output").is_some());
903    }
904
905    #[test]
906    fn test_dataset_add_and_deduplicate() {
907        let mut dataset = TrainingDataset::new("test-ds".to_string(), "Test Dataset".to_string());
908
909        dataset.add_example(make_example("What is RDF?", "RDF is..."));
910        dataset.add_example(make_example("What is SPARQL?", "SPARQL is..."));
911        dataset.add_example(make_example("What is RDF?", "RDF is...")); // duplicate
912
913        assert_eq!(dataset.examples.len(), 3);
914
915        let removed = dataset.deduplicate();
916        assert_eq!(removed, 1);
917        assert_eq!(dataset.examples.len(), 2);
918    }
919
920    #[test]
921    fn test_dataset_quality_filtering() {
922        let mut dataset = TrainingDataset::new("filter-ds".to_string(), "Filter Test".to_string());
923
924        let mut low_quality = make_example("Hi", "Hi!");
925        low_quality.quality_score = 0.1;
926        dataset.examples.push(low_quality);
927
928        let mut high_quality = make_example(
929            "How does SPARQL federation work?",
930            "SPARQL federation allows querying multiple endpoints simultaneously using the SERVICE keyword.",
931        );
932        high_quality.quality_score = 0.9;
933        dataset.examples.push(high_quality);
934
935        let high = dataset.examples_above_quality(0.5);
936        assert_eq!(high.len(), 1);
937    }
938
939    #[test]
940    fn test_dataset_export_jsonl() {
941        let mut dataset = TrainingDataset::new("export-ds".to_string(), "Export Test".to_string());
942
943        let mut example = make_example(
944            "What is OWL?",
945            "OWL (Web Ontology Language) is a semantic web language for defining ontologies.",
946        );
947        example.quality_score = 0.8;
948        dataset.examples.push(example);
949
950        let jsonl = dataset
951            .export_jsonl(&ExportFormat::OpenAiChatJsonl, 0.5)
952            .expect("export");
953        assert!(!jsonl.is_empty());
954        // Verify it's valid JSON
955        let line = jsonl.lines().next().expect("at least one line");
956        serde_json::from_str::<serde_json::Value>(line).expect("valid JSON");
957    }
958
959    #[test]
960    fn test_finetuning_manager_create_and_add() {
961        let dir =
962            env::temp_dir().join(format!("oxirs_finetuning_test_{}", Uuid::new_v4().simple()));
963        let config = FinetuningManagerConfig {
964            storage_dir: dir.clone(),
965            min_examples_for_export: 1,
966            ..Default::default()
967        };
968        let mut manager = FinetuningManager::new(config).expect("create manager");
969
970        let dataset_id = manager
971            .create_dataset("Test Dataset".to_string(), "A test dataset".to_string())
972            .expect("create dataset");
973
974        for i in 0..5 {
975            let mut example = make_example(
976                &format!("Question {}?", i),
977                &format!("Answer {} with more detail about semantic web and RDF.", i),
978            );
979            example.quality_score = 0.8;
980            manager
981                .add_example(&dataset_id, example)
982                .expect("add example");
983        }
984
985        let stats = manager.statistics();
986        assert_eq!(stats.total_datasets, 1);
987        assert_eq!(stats.total_examples, 5);
988
989        // Cleanup
990        let _ = fs::remove_dir_all(&dir);
991    }
992
993    #[test]
994    fn test_create_finetuning_job() {
995        let dir = env::temp_dir().join(format!("oxirs_job_test_{}", Uuid::new_v4().simple()));
996        let config = FinetuningManagerConfig {
997            storage_dir: dir.clone(),
998            min_examples_for_export: 1,
999            ..Default::default()
1000        };
1001        let mut manager = FinetuningManager::new(config).expect("create manager");
1002
1003        let dataset_id = manager
1004            .create_dataset("Job Test".to_string(), "For job creation test".to_string())
1005            .expect("create dataset");
1006
1007        for i in 0..3 {
1008            let mut example = make_example(
1009                &format!("SPARQL question {}?", i),
1010                &format!(
1011                    "Detailed SPARQL answer {} explaining the query pattern and expected results.",
1012                    i
1013                ),
1014            );
1015            example.quality_score = 0.8;
1016            manager
1017                .add_example(&dataset_id, example)
1018                .expect("add example");
1019        }
1020
1021        let job_id = manager
1022            .create_job(&dataset_id, FinetuningJobConfig::default())
1023            .expect("create job");
1024
1025        let job = manager.get_job(&job_id).expect("get job");
1026        assert_eq!(job.status, JobStatus::Pending);
1027        assert!(!job.id.is_empty());
1028
1029        // Cleanup
1030        let _ = fs::remove_dir_all(&dir);
1031    }
1032
1033    #[test]
1034    fn test_job_lifecycle() {
1035        let job_config = FinetuningJobConfig::default();
1036        let mut job = FinetuningJob::new("dataset-1".to_string(), job_config);
1037
1038        assert_eq!(job.status, JobStatus::Pending);
1039        assert!(job.is_active());
1040        assert_eq!(job.progress(), 0.0);
1041
1042        job.start();
1043        assert_eq!(job.status, JobStatus::Training);
1044
1045        job.record_step(10, 0.85, Some(0.90));
1046        assert_eq!(job.training_loss.len(), 1);
1047
1048        job.complete("ft:gpt-3.5-turbo:oxirs".to_string());
1049        assert_eq!(job.status, JobStatus::Completed);
1050        assert!(!job.is_active());
1051        assert_eq!(job.progress(), 1.0);
1052        assert!(job.completed_at.is_some());
1053    }
1054
1055    #[test]
1056    fn test_feedback_collection() {
1057        let dir = env::temp_dir().join(format!("oxirs_feedback_test_{}", Uuid::new_v4().simple()));
1058        let config = FinetuningManagerConfig {
1059            storage_dir: dir.clone(),
1060            ..Default::default()
1061        };
1062        let mut manager = FinetuningManager::new(config).expect("create manager");
1063
1064        let feedback = ConversationFeedback::new("session-abc".to_string(), 5);
1065        manager.submit_feedback(feedback).expect("submit feedback");
1066
1067        let session_feedback = manager.get_session_feedback("session-abc");
1068        assert_eq!(session_feedback.len(), 1);
1069        assert_eq!(session_feedback[0].rating, 5);
1070
1071        let stats = manager.statistics();
1072        assert_eq!(stats.total_feedback, 1);
1073        assert_eq!(stats.average_rating, 5.0);
1074
1075        // Cleanup
1076        let _ = fs::remove_dir_all(&dir);
1077    }
1078
1079    #[test]
1080    fn test_export_to_file() {
1081        let dir = env::temp_dir().join(format!("oxirs_export_test_{}", Uuid::new_v4().simple()));
1082        let config = FinetuningManagerConfig {
1083            storage_dir: dir.clone(),
1084            min_examples_for_export: 1,
1085            ..Default::default()
1086        };
1087        let mut manager = FinetuningManager::new(config).expect("create manager");
1088
1089        let dataset_id = manager
1090            .create_dataset("Export Test".to_string(), "For export test".to_string())
1091            .expect("create dataset");
1092
1093        let mut example = make_example(
1094            "What is triple store?",
1095            "A triple store is a purpose-built database for storing and querying RDF triples.",
1096        );
1097        example.quality_score = 0.9;
1098        manager.add_example(&dataset_id, example).expect("add");
1099
1100        let output_path = dir.join("training_data.jsonl");
1101        let count = manager
1102            .export_dataset(
1103                &dataset_id,
1104                &output_path,
1105                &ExportFormat::OpenAiChatJsonl,
1106                Some(0.5),
1107            )
1108            .expect("export");
1109
1110        assert_eq!(count, 1);
1111        assert!(output_path.exists());
1112
1113        // Cleanup
1114        let _ = fs::remove_dir_all(&dir);
1115    }
1116
1117    #[test]
1118    fn test_dataset_stats_computation() {
1119        let mut dataset = TrainingDataset::new("stats-ds".to_string(), "Stats Test".to_string());
1120
1121        for i in 0..10 {
1122            let mut example = make_example(
1123                &format!("Question {} about semantic web?", i),
1124                &format!("Detailed answer about semantic web topic {}.", i),
1125            );
1126            if i < 5 {
1127                example.quality_score = 0.8;
1128                example.human_reviewed = true;
1129            } else {
1130                example.quality_score = 0.4;
1131            }
1132            dataset.examples.push(example);
1133        }
1134
1135        dataset.recompute_stats();
1136
1137        assert_eq!(dataset.stats.total_examples, 10);
1138        assert_eq!(dataset.stats.high_quality_examples, 5);
1139        assert_eq!(dataset.stats.human_reviewed_examples, 5);
1140        assert!(dataset.stats.average_quality_score > 0.0);
1141    }
1142}