1use 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#[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
45pub type FinetuningResult<T> = Result<T, FinetuningError>;
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub enum ExportFormat {
51 OpenAiChatJsonl,
53 HuggingFaceInstruct,
55 AlpacaInstruct,
57 ConversationPairs,
59 FullConversationJson,
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct TrainingExample {
66 pub id: String,
68 pub system_prompt: Option<String>,
70 pub human_message: String,
72 pub assistant_response: String,
74 pub domain: Option<String>,
76 pub quality_score: f32,
78 pub human_reviewed: bool,
80 pub user_rating: Option<u8>,
82 pub tags: Vec<String>,
84 pub source_session_id: Option<String>,
86 pub collected_at: DateTime<Utc>,
88 pub metadata: HashMap<String, String>,
90}
91
92impl TrainingExample {
93 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 pub fn meets_quality_threshold(&self, threshold: f32) -> bool {
113 self.quality_score >= threshold
114 }
115
116 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 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 pub fn compute_quality_score(&mut self) {
151 let mut score = 0.5f32;
152
153 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 if let Some(rating) = self.user_rating {
164 score += (rating as f32 - 3.0) * 0.1;
165 }
166
167 if self.human_reviewed {
169 score += 0.2;
170 }
171
172 if response_len < 20 {
174 score -= 0.3;
175 }
176
177 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#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct TrainingDataset {
189 pub id: String,
191 pub name: String,
193 pub description: String,
195 pub domain: Option<String>,
197 pub examples: Vec<TrainingExample>,
199 pub created_at: DateTime<Utc>,
201 pub updated_at: DateTime<Utc>,
203 pub version: String,
205 pub tags: Vec<String>,
207 pub stats: DatasetStats,
209}
210
211#[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 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 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
372pub enum JobStatus {
373 Pending,
375 PreparingData,
377 Training,
379 Completed,
381 Failed,
383 Cancelled,
385}
386
387#[derive(Debug, Clone, Serialize, Deserialize)]
389pub struct FinetuningJobConfig {
390 pub base_model: String,
392 pub suffix: String,
394 pub epochs: u32,
396 pub batch_size: u32,
398 pub learning_rate_multiplier: f32,
400 pub quality_threshold: f32,
402 pub export_format: ExportFormat,
404 pub max_examples: Option<usize>,
406 pub run_validation: bool,
408 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#[derive(Debug, Clone, Serialize, Deserialize)]
431pub struct FinetuningJob {
432 pub id: String,
434 pub dataset_id: String,
436 pub config: FinetuningJobConfig,
438 pub status: JobStatus,
440 pub created_at: DateTime<Utc>,
442 pub started_at: Option<DateTime<Utc>>,
444 pub completed_at: Option<DateTime<Utc>>,
446 pub external_job_id: Option<String>,
448 pub result_model: Option<String>,
450 pub training_examples: usize,
452 pub validation_examples: usize,
454 pub current_step: Option<u64>,
456 pub total_steps: Option<u64>,
458 pub training_loss: Vec<f32>,
460 pub validation_loss: Vec<f32>,
462 pub error_message: Option<String>,
464 pub metadata: HashMap<String, String>,
466}
467
468impl FinetuningJob {
469 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 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 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 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 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 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 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 pub fn is_active(&self) -> bool {
553 matches!(
554 self.status,
555 JobStatus::Pending | JobStatus::PreparingData | JobStatus::Training
556 )
557 }
558}
559
560#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct ConversationFeedback {
563 pub id: String,
565 pub session_id: String,
567 pub message_id: Option<String>,
569 pub rating: u8,
571 pub comment: Option<String>,
573 pub flagged_incorrect: bool,
575 pub flagged_harmful: bool,
577 pub issue_categories: Vec<FeedbackIssue>,
579 pub submitted_at: DateTime<Utc>,
581 pub user_id: Option<String>,
583}
584
585#[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 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 pub fn rating_to_quality(&self) -> f32 {
619 (self.rating as f32 - 1.0) / 4.0 }
621}
622
623#[derive(Debug, Clone, Serialize, Deserialize)]
625pub struct FinetuningManagerConfig {
626 pub storage_dir: PathBuf,
628 pub min_examples_for_export: usize,
630 pub default_quality_threshold: f32,
632 pub auto_deduplicate: bool,
634 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
650pub struct FinetuningManager {
652 config: FinetuningManagerConfig,
653 datasets: HashMap<String, TrainingDataset>,
654 jobs: HashMap<String, FinetuningJob>,
655 feedback: Vec<ConversationFeedback>,
656}
657
658impl FinetuningManager {
659 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 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 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 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 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 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 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 pub fn create_job(
747 &mut self,
748 dataset_id: &str,
749 config: FinetuningJobConfig,
750 ) -> FinetuningResult<String> {
751 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 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 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 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 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 pub fn list_datasets(&self) -> Vec<&TrainingDataset> {
843 self.datasets.values().collect()
844 }
845
846 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#[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...")); 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 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 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 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 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 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}