Skip to main content

openai_rust_sdk/models/
files.rs

1//! # Files API Models
2//!
3//! This module provides data structures for OpenAI's Files API, which allows you to
4//! upload and manage files that can be used with various OpenAI services.
5//!
6//! ## Overview
7//!
8//! The Files API supports uploading files for use with:
9//! - **Fine-tuning**: Training data for custom models
10//! - **Assistants**: Documents for retrieval and knowledge
11//! - **Batch processing**: Input files for batch API
12//! - **Vision**: Images for analysis
13//! - **User data**: General purpose file storage
14//!
15//! ## File Purposes
16//!
17//! Each file must be uploaded with a specific purpose that determines how it can be used:
18//!
19//! - `fine-tune`: For fine-tuning datasets
20//! - `assistants`: For Assistants API retrieval
21//! - `batch`: For Batch API input files
22//! - `user_data`: For general file storage
23//! - `responses`: For storing API responses
24//! - `vision`: For image analysis
25//!
26//! ## Examples
27//!
28//! ```rust
29//! use openai_rust_sdk::models::files::{FileUploadRequest, FilePurpose};
30//!
31//! // Create a file upload request for fine-tuning
32//! let upload_request = FileUploadRequest {
33//!     file: vec![/* file bytes */],
34//!     filename: "training_data.jsonl".to_string(),
35//!     purpose: FilePurpose::FineTune,
36//! };
37//! ```
38
39use crate::api::base::Validate;
40use crate::{De, Ser};
41use serde::{self, Deserialize, Serialize};
42use std::fmt;
43use std::str::FromStr;
44
45// Generate the bytes to human readable function
46crate::impl_bytes_to_human_readable!();
47
48/// Purpose for which a file is being uploaded
49#[derive(Debug, Clone, PartialEq, Eq, Ser, De)]
50#[serde(rename_all = "snake_case")]
51pub enum FilePurpose {
52    /// Fine-tuning training data
53    FineTune,
54    /// Files for Assistants API (retrieval, knowledge base)
55    Assistants,
56    /// Batch processing input files
57    Batch,
58    /// General user data storage
59    UserData,
60    /// API response storage
61    Responses,
62    /// Vision/image analysis files
63    Vision,
64    /// Fine-tuning results and outputs
65    FineTuneResults,
66    /// Assistants retrieval files
67    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    /// Returns all valid file purposes
103    #[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    /// Check if this purpose supports text files
118    #[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    /// Check if this purpose supports image files
131    #[must_use]
132    pub fn supports_images(&self) -> bool {
133        matches!(self, FilePurpose::Vision | FilePurpose::UserData)
134    }
135}
136
137/// Status of a file upload or processing
138#[derive(Debug, Clone, PartialEq, Eq, Ser, De)]
139#[serde(rename_all = "snake_case")]
140pub enum FileStatus {
141    /// File has been uploaded successfully
142    Uploaded,
143    /// File is being processed
144    Processed,
145    /// File processing failed
146    Error,
147    /// File has been deleted
148    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/// Represents a file object in `OpenAI`'s system
161#[derive(Debug, Clone, Ser, De)]
162pub struct File {
163    /// Unique identifier for the file
164    pub id: String,
165    /// The object type, which is always "file"
166    pub object: String,
167    /// The size of the file, in bytes
168    pub bytes: u64,
169    /// The Unix timestamp (in seconds) for when the file was created
170    pub created_at: u64,
171    /// The name of the file
172    pub filename: String,
173    /// The intended purpose of the file
174    pub purpose: String,
175    /// The current status of the file
176    #[serde(default = "default_file_status")]
177    pub status: String,
178    /// Additional details about the file's status, if available
179    #[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    /// Get the file purpose as a typed enum
187    #[must_use]
188    pub fn purpose_enum(&self) -> Option<FilePurpose> {
189        FilePurpose::from_str(&self.purpose).ok()
190    }
191
192    /// Check if this file can be used for fine-tuning
193    #[must_use]
194    pub fn is_fine_tune_file(&self) -> bool {
195        self.purpose == "fine-tune"
196    }
197
198    /// Check if this file can be used with Assistants
199    #[must_use]
200    pub fn is_assistants_file(&self) -> bool {
201        self.purpose == "assistants"
202    }
203
204    /// Check if this file can be used for batch processing
205    #[must_use]
206    pub fn is_batch_file(&self) -> bool {
207        self.purpose == "batch"
208    }
209
210    /// Get human-readable file size
211    #[must_use]
212    pub fn size_human_readable(&self) -> String {
213        bytes_to_human_readable(self.bytes)
214    }
215
216    /// Get the creation date as a formatted string
217    #[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/// Request structure for uploading a file
226#[derive(Debug, Clone)]
227pub struct FileUploadRequest {
228    /// The file content as bytes
229    pub file: Vec<u8>,
230    /// The name of the file being uploaded
231    pub filename: String,
232    /// The intended purpose of the file
233    pub purpose: FilePurpose,
234}
235
236impl FileUploadRequest {
237    /// Create a new file upload request
238    #[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    /// Create a file upload request from a file path
248    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    /// Validate the file upload request
263    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        // Check file size limits (200MB for most purposes)
273        const MAX_FILE_SIZE: usize = 200 * 1024 * 1024; // 200MB
274        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        // Validate file extension for certain purposes
283        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            _ => {} // Other purposes allow various file types
302        }
303
304        Ok(())
305    }
306
307    /// Get the MIME type for the file based on its extension
308    #[must_use]
309    pub fn mime_type(&self) -> &'static str {
310        Self::determine_mime_type(&self.filename)
311    }
312
313    /// Determine MIME type from filename
314    fn determine_mime_type(filename: &str) -> &'static str {
315        let filename_lower = filename.to_lowercase();
316
317        // Use pattern matching on extension for better performance
318        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    /// Extract file extension from lowercase filename
326    fn extract_extension(filename_lower: &str) -> Option<&str> {
327        filename_lower.rfind('.').map(|pos| &filename_lower[pos..])
328    }
329
330    /// Get MIME type for a given extension
331    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
347/// Implementation of Validate trait for FileUploadRequest
348impl Validate for FileUploadRequest {
349    fn validate(&self) -> Result<(), String> {
350        self.validate()
351    }
352}
353
354/// Response from the list files API endpoint
355#[derive(Debug, Clone, Ser, De)]
356pub struct ListFilesResponse {
357    /// The object type, which is always "list"
358    pub object: String,
359    /// The list of files
360    pub data: Vec<File>,
361    /// Whether there are more results available
362    #[serde(default)]
363    pub has_more: bool,
364    /// Cursor for the first item in the list (for pagination)
365    #[serde(skip_serializing_if = "Option::is_none")]
366    pub first_id: Option<String>,
367    /// Cursor for the last item in the list (for pagination)
368    #[serde(skip_serializing_if = "Option::is_none")]
369    pub last_id: Option<String>,
370}
371
372impl ListFilesResponse {
373    /// Create a new empty list response
374    #[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    /// Get files by purpose
386    #[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    /// Get total size of all files in bytes
396    #[must_use]
397    pub fn total_size(&self) -> u64 {
398        self.data.iter().map(|file| file.bytes).sum()
399    }
400
401    /// Get total size in human-readable format
402    #[must_use]
403    pub fn total_size_human_readable(&self) -> String {
404        bytes_to_human_readable(self.total_size())
405    }
406}
407
408/// Response from deleting a file
409#[derive(Debug, Clone, Ser, De)]
410pub struct FileDeleteResponse {
411    /// Unique identifier for the file that was deleted
412    pub id: String,
413    /// The object type, which is always "file"
414    pub object: String,
415    /// Whether the file was successfully deleted
416    pub deleted: bool,
417}
418
419crate::impl_response_constructors!(FileDeleteResponse, id, "file");
420
421/// Parameters for listing files
422#[derive(Debug, Clone, Default)]
423pub struct ListFilesParams {
424    /// Filter files by purpose
425    pub purpose: Option<FilePurpose>,
426    /// Maximum number of files to return (default 20, max 10,000)
427    pub limit: Option<u32>,
428    /// Pagination cursor - list files after this ID
429    pub after: Option<String>,
430    /// Pagination cursor - list files before this ID  
431    pub before: Option<String>,
432    /// Sort order for the results
433    pub order: Option<SortOrder>,
434}
435
436/// Sort order for file listings
437#[derive(Debug, Clone, PartialEq, Eq, Ser, De)]
438#[serde(rename_all = "snake_case")]
439pub enum SortOrder {
440    /// Sort by creation date, ascending (oldest first)
441    Asc,
442    /// Sort by creation date, descending (newest first)
443    Desc,
444}
445
446crate::impl_enum_display! {
447    SortOrder {
448        Asc => "asc",
449        Desc => "desc",
450    }
451}
452
453impl ListFilesParams {
454    /// Create new parameters with default values
455    #[must_use]
456    pub fn new() -> Self {
457        Self::default()
458    }
459
460    /// Set the purpose filter
461    #[must_use]
462    pub fn with_purpose(mut self, purpose: FilePurpose) -> Self {
463        self.purpose = Some(purpose);
464        self
465    }
466
467    /// Set the limit
468    #[must_use]
469    pub fn with_limit(mut self, limit: u32) -> Self {
470        self.limit = Some(limit);
471        self
472    }
473
474    /// Set the after cursor for pagination
475    #[must_use]
476    pub fn with_after(mut self, after: String) -> Self {
477        self.after = Some(after);
478        self
479    }
480
481    /// Set the before cursor for pagination
482    #[must_use]
483    pub fn with_before(mut self, before: String) -> Self {
484        self.before = Some(before);
485        self
486    }
487
488    /// Set the sort order
489    #[must_use]
490    pub fn with_order(mut self, order: SortOrder) -> Self {
491        self.order = Some(order);
492        self
493    }
494
495    /// Build query parameters for the API request
496    #[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}