1use crate::api::base::Validate;
40use crate::{De, Ser};
41use serde::{self, Deserialize, Serialize};
42use std::fmt;
43use std::str::FromStr;
44
45crate::impl_bytes_to_human_readable!();
47
48#[derive(Debug, Clone, PartialEq, Eq, Ser, De)]
50#[serde(rename_all = "snake_case")]
51pub enum FilePurpose {
52 FineTune,
54 Assistants,
56 Batch,
58 UserData,
60 Responses,
62 Vision,
64 FineTuneResults,
66 AssistantsOutput,
68}
69
70crate::impl_enum_display! {
71 FilePurpose {
72 FineTune => "fine-tune",
73 Assistants => "assistants",
74 Batch => "batch",
75 UserData => "user_data",
76 Responses => "responses",
77 Vision => "vision",
78 FineTuneResults => "fine-tune-results",
79 AssistantsOutput => "assistants_output",
80 }
81}
82
83impl FromStr for FilePurpose {
84 type Err = String;
85
86 fn from_str(s: &str) -> Result<Self, Self::Err> {
87 match s {
88 "fine-tune" => Ok(FilePurpose::FineTune),
89 "assistants" => Ok(FilePurpose::Assistants),
90 "batch" => Ok(FilePurpose::Batch),
91 "user_data" => Ok(FilePurpose::UserData),
92 "responses" => Ok(FilePurpose::Responses),
93 "vision" => Ok(FilePurpose::Vision),
94 "fine-tune-results" => Ok(FilePurpose::FineTuneResults),
95 "assistants_output" => Ok(FilePurpose::AssistantsOutput),
96 _ => Err(format!("Unknown file purpose: {}", s)),
97 }
98 }
99}
100
101impl FilePurpose {
102 #[must_use]
104 pub fn all() -> Vec<FilePurpose> {
105 vec![
106 FilePurpose::FineTune,
107 FilePurpose::Assistants,
108 FilePurpose::Batch,
109 FilePurpose::UserData,
110 FilePurpose::Responses,
111 FilePurpose::Vision,
112 FilePurpose::FineTuneResults,
113 FilePurpose::AssistantsOutput,
114 ]
115 }
116
117 #[must_use]
119 pub fn supports_text(&self) -> bool {
120 matches!(
121 self,
122 FilePurpose::FineTune
123 | FilePurpose::Assistants
124 | FilePurpose::Batch
125 | FilePurpose::UserData
126 | FilePurpose::Responses
127 )
128 }
129
130 #[must_use]
132 pub fn supports_images(&self) -> bool {
133 matches!(self, FilePurpose::Vision | FilePurpose::UserData)
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Ser, De)]
139#[serde(rename_all = "snake_case")]
140pub enum FileStatus {
141 Uploaded,
143 Processed,
145 Error,
147 Deleted,
149}
150
151crate::impl_enum_display! {
152 FileStatus {
153 Uploaded => "uploaded",
154 Processed => "processed",
155 Error => "error",
156 Deleted => "deleted",
157 }
158}
159
160#[derive(Debug, Clone, Ser, De)]
162pub struct File {
163 pub id: String,
165 pub object: String,
167 pub bytes: u64,
169 pub created_at: u64,
171 pub filename: String,
173 pub purpose: String,
175 #[serde(default = "default_file_status")]
177 pub status: String,
178 #[serde(skip_serializing_if = "Option::is_none")]
180 pub status_details: Option<String>,
181}
182
183crate::impl_default_object_type!(default_file_status, "uploaded");
184
185impl File {
186 #[must_use]
188 pub fn purpose_enum(&self) -> Option<FilePurpose> {
189 FilePurpose::from_str(&self.purpose).ok()
190 }
191
192 #[must_use]
194 pub fn is_fine_tune_file(&self) -> bool {
195 self.purpose == "fine-tune"
196 }
197
198 #[must_use]
200 pub fn is_assistants_file(&self) -> bool {
201 self.purpose == "assistants"
202 }
203
204 #[must_use]
206 pub fn is_batch_file(&self) -> bool {
207 self.purpose == "batch"
208 }
209
210 #[must_use]
212 pub fn size_human_readable(&self) -> String {
213 bytes_to_human_readable(self.bytes)
214 }
215
216 #[must_use]
218 pub fn created_at_formatted(&self) -> String {
219 use std::time::UNIX_EPOCH;
220 let datetime = UNIX_EPOCH + std::time::Duration::from_secs(self.created_at);
221 format!("{datetime:?}")
222 }
223}
224
225#[derive(Debug, Clone)]
227pub struct FileUploadRequest {
228 pub file: Vec<u8>,
230 pub filename: String,
232 pub purpose: FilePurpose,
234}
235
236impl FileUploadRequest {
237 #[must_use]
239 pub fn new(file: Vec<u8>, filename: String, purpose: FilePurpose) -> Self {
240 Self {
241 file,
242 filename,
243 purpose,
244 }
245 }
246
247 pub async fn from_file_path(
249 file_path: &std::path::Path,
250 purpose: FilePurpose,
251 ) -> Result<Self, std::io::Error> {
252 let file = tokio::fs::read(file_path).await?;
253 let filename = file_path
254 .file_name()
255 .and_then(|n| n.to_str())
256 .unwrap_or("unknown")
257 .to_string();
258
259 Ok(Self::new(file, filename, purpose))
260 }
261
262 pub fn validate(&self) -> Result<(), String> {
264 if self.file.is_empty() {
265 return Err("File cannot be empty".to_string());
266 }
267
268 if self.filename.is_empty() {
269 return Err("Filename cannot be empty".to_string());
270 }
271
272 const MAX_FILE_SIZE: usize = 200 * 1024 * 1024; if self.file.len() > MAX_FILE_SIZE {
275 return Err(format!(
276 "File size {} exceeds maximum limit of {} bytes",
277 self.file.len(),
278 MAX_FILE_SIZE
279 ));
280 }
281
282 match self.purpose {
284 FilePurpose::FineTune if !self.filename.ends_with(".jsonl") => {
285 return Err("Fine-tuning files must be in JSONL format".to_string());
286 }
287 FilePurpose::Batch if !self.filename.ends_with(".jsonl") => {
288 return Err("Batch files must be in JSONL format".to_string());
289 }
290 FilePurpose::Vision => {
291 let valid_extensions = [".png", ".jpg", ".jpeg", ".gif", ".webp"];
292 if !valid_extensions
293 .iter()
294 .any(|ext| self.filename.to_lowercase().ends_with(ext))
295 {
296 return Err(
297 "Vision files must be images (PNG, JPG, JPEG, GIF, WebP)".to_string()
298 );
299 }
300 }
301 _ => {} }
303
304 Ok(())
305 }
306
307 #[must_use]
309 pub fn mime_type(&self) -> &'static str {
310 Self::determine_mime_type(&self.filename)
311 }
312
313 fn determine_mime_type(filename: &str) -> &'static str {
315 let filename_lower = filename.to_lowercase();
316
317 if let Some(extension) = Self::extract_extension(&filename_lower) {
319 Self::mime_type_for_extension(extension)
320 } else {
321 "application/octet-stream"
322 }
323 }
324
325 fn extract_extension(filename_lower: &str) -> Option<&str> {
327 filename_lower.rfind('.').map(|pos| &filename_lower[pos..])
328 }
329
330 fn mime_type_for_extension(extension: &str) -> &'static str {
332 match extension {
333 ".jsonl" => "application/jsonl",
334 ".json" => "application/json",
335 ".txt" => "text/plain",
336 ".csv" => "text/csv",
337 ".png" => "image/png",
338 ".jpg" | ".jpeg" => "image/jpeg",
339 ".gif" => "image/gif",
340 ".webp" => "image/webp",
341 ".pdf" => "application/pdf",
342 _ => "application/octet-stream",
343 }
344 }
345}
346
347impl Validate for FileUploadRequest {
349 fn validate(&self) -> Result<(), String> {
350 self.validate()
351 }
352}
353
354#[derive(Debug, Clone, Ser, De)]
356pub struct ListFilesResponse {
357 pub object: String,
359 pub data: Vec<File>,
361 #[serde(default)]
363 pub has_more: bool,
364 #[serde(skip_serializing_if = "Option::is_none")]
366 pub first_id: Option<String>,
367 #[serde(skip_serializing_if = "Option::is_none")]
369 pub last_id: Option<String>,
370}
371
372impl ListFilesResponse {
373 #[must_use]
375 pub fn empty() -> Self {
376 Self {
377 object: "list".to_string(),
378 data: Vec::new(),
379 has_more: false,
380 first_id: None,
381 last_id: None,
382 }
383 }
384
385 #[must_use]
387 pub fn files_by_purpose(&self, purpose: &FilePurpose) -> Vec<&File> {
388 let purpose_str = purpose.to_string();
389 self.data
390 .iter()
391 .filter(|file| file.purpose == purpose_str)
392 .collect()
393 }
394
395 #[must_use]
397 pub fn total_size(&self) -> u64 {
398 self.data.iter().map(|file| file.bytes).sum()
399 }
400
401 #[must_use]
403 pub fn total_size_human_readable(&self) -> String {
404 bytes_to_human_readable(self.total_size())
405 }
406}
407
408#[derive(Debug, Clone, Ser, De)]
410pub struct FileDeleteResponse {
411 pub id: String,
413 pub object: String,
415 pub deleted: bool,
417}
418
419crate::impl_response_constructors!(FileDeleteResponse, id, "file");
420
421#[derive(Debug, Clone, Default)]
423pub struct ListFilesParams {
424 pub purpose: Option<FilePurpose>,
426 pub limit: Option<u32>,
428 pub after: Option<String>,
430 pub before: Option<String>,
432 pub order: Option<SortOrder>,
434}
435
436#[derive(Debug, Clone, PartialEq, Eq, Ser, De)]
438#[serde(rename_all = "snake_case")]
439pub enum SortOrder {
440 Asc,
442 Desc,
444}
445
446crate::impl_enum_display! {
447 SortOrder {
448 Asc => "asc",
449 Desc => "desc",
450 }
451}
452
453impl ListFilesParams {
454 #[must_use]
456 pub fn new() -> Self {
457 Self::default()
458 }
459
460 #[must_use]
462 pub fn with_purpose(mut self, purpose: FilePurpose) -> Self {
463 self.purpose = Some(purpose);
464 self
465 }
466
467 #[must_use]
469 pub fn with_limit(mut self, limit: u32) -> Self {
470 self.limit = Some(limit);
471 self
472 }
473
474 #[must_use]
476 pub fn with_after(mut self, after: String) -> Self {
477 self.after = Some(after);
478 self
479 }
480
481 #[must_use]
483 pub fn with_before(mut self, before: String) -> Self {
484 self.before = Some(before);
485 self
486 }
487
488 #[must_use]
490 pub fn with_order(mut self, order: SortOrder) -> Self {
491 self.order = Some(order);
492 self
493 }
494
495 #[must_use]
497 pub fn to_query_params(&self) -> Vec<(String, String)> {
498 let mut params = Vec::new();
499
500 if let Some(purpose) = &self.purpose {
501 params.push(("purpose".to_string(), purpose.to_string()));
502 }
503
504 if let Some(limit) = self.limit {
505 params.push(("limit".to_string(), limit.to_string()));
506 }
507
508 if let Some(after) = &self.after {
509 params.push(("after".to_string(), after.clone()));
510 }
511
512 if let Some(before) = &self.before {
513 params.push(("before".to_string(), before.clone()));
514 }
515
516 if let Some(order) = &self.order {
517 params.push(("order".to_string(), order.to_string()));
518 }
519
520 params
521 }
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 #[test]
529 fn test_file_purpose_display() {
530 assert_eq!(FilePurpose::FineTune.to_string(), "fine-tune");
531 assert_eq!(FilePurpose::Assistants.to_string(), "assistants");
532 assert_eq!(FilePurpose::Batch.to_string(), "batch");
533 assert_eq!(FilePurpose::UserData.to_string(), "user_data");
534 }
535
536 #[test]
537 fn test_file_purpose_from_str() {
538 assert_eq!(
539 FilePurpose::from_str("fine-tune"),
540 Ok(FilePurpose::FineTune)
541 );
542 assert_eq!(
543 FilePurpose::from_str("assistants"),
544 Ok(FilePurpose::Assistants)
545 );
546 assert!(FilePurpose::from_str("invalid").is_err());
547 }
548
549 #[test]
550 fn test_file_purpose_supports() {
551 assert!(FilePurpose::FineTune.supports_text());
552 assert!(!FilePurpose::FineTune.supports_images());
553 assert!(FilePurpose::Vision.supports_images());
554 assert!(!FilePurpose::Vision.supports_text());
555 assert!(FilePurpose::UserData.supports_text());
556 assert!(FilePurpose::UserData.supports_images());
557 }
558
559 #[test]
560 fn test_file_upload_request_validation() {
561 let valid_request = FileUploadRequest::new(
562 b"test content".to_vec(),
563 "test.jsonl".to_string(),
564 FilePurpose::FineTune,
565 );
566 assert!(valid_request.validate().is_ok());
567
568 let empty_file_request =
569 FileUploadRequest::new(Vec::new(), "test.jsonl".to_string(), FilePurpose::FineTune);
570 assert!(empty_file_request.validate().is_err());
571
572 let wrong_extension_request = FileUploadRequest::new(
573 b"test content".to_vec(),
574 "test.txt".to_string(),
575 FilePurpose::FineTune,
576 );
577 assert!(wrong_extension_request.validate().is_err());
578 }
579
580 #[test]
581 fn test_file_upload_request_mime_type() {
582 let jsonl_request = FileUploadRequest::new(
583 b"test".to_vec(),
584 "test.jsonl".to_string(),
585 FilePurpose::FineTune,
586 );
587 assert_eq!(jsonl_request.mime_type(), "application/jsonl");
588
589 let image_request = FileUploadRequest::new(
590 b"test".to_vec(),
591 "test.png".to_string(),
592 FilePurpose::Vision,
593 );
594 assert_eq!(image_request.mime_type(), "image/png");
595 }
596
597 #[test]
598 fn test_file_size_human_readable() {
599 let file = File {
600 id: "file-123".to_string(),
601 object: "file".to_string(),
602 bytes: 1024,
603 created_at: 1_640_995_200,
604 filename: "test.txt".to_string(),
605 purpose: "user_data".to_string(),
606 status: "uploaded".to_string(),
607 status_details: None,
608 };
609 assert_eq!(file.size_human_readable(), "1.0 KB");
610 }
611
612 #[test]
613 fn test_list_files_params_query() {
614 let params = ListFilesParams::new()
615 .with_purpose(FilePurpose::FineTune)
616 .with_limit(10)
617 .with_order(SortOrder::Desc);
618
619 let query_params = params.to_query_params();
620 assert_eq!(query_params.len(), 3);
621 assert!(query_params.contains(&("purpose".to_string(), "fine-tune".to_string())));
622 assert!(query_params.contains(&("limit".to_string(), "10".to_string())));
623 assert!(query_params.contains(&("order".to_string(), "desc".to_string())));
624 }
625
626 #[test]
627 fn test_list_files_response_filters() {
628 let files = vec![
629 File {
630 id: "file-1".to_string(),
631 object: "file".to_string(),
632 bytes: 100,
633 created_at: 1_640_995_200,
634 filename: "train.jsonl".to_string(),
635 purpose: "fine-tune".to_string(),
636 status: "uploaded".to_string(),
637 status_details: None,
638 },
639 File {
640 id: "file-2".to_string(),
641 object: "file".to_string(),
642 bytes: 200,
643 created_at: 1_640_995_300,
644 filename: "knowledge.pdf".to_string(),
645 purpose: "assistants".to_string(),
646 status: "uploaded".to_string(),
647 status_details: None,
648 },
649 ];
650
651 let response = ListFilesResponse {
652 object: "list".to_string(),
653 data: files,
654 has_more: false,
655 first_id: None,
656 last_id: None,
657 };
658
659 let fine_tune_files = response.files_by_purpose(&FilePurpose::FineTune);
660 assert_eq!(fine_tune_files.len(), 1);
661 assert_eq!(fine_tune_files[0].id, "file-1");
662
663 assert_eq!(response.total_size(), 300);
664 assert_eq!(response.total_size_human_readable(), "300 B");
665 }
666
667 #[test]
668 fn test_file_delete_response() {
669 let success = FileDeleteResponse::success("file-123".to_string());
670 assert!(success.deleted);
671 assert_eq!(success.id, "file-123");
672
673 let failure = FileDeleteResponse::failure("file-456".to_string());
674 assert!(!failure.deleted);
675 assert_eq!(failure.id, "file-456");
676 }
677}