Skip to main content

openai_interface/uploads/
parts.rs

1//! Add an upload part via `POST /uploads/{upload_id}/parts`.
2//!
3//! > ![warn] This module is untested!
4//! > If you encounter any issues, please report them on the repository.
5//!
6//! Each part can be up to 64 MB except the last, which may be smaller.
7//! Parts must be added in order and the combined size must match the
8//! declared upload size.
9
10use url::Url;
11
12use crate::{
13    errors::OapiError,
14    rest::post::{Post, PostNoStream},
15    uploads::UploadPart,
16};
17
18/// Adds a chunk of bytes to an upload session.
19#[derive(Debug, Clone, serde::Serialize)]
20pub struct AddUploadPartRequest<'a> {
21    /// The ID of the upload session, e.g. `upload_...`.
22    #[serde(skip)]
23    pub upload_id: &'a str,
24    /// The chunk of bytes for this part.
25    pub data: Vec<u8>,
26}
27
28impl Post for AddUploadPartRequest<'_> {
29    fn is_streaming(&self) -> bool {
30        false
31    }
32
33    /// Builds the URL for the request.
34    ///
35    /// `base_url` should be like <https://api.openai.com/v1>
36    fn build_url(&self, base_url: &str) -> Result<String, OapiError> {
37        let mut url = Url::parse(base_url.trim_end_matches('/')).map_err(OapiError::UrlError)?;
38        url.path_segments_mut()
39            .map_err(|_| OapiError::UrlCannotBeBase(base_url.to_string()))?
40            .push("uploads")
41            .push(self.upload_id)
42            .push("parts");
43        Ok(url.to_string())
44    }
45}
46
47impl PostNoStream for AddUploadPartRequest<'_> {
48    type Response = UploadPart;
49
50    /// Sends the part upload POST request using multipart/form-data
51    /// format with a `data` file field.
52    async fn get_response_string(
53        &self,
54        client: &reqwest::Client,
55        url: &str,
56        key: &str,
57    ) -> Result<String, OapiError> {
58        let part = reqwest::multipart::Part::bytes(self.data.clone());
59        let form = reqwest::multipart::Form::new().part("data", part);
60
61        let response = client
62            .post(url)
63            .header("Accept", "application/json")
64            .bearer_auth(key)
65            .multipart(form)
66            .send()
67            .await?;
68
69        crate::rest::response_text_checked(response).await
70    }
71}