openai-tools 1.1.0

Tools for OpenAI API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! OpenAI Files API Request Module
//!
//! This module provides the functionality to interact with the OpenAI Files API.
//! It allows you to upload, list, retrieve, delete files, and get file content.
//!
//! # Key Features
//!
//! - **Upload Files**: Upload files for fine-tuning, batch processing, assistants, etc.
//! - **List Files**: Retrieve all uploaded files
//! - **Retrieve File**: Get details of a specific file
//! - **Delete File**: Remove an uploaded file
//! - **Get Content**: Retrieve the content of a file
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use openai_tools::files::request::{Files, FilePurpose};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let files = Files::new()?;
//!
//!     // List all files
//!     let response = files.list(None).await?;
//!     for file in &response.data {
//!         println!("{}: {} bytes", file.filename, file.bytes);
//!     }
//!
//!     Ok(())
//! }
//! ```

use crate::common::auth::{AuthProvider, OpenAIAuth};
use crate::common::client::create_http_client;
use crate::common::errors::{ErrorResponse, OpenAIToolError, Result};
use crate::files::response::{DeleteResponse, File, FileListResponse};
use request::multipart::{Form, Part};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::time::Duration;

/// Default API path for Files
const FILES_PATH: &str = "files";

/// The intended purpose of the uploaded file.
///
/// Different purposes have different processing requirements and usage patterns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FilePurpose {
    /// For use with Assistants and Message files
    Assistants,
    /// For files generated by Assistants
    AssistantsOutput,
    /// For use with Batch API
    Batch,
    /// For files generated by Batch API
    BatchOutput,
    /// For use with Fine-tuning
    FineTune,
    /// For files generated by Fine-tuning
    FineTuneResults,
    /// For use with Vision features
    Vision,
    /// For user-uploaded data
    UserData,
}

impl FilePurpose {
    /// Returns the string representation of the purpose.
    pub fn as_str(&self) -> &'static str {
        match self {
            FilePurpose::Assistants => "assistants",
            FilePurpose::AssistantsOutput => "assistants_output",
            FilePurpose::Batch => "batch",
            FilePurpose::BatchOutput => "batch_output",
            FilePurpose::FineTune => "fine-tune",
            FilePurpose::FineTuneResults => "fine-tune-results",
            FilePurpose::Vision => "vision",
            FilePurpose::UserData => "user_data",
        }
    }
}

impl std::fmt::Display for FilePurpose {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Client for interacting with the OpenAI Files API.
///
/// This struct provides methods to upload, list, retrieve, delete files,
/// and get file content. Use [`Files::new()`] to create a new instance.
///
/// # Providers
///
/// The client supports two providers:
/// - **OpenAI**: Standard OpenAI API (default)
/// - **Azure**: Azure OpenAI Service
///
/// # Example
///
/// ```rust,no_run
/// use openai_tools::files::request::{Files, FilePurpose};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let files = Files::new()?;
///
///     // Upload a file for fine-tuning
///     let file = files.upload_path("training_data.jsonl", FilePurpose::FineTune).await?;
///     println!("Uploaded: {} ({})", file.filename, file.id);
///
///     Ok(())
/// }
/// ```
pub struct Files {
    /// Authentication provider (OpenAI or Azure)
    auth: AuthProvider,
    /// Optional request timeout duration
    timeout: Option<Duration>,
}

impl Files {
    /// Creates a new Files client for OpenAI API.
    ///
    /// Initializes the client by loading the OpenAI API key from
    /// the environment variable `OPENAI_API_KEY`. Supports `.env` file loading
    /// via dotenvy.
    ///
    /// # Returns
    ///
    /// * `Ok(Files)` - A new Files client ready for use
    /// * `Err(OpenAIToolError)` - If the API key is not found in the environment
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_tools::files::request::Files;
    ///
    /// let files = Files::new().expect("API key should be set");
    /// ```
    pub fn new() -> Result<Self> {
        let auth = AuthProvider::openai_from_env()?;
        Ok(Self { auth, timeout: None })
    }

    /// Creates a new Files client with a custom authentication provider
    pub fn with_auth(auth: AuthProvider) -> Self {
        Self { auth, timeout: None }
    }

    /// Creates a new Files client for Azure OpenAI API
    pub fn azure() -> Result<Self> {
        let auth = AuthProvider::azure_from_env()?;
        Ok(Self { auth, timeout: None })
    }

    /// Creates a new Files client by auto-detecting the provider
    pub fn detect_provider() -> Result<Self> {
        let auth = AuthProvider::from_env()?;
        Ok(Self { auth, timeout: None })
    }

    /// Creates a new Files client with URL-based provider detection
    pub fn with_url<S: Into<String>>(base_url: S, api_key: S) -> Self {
        let auth = AuthProvider::from_url_with_key(base_url, api_key);
        Self { auth, timeout: None }
    }

    /// Creates a new Files client from URL using environment variables
    pub fn from_url<S: Into<String>>(url: S) -> Result<Self> {
        let auth = AuthProvider::from_url(url)?;
        Ok(Self { auth, timeout: None })
    }

    /// Returns the authentication provider
    pub fn auth(&self) -> &AuthProvider {
        &self.auth
    }

    /// Sets a custom API endpoint URL (OpenAI only)
    ///
    /// Use this to point to alternative OpenAI-compatible APIs.
    ///
    /// # Arguments
    ///
    /// * `url` - The base URL (e.g., "https://my-proxy.example.com/v1")
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    pub fn base_url<T: AsRef<str>>(&mut self, url: T) -> &mut Self {
        if let AuthProvider::OpenAI(ref openai_auth) = self.auth {
            let new_auth = OpenAIAuth::new(openai_auth.api_key()).with_base_url(url.as_ref());
            self.auth = AuthProvider::OpenAI(new_auth);
        } else {
            tracing::warn!("base_url() is only supported for OpenAI provider. Use azure() or with_auth() for Azure.");
        }
        self
    }

    /// Sets the request timeout duration.
    ///
    /// # Arguments
    ///
    /// * `timeout` - The maximum time to wait for a response
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use std::time::Duration;
    /// use openai_tools::files::request::Files;
    ///
    /// let mut files = Files::new().unwrap();
    /// files.timeout(Duration::from_secs(120));  // Longer timeout for file uploads
    /// ```
    pub fn timeout(&mut self, timeout: Duration) -> &mut Self {
        self.timeout = Some(timeout);
        self
    }

    /// Creates the HTTP client with default headers.
    fn create_client(&self) -> Result<(request::Client, request::header::HeaderMap)> {
        let client = create_http_client(self.timeout)?;
        let mut headers = request::header::HeaderMap::new();
        self.auth.apply_headers(&mut headers)?;
        headers.insert("User-Agent", request::header::HeaderValue::from_static("openai-tools-rust"));
        Ok((client, headers))
    }

    /// Uploads a file from a file path.
    ///
    /// The file will be uploaded with the specified purpose.
    /// Individual files can be up to 512 MB, and the total size of all files
    /// uploaded by one organization can be up to 100 GB.
    ///
    /// # Arguments
    ///
    /// * `file_path` - Path to the file to upload
    /// * `purpose` - The intended purpose of the uploaded file
    ///
    /// # Returns
    ///
    /// * `Ok(File)` - The uploaded file object
    /// * `Err(OpenAIToolError)` - If the file cannot be read or the upload fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_tools::files::request::{Files, FilePurpose};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let files = Files::new()?;
    ///     let file = files.upload_path("data.jsonl", FilePurpose::FineTune).await?;
    ///     println!("Uploaded: {}", file.id);
    ///     Ok(())
    /// }
    /// ```
    pub async fn upload_path(&self, file_path: &str, purpose: FilePurpose) -> Result<File> {
        let path = Path::new(file_path);
        let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();

        let content = tokio::fs::read(file_path).await.map_err(|e| OpenAIToolError::Error(format!("Failed to read file: {}", e)))?;

        self.upload_bytes(&content, &filename, purpose).await
    }

    /// Uploads a file from bytes.
    ///
    /// The file will be uploaded with the specified filename and purpose.
    ///
    /// # Arguments
    ///
    /// * `content` - The file content as bytes
    /// * `filename` - The name to give the file
    /// * `purpose` - The intended purpose of the uploaded file
    ///
    /// # Returns
    ///
    /// * `Ok(File)` - The uploaded file object
    /// * `Err(OpenAIToolError)` - If the upload fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_tools::files::request::{Files, FilePurpose};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let files = Files::new()?;
    ///
    ///     let content = b"{\"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]}";
    ///     let file = files.upload_bytes(content, "training.jsonl", FilePurpose::FineTune).await?;
    ///
    ///     println!("Uploaded: {}", file.id);
    ///     Ok(())
    /// }
    /// ```
    pub async fn upload_bytes(&self, content: &[u8], filename: &str, purpose: FilePurpose) -> Result<File> {
        let (client, headers) = self.create_client()?;

        let file_part = Part::bytes(content.to_vec())
            .file_name(filename.to_string())
            .mime_str("application/octet-stream")
            .map_err(|e| OpenAIToolError::Error(format!("Failed to set MIME type: {}", e)))?;

        let form = Form::new().part("file", file_part).text("purpose", purpose.as_str().to_string());

        let endpoint = self.auth.endpoint(FILES_PATH);
        let response = client.post(&endpoint).headers(headers).multipart(form).send().await.map_err(OpenAIToolError::RequestError)?;

        let status = response.status();
        let content = response.text().await.map_err(OpenAIToolError::RequestError)?;

        if cfg!(test) {
            tracing::info!("Response content: {}", content);
        }

        if !status.is_success() {
            if let Ok(error_resp) = serde_json::from_str::<ErrorResponse>(&content) {
                return Err(OpenAIToolError::Error(error_resp.error.message.unwrap_or_default()));
            }
            return Err(OpenAIToolError::Error(format!("API error ({}): {}", status, content)));
        }

        serde_json::from_str::<File>(&content).map_err(OpenAIToolError::SerdeJsonError)
    }

    /// Lists all files that belong to the user's organization.
    ///
    /// Optionally filter by purpose.
    ///
    /// # Arguments
    ///
    /// * `purpose` - Optional filter by file purpose
    ///
    /// # Returns
    ///
    /// * `Ok(FileListResponse)` - The list of files
    /// * `Err(OpenAIToolError)` - If the request fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_tools::files::request::{Files, FilePurpose};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let files = Files::new()?;
    ///
    ///     // List all files
    ///     let all_files = files.list(None).await?;
    ///     println!("Total files: {}", all_files.data.len());
    ///
    ///     // List only fine-tuning files
    ///     let ft_files = files.list(Some(FilePurpose::FineTune)).await?;
    ///     println!("Fine-tuning files: {}", ft_files.data.len());
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn list(&self, purpose: Option<FilePurpose>) -> Result<FileListResponse> {
        let (client, headers) = self.create_client()?;

        let endpoint = self.auth.endpoint(FILES_PATH);
        let url = match purpose {
            Some(p) => format!("{}?purpose={}", endpoint, p.as_str()),
            None => endpoint,
        };

        let response = client.get(&url).headers(headers).send().await.map_err(OpenAIToolError::RequestError)?;

        let status = response.status();
        let content = response.text().await.map_err(OpenAIToolError::RequestError)?;

        if cfg!(test) {
            tracing::info!("Response content: {}", content);
        }

        if !status.is_success() {
            if let Ok(error_resp) = serde_json::from_str::<ErrorResponse>(&content) {
                return Err(OpenAIToolError::Error(error_resp.error.message.unwrap_or_default()));
            }
            return Err(OpenAIToolError::Error(format!("API error ({}): {}", status, content)));
        }

        serde_json::from_str::<FileListResponse>(&content).map_err(OpenAIToolError::SerdeJsonError)
    }

    /// Retrieves details of a specific file.
    ///
    /// # Arguments
    ///
    /// * `file_id` - The ID of the file to retrieve
    ///
    /// # Returns
    ///
    /// * `Ok(File)` - The file details
    /// * `Err(OpenAIToolError)` - If the file is not found or the request fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_tools::files::request::Files;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let files = Files::new()?;
    ///     let file = files.retrieve("file-abc123").await?;
    ///
    ///     println!("File: {}", file.filename);
    ///     println!("Size: {} bytes", file.bytes);
    ///     println!("Purpose: {}", file.purpose);
    ///     Ok(())
    /// }
    /// ```
    pub async fn retrieve(&self, file_id: &str) -> Result<File> {
        let (client, headers) = self.create_client()?;
        let url = format!("{}/{}", self.auth.endpoint(FILES_PATH), file_id);

        let response = client.get(&url).headers(headers).send().await.map_err(OpenAIToolError::RequestError)?;

        let status = response.status();
        let content = response.text().await.map_err(OpenAIToolError::RequestError)?;

        if cfg!(test) {
            tracing::info!("Response content: {}", content);
        }

        if !status.is_success() {
            if let Ok(error_resp) = serde_json::from_str::<ErrorResponse>(&content) {
                return Err(OpenAIToolError::Error(error_resp.error.message.unwrap_or_default()));
            }
            return Err(OpenAIToolError::Error(format!("API error ({}): {}", status, content)));
        }

        serde_json::from_str::<File>(&content).map_err(OpenAIToolError::SerdeJsonError)
    }

    /// Deletes a file.
    ///
    /// # Arguments
    ///
    /// * `file_id` - The ID of the file to delete
    ///
    /// # Returns
    ///
    /// * `Ok(DeleteResponse)` - Confirmation of deletion
    /// * `Err(OpenAIToolError)` - If the file cannot be deleted or the request fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_tools::files::request::Files;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let files = Files::new()?;
    ///     let result = files.delete("file-abc123").await?;
    ///
    ///     if result.deleted {
    ///         println!("File {} was deleted", result.id);
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn delete(&self, file_id: &str) -> Result<DeleteResponse> {
        let (client, headers) = self.create_client()?;
        let url = format!("{}/{}", self.auth.endpoint(FILES_PATH), file_id);

        let response = client.delete(&url).headers(headers).send().await.map_err(OpenAIToolError::RequestError)?;

        let status = response.status();
        let content = response.text().await.map_err(OpenAIToolError::RequestError)?;

        if cfg!(test) {
            tracing::info!("Response content: {}", content);
        }

        if !status.is_success() {
            if let Ok(error_resp) = serde_json::from_str::<ErrorResponse>(&content) {
                return Err(OpenAIToolError::Error(error_resp.error.message.unwrap_or_default()));
            }
            return Err(OpenAIToolError::Error(format!("API error ({}): {}", status, content)));
        }

        serde_json::from_str::<DeleteResponse>(&content).map_err(OpenAIToolError::SerdeJsonError)
    }

    /// Retrieves the content of a file.
    ///
    /// # Arguments
    ///
    /// * `file_id` - The ID of the file to retrieve content from
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<u8>)` - The file content as bytes
    /// * `Err(OpenAIToolError)` - If the file cannot be retrieved or the request fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openai_tools::files::request::Files;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let files = Files::new()?;
    ///     let content = files.content("file-abc123").await?;
    ///
    ///     // Convert to string if it's text content
    ///     let text = String::from_utf8(content)?;
    ///     println!("Content: {}", text);
    ///     Ok(())
    /// }
    /// ```
    pub async fn content(&self, file_id: &str) -> Result<Vec<u8>> {
        let (client, headers) = self.create_client()?;
        let url = format!("{}/{}/content", self.auth.endpoint(FILES_PATH), file_id);

        let response = client.get(&url).headers(headers).send().await.map_err(OpenAIToolError::RequestError)?;

        let bytes = response.bytes().await.map_err(OpenAIToolError::RequestError)?;

        Ok(bytes.to_vec())
    }
}