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
//! Large files through the Uploads API: create an upload, add its parts in parallel, complete
//! it.
use super::raw::check_status;
use super::Client;
use crate::{box_stream, BoxFuture, BoxStream, Error, MaybeSend, MaybeSync, Result, UploadPurpose};
use bytes::{Bytes, BytesMut};
use futures::stream::{self, StreamExt, TryStreamExt};
use http::Method;
use openai_client_base::models::{
CompleteUploadRequest, CreateUploadRequest, Upload as UploadObject, UploadPart,
};
use std::future::IntoFuture;
use std::time::Duration;
use timvw_rust_runtime::multipart::{Form, Part};
use timvw_rust_runtime::{Body, Upload};
/// The largest part the Uploads API accepts: 64 MB.
pub const MAX_UPLOAD_PART_SIZE: u64 = 64_000_000;
/// How many parts are sent at the same time, by default.
pub const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
/// A file sent through the Uploads API in parts; see [`Client::upload_large_file`].
///
/// Await it (or call [`LargeUpload::send`]) to upload.
#[must_use = "a LargeUpload does nothing until awaited"]
pub struct LargeUpload<'a, T = ()> {
client: &'a Client<T>,
upload: Upload,
filename: Option<String>,
purpose: UploadPurpose,
mime_type: Option<String>,
part_size: u64,
concurrency: usize,
part_retries: usize,
retry_backoff: Duration,
md5: Option<String>,
}
impl<T> std::fmt::Debug for LargeUpload<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LargeUpload")
.field("upload", &self.upload)
.field("filename", &self.filename)
.field("purpose", &self.purpose)
.field("mime_type", &self.mime_type)
.field("part_size", &self.part_size)
.field("concurrency", &self.concurrency)
.field("part_retries", &self.part_retries)
.finish_non_exhaustive()
}
}
impl<T> Client<T> {
/// Uploads a large file (up to 8 GB) through the Uploads API: creates an upload, adds the
/// file in parts of at most 64 MB, several at a time, and completes it. The result is the
/// completed upload, whose `file` is the `File` object to use like any uploaded file.
///
/// `upload` is anything that converts into a [`Upload`]: a path (`PathBuf`, `&Path`), bytes
/// (`Vec<u8>`, `Bytes`), or an `Upload` made from a reader or a stream (give it its length
/// with [`Upload::len`]: the Uploads API needs the size up front).
///
/// The file name is the upload's ([`Upload::name`]: a path's last component, or the one set
/// with [`Upload::file_name`]) unless set with [`filename`](LargeUpload::filename); an upload
/// without one is rejected. The media type is the upload's ([`Upload::media_type`]: guessed
/// from a path's extension, or set with [`Upload::mime`]) unless set with
/// [`mime_type`](LargeUpload::mime_type), and `application/octet-stream` otherwise. The API
/// checks it against the purpose: set it when the guess is not what the API expects (such
/// as `text/jsonl` for a fine-tuning file).
///
/// - A file is read part by part, each part straight from its offset in the file
/// ([`Upload::slice`]), and bytes are sliced without a copy. A stream or a reader is read
/// once, in order, holding at most [`concurrency`](LargeUpload::concurrency) + 1 parts in
/// memory.
/// - Each part is its own request, so the client's retry layer retries it on its own; on top
/// of that a part whose request fails with a transport error, a `408`, a `429` or a `5xx`
/// is sent again up to [`part_retries`](LargeUpload::part_retries) times.
/// - When a part fails for good, the upload is cancelled and the error returned.
///
/// Interceptors are not called for these requests.
///
/// ```rust,no_run
/// use openai_ergonomic::{Client, UploadPurpose};
/// use std::path::PathBuf;
///
/// # async fn example() -> openai_ergonomic::Result<()> {
/// let client = Client::from_env()?.build();
/// let upload = client
/// .upload_large_file(PathBuf::from("training.jsonl"), UploadPurpose::FineTune)
/// .mime_type("text/jsonl")
/// .concurrency(8)
/// .await?;
/// println!("file: {:?}", upload.file);
/// # Ok(())
/// # }
/// ```
pub fn upload_large_file(
&self,
upload: impl Into<Upload>,
purpose: UploadPurpose,
) -> LargeUpload<'_, T> {
LargeUpload {
client: self,
upload: upload.into(),
filename: None,
purpose,
mime_type: None,
part_size: MAX_UPLOAD_PART_SIZE,
concurrency: DEFAULT_UPLOAD_CONCURRENCY,
part_retries: 2,
retry_backoff: Duration::from_millis(500),
md5: None,
}
}
}
impl<T> LargeUpload<'_, T> {
/// The name of the file (default: the upload's, [`Upload::name`]).
pub fn filename(mut self, filename: impl Into<String>) -> Self {
self.filename = Some(filename.into());
self
}
/// The media type of the file (default: the upload's, [`Upload::media_type`], or else
/// `application/octet-stream`).
pub fn mime_type(mut self, mime_type: impl Into<String>) -> Self {
self.mime_type = Some(mime_type.into());
self
}
/// The size of each part but the last (default and maximum [`MAX_UPLOAD_PART_SIZE`]).
pub fn part_size(mut self, bytes: u64) -> Self {
self.part_size = bytes;
self
}
/// How many parts are sent at the same time (default [`DEFAULT_UPLOAD_CONCURRENCY`]).
pub fn concurrency(mut self, parts: usize) -> Self {
self.concurrency = parts.max(1);
self
}
/// How many more times a failed part is sent (default 2).
pub fn part_retries(mut self, retries: usize) -> Self {
self.part_retries = retries;
self
}
/// The wait before a part is sent again (default 500 ms), doubled on each retry.
pub fn retry_backoff(mut self, backoff: Duration) -> Self {
self.retry_backoff = backoff;
self
}
/// The MD5 checksum of the whole file, which the API checks when completing the upload.
pub fn md5(mut self, md5: impl Into<String>) -> Self {
self.md5 = Some(md5.into());
self
}
/// Uploads the file; see [`Client::upload_large_file`].
pub async fn send(self) -> Result<UploadObject> {
if self.part_size == 0 || self.part_size > MAX_UPLOAD_PART_SIZE {
return Err(Error::InvalidRequest(format!(
"the part size must be between 1 and {MAX_UPLOAD_PART_SIZE} bytes, not {}",
self.part_size
)));
}
let filename = self
.filename
.clone()
.or_else(|| self.upload.name().map(str::to_string))
.ok_or_else(|| {
Error::InvalidRequest(
"the upload has no file name: set it with `LargeUpload::filename` or `Upload::file_name`"
.to_string(),
)
})?;
let mime_type = self
.mime_type
.clone()
.or_else(|| self.upload.media_type().map(str::to_string))
.unwrap_or_else(|| "application/octet-stream".to_string());
let upload = self.upload.clone().resolve().await?;
let length = upload.content_length().ok_or_else(|| {
Error::InvalidRequest(
"the length of the upload is unknown: set it with `Upload::len`".to_string(),
)
})?;
let request = CreateUploadRequest {
filename,
purpose: self.purpose,
bytes: i64::try_from(length)
.map_err(|_| Error::InvalidRequest("the upload is too large".to_string()))?,
mime_type,
expires_after: None,
};
let created: UploadObject = self.client.post_json("/uploads", &request).await?;
match self.send_parts(&created.id, upload, length).await {
Ok(part_ids) => {
let complete = CompleteUploadRequest {
part_ids,
md5: self.md5.clone(),
};
self.client
.post_json(&format!("/uploads/{}/complete", created.id), &complete)
.await
}
Err(error) => {
// Best effort: the upload expires anyway.
let cancelled: Result<serde_json::Value> = self
.client
.post_json(&format!("/uploads/{}/cancel", created.id), &())
.await;
if let Err(cancel_error) = cancelled {
tracing::debug!("failed to cancel upload {}: {cancel_error}", created.id);
}
Err(error)
}
}
}
/// Sends the parts, `concurrency` at a time, and returns their IDs in order.
async fn send_parts(
&self,
upload_id: &str,
upload: Upload,
length: u64,
) -> Result<Vec<String>> {
let parts = split(upload, length, self.part_size);
parts
.map_ok(|part| self.send_part(upload_id, part))
.try_buffered(self.concurrency)
.try_collect()
.await
}
/// Sends one part, again after a transient failure.
async fn send_part(&self, upload_id: &str, part: Upload) -> Result<String> {
let path = format!("/uploads/{upload_id}/parts");
let mut attempt = 0;
loop {
let form = Form::new().part("data", Part::upload(part.clone()));
let sent = async {
let response = self
.client
.raw_request(Method::POST, &path)
.multipart(form)
.send()
.await?;
let part: UploadPart = check_status(response).await?.json().await?;
Ok::<_, Error>(part.id)
}
.await;
match sent {
Ok(id) => return Ok(id),
Err(error) if attempt < self.part_retries && is_transient(&error) => {
let backoff = self
.retry_backoff
.saturating_mul(1 << attempt.min(16))
.min(Duration::from_secs(30));
tracing::debug!(
"retrying a part of upload {upload_id} in {backoff:?}: {error}"
);
crate::time::sleep(backoff).await;
attempt += 1;
}
Err(error) => return Err(error),
}
}
}
}
impl<'a, T: MaybeSend + MaybeSync> IntoFuture for LargeUpload<'a, T> {
type Output = Result<UploadObject>;
type IntoFuture = BoxFuture<'a, Result<UploadObject>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.send())
}
}
/// Whether sending a part again may succeed.
fn is_transient(error: &Error) -> bool {
match error {
Error::Http(error) => !error.is_builder(),
Error::Api {
status, error_code, ..
} => {
(*status == 408 || *status == 429 || *status >= 500)
&& error_code.as_deref() != Some("insufficient_quota")
}
_ => false,
}
}
/// The parts of an upload of `length` bytes: slices of a source that can be read again (a file,
/// bytes), or chunks read in order from a stream. An empty upload has one empty part.
fn split(upload: Upload, length: u64, part_size: u64) -> BoxStream<'static, Result<Upload>> {
if length == 0 {
return box_stream(stream::once(async { Ok(Upload::bytes(Bytes::new())) }));
}
if upload.is_replayable() {
let count = length.div_ceil(part_size);
return box_stream(stream::iter((0..count).map(move |index| {
let start = index * part_size;
let end = (start + part_size).min(length);
Ok(upload.clone().slice(start..end))
})));
}
let response = timvw_rust_runtime::Response::from(http::Response::new(Body::from(upload)));
let part_size = usize::try_from(part_size).unwrap_or(usize::MAX);
box_stream(stream::try_unfold(
(
box_stream(response.bytes_stream()),
BytesMut::new(),
0u64,
false,
),
move |(mut chunks, mut buffer, mut read, mut done)| async move {
while !done && buffer.len() < part_size {
match chunks.next().await {
Some(chunk) => {
let chunk = chunk?;
read += chunk.len() as u64;
buffer.extend_from_slice(&chunk);
}
None => done = true,
}
}
if read > length || (done && read < length) {
return Err(Error::InvalidRequest(format!(
"the upload has {read} bytes{}, not the {length} it was declared with",
if done { "" } else { " or more" }
)));
}
if buffer.is_empty() {
return Ok(None);
}
let part = buffer.split_to(buffer.len().min(part_size)).freeze();
Ok(Some((Upload::bytes(part), (chunks, buffer, read, done))))
},
))
}