Skip to main content

mistral_openapi_client/apis/
files_api.rs

1/*
2 * Mistral AI API
3 *
4 * Our Chat Completion and Embeddings APIs specification. Create your account on [La Plateforme](https://console.mistral.ai) to get access and read the [docs](https://docs.mistral.ai) to learn how to use it.
5 *
6 * The version of the OpenAPI document: 1.0.0
7 * 
8 * Generated by: https://openapi-generator.tech
9 */
10
11
12use reqwest;
13use serde::{Deserialize, Serialize, de::Error as _};
14use crate::{apis::ResponseContent, models};
15use super::{Error, configuration, ContentType};
16use tokio::fs::File as TokioFile;
17use tokio_util::codec::{BytesCodec, FramedRead};
18
19
20/// struct for typed errors of method [`files_api_routes_delete_file`]
21#[derive(Debug, Clone, Serialize, Deserialize)]
22#[serde(untagged)]
23pub enum FilesApiRoutesDeleteFileError {
24    UnknownValue(serde_json::Value),
25}
26
27/// struct for typed errors of method [`files_api_routes_download_file`]
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(untagged)]
30pub enum FilesApiRoutesDownloadFileError {
31    UnknownValue(serde_json::Value),
32}
33
34/// struct for typed errors of method [`files_api_routes_get_signed_url`]
35#[derive(Debug, Clone, Serialize, Deserialize)]
36#[serde(untagged)]
37pub enum FilesApiRoutesGetSignedUrlError {
38    UnknownValue(serde_json::Value),
39}
40
41/// struct for typed errors of method [`files_api_routes_list_files`]
42#[derive(Debug, Clone, Serialize, Deserialize)]
43#[serde(untagged)]
44pub enum FilesApiRoutesListFilesError {
45    UnknownValue(serde_json::Value),
46}
47
48/// struct for typed errors of method [`files_api_routes_retrieve_file`]
49#[derive(Debug, Clone, Serialize, Deserialize)]
50#[serde(untagged)]
51pub enum FilesApiRoutesRetrieveFileError {
52    UnknownValue(serde_json::Value),
53}
54
55/// struct for typed errors of method [`files_api_routes_upload_file`]
56#[derive(Debug, Clone, Serialize, Deserialize)]
57#[serde(untagged)]
58pub enum FilesApiRoutesUploadFileError {
59    UnknownValue(serde_json::Value),
60}
61
62
63/// Delete a file.
64pub async fn files_api_routes_delete_file(configuration: &configuration::Configuration, file_id: &str) -> Result<models::DeleteFileOut, Error<FilesApiRoutesDeleteFileError>> {
65    // add a prefix to parameters to efficiently prevent name collisions
66    let p_path_file_id = file_id;
67
68    let uri_str = format!("{}/v1/files/{file_id}", configuration.base_path, file_id=crate::apis::urlencode(p_path_file_id));
69    let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str);
70
71    if let Some(ref user_agent) = configuration.user_agent {
72        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
73    }
74    if let Some(ref token) = configuration.bearer_access_token {
75        req_builder = req_builder.bearer_auth(token.to_owned());
76    };
77
78    let req = req_builder.build()?;
79    let resp = configuration.client.execute(req).await?;
80
81    let status = resp.status();
82    let content_type = resp
83        .headers()
84        .get("content-type")
85        .and_then(|v| v.to_str().ok())
86        .unwrap_or("application/octet-stream");
87    let content_type = super::ContentType::from(content_type);
88
89    if !status.is_client_error() && !status.is_server_error() {
90        let content = resp.text().await?;
91        match content_type {
92            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
93            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteFileOut`"))),
94            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteFileOut`")))),
95        }
96    } else {
97        let content = resp.text().await?;
98        let entity: Option<FilesApiRoutesDeleteFileError> = serde_json::from_str(&content).ok();
99        Err(Error::ResponseError(ResponseContent { status, content, entity }))
100    }
101}
102
103/// Download a file
104pub async fn files_api_routes_download_file(configuration: &configuration::Configuration, file_id: &str) -> Result<reqwest::Response, Error<FilesApiRoutesDownloadFileError>> {
105    // add a prefix to parameters to efficiently prevent name collisions
106    let p_path_file_id = file_id;
107
108    let uri_str = format!("{}/v1/files/{file_id}/content", configuration.base_path, file_id=crate::apis::urlencode(p_path_file_id));
109    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
110
111    if let Some(ref user_agent) = configuration.user_agent {
112        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
113    }
114    if let Some(ref token) = configuration.bearer_access_token {
115        req_builder = req_builder.bearer_auth(token.to_owned());
116    };
117
118    let req = req_builder.build()?;
119    let resp = configuration.client.execute(req).await?;
120
121    let status = resp.status();
122
123    if !status.is_client_error() && !status.is_server_error() {
124        Ok(resp)
125    } else {
126        let content = resp.text().await?;
127        let entity: Option<FilesApiRoutesDownloadFileError> = serde_json::from_str(&content).ok();
128        Err(Error::ResponseError(ResponseContent { status, content, entity }))
129    }
130}
131
132pub async fn files_api_routes_get_signed_url(configuration: &configuration::Configuration, file_id: &str, expiry: Option<i32>) -> Result<models::FileSignedUrl, Error<FilesApiRoutesGetSignedUrlError>> {
133    // add a prefix to parameters to efficiently prevent name collisions
134    let p_path_file_id = file_id;
135    let p_query_expiry = expiry;
136
137    let uri_str = format!("{}/v1/files/{file_id}/url", configuration.base_path, file_id=crate::apis::urlencode(p_path_file_id));
138    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
139
140    if let Some(ref param_value) = p_query_expiry {
141        req_builder = req_builder.query(&[("expiry", &param_value.to_string())]);
142    }
143    if let Some(ref user_agent) = configuration.user_agent {
144        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
145    }
146    if let Some(ref token) = configuration.bearer_access_token {
147        req_builder = req_builder.bearer_auth(token.to_owned());
148    };
149
150    let req = req_builder.build()?;
151    let resp = configuration.client.execute(req).await?;
152
153    let status = resp.status();
154    let content_type = resp
155        .headers()
156        .get("content-type")
157        .and_then(|v| v.to_str().ok())
158        .unwrap_or("application/octet-stream");
159    let content_type = super::ContentType::from(content_type);
160
161    if !status.is_client_error() && !status.is_server_error() {
162        let content = resp.text().await?;
163        match content_type {
164            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
165            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::FileSignedUrl`"))),
166            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::FileSignedUrl`")))),
167        }
168    } else {
169        let content = resp.text().await?;
170        let entity: Option<FilesApiRoutesGetSignedUrlError> = serde_json::from_str(&content).ok();
171        Err(Error::ResponseError(ResponseContent { status, content, entity }))
172    }
173}
174
175/// Returns a list of files that belong to the user's organization.
176pub async fn files_api_routes_list_files(configuration: &configuration::Configuration, page: Option<i32>, page_size: Option<i32>, include_total: Option<bool>, sample_type: Option<Vec<models::SampleType>>, source: Option<Vec<models::Source>>, search: Option<&str>, purpose: Option<models::FilePurpose>, mimetypes: Option<Vec<String>>) -> Result<models::ListFilesOut, Error<FilesApiRoutesListFilesError>> {
177    // add a prefix to parameters to efficiently prevent name collisions
178    let p_query_page = page;
179    let p_query_page_size = page_size;
180    let p_query_include_total = include_total;
181    let p_query_sample_type = sample_type;
182    let p_query_source = source;
183    let p_query_search = search;
184    let p_query_purpose = purpose;
185    let p_query_mimetypes = mimetypes;
186
187    let uri_str = format!("{}/v1/files", configuration.base_path);
188    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
189
190    if let Some(ref param_value) = p_query_page {
191        req_builder = req_builder.query(&[("page", &param_value.to_string())]);
192    }
193    if let Some(ref param_value) = p_query_page_size {
194        req_builder = req_builder.query(&[("page_size", &param_value.to_string())]);
195    }
196    if let Some(ref param_value) = p_query_include_total {
197        req_builder = req_builder.query(&[("include_total", &param_value.to_string())]);
198    }
199    if let Some(ref param_value) = p_query_sample_type {
200        req_builder = match "multi" {
201            "multi" => req_builder.query(&param_value.into_iter().map(|p| ("sample_type".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
202            _ => req_builder.query(&[("sample_type", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
203        };
204    }
205    if let Some(ref param_value) = p_query_source {
206        req_builder = match "multi" {
207            "multi" => req_builder.query(&param_value.into_iter().map(|p| ("source".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
208            _ => req_builder.query(&[("source", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
209        };
210    }
211    if let Some(ref param_value) = p_query_search {
212        req_builder = req_builder.query(&[("search", &param_value.to_string())]);
213    }
214    if let Some(ref param_value) = p_query_purpose {
215        req_builder = req_builder.query(&[("purpose", &param_value.to_string())]);
216    }
217    if let Some(ref param_value) = p_query_mimetypes {
218        req_builder = match "multi" {
219            "multi" => req_builder.query(&param_value.into_iter().map(|p| ("mimetypes".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
220            _ => req_builder.query(&[("mimetypes", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
221        };
222    }
223    if let Some(ref user_agent) = configuration.user_agent {
224        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
225    }
226    if let Some(ref token) = configuration.bearer_access_token {
227        req_builder = req_builder.bearer_auth(token.to_owned());
228    };
229
230    let req = req_builder.build()?;
231    let resp = configuration.client.execute(req).await?;
232
233    let status = resp.status();
234    let content_type = resp
235        .headers()
236        .get("content-type")
237        .and_then(|v| v.to_str().ok())
238        .unwrap_or("application/octet-stream");
239    let content_type = super::ContentType::from(content_type);
240
241    if !status.is_client_error() && !status.is_server_error() {
242        let content = resp.text().await?;
243        match content_type {
244            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
245            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListFilesOut`"))),
246            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListFilesOut`")))),
247        }
248    } else {
249        let content = resp.text().await?;
250        let entity: Option<FilesApiRoutesListFilesError> = serde_json::from_str(&content).ok();
251        Err(Error::ResponseError(ResponseContent { status, content, entity }))
252    }
253}
254
255/// Returns information about a specific file.
256pub async fn files_api_routes_retrieve_file(configuration: &configuration::Configuration, file_id: &str) -> Result<models::RetrieveFileOut, Error<FilesApiRoutesRetrieveFileError>> {
257    // add a prefix to parameters to efficiently prevent name collisions
258    let p_path_file_id = file_id;
259
260    let uri_str = format!("{}/v1/files/{file_id}", configuration.base_path, file_id=crate::apis::urlencode(p_path_file_id));
261    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
262
263    if let Some(ref user_agent) = configuration.user_agent {
264        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
265    }
266    if let Some(ref token) = configuration.bearer_access_token {
267        req_builder = req_builder.bearer_auth(token.to_owned());
268    };
269
270    let req = req_builder.build()?;
271    let resp = configuration.client.execute(req).await?;
272
273    let status = resp.status();
274    let content_type = resp
275        .headers()
276        .get("content-type")
277        .and_then(|v| v.to_str().ok())
278        .unwrap_or("application/octet-stream");
279    let content_type = super::ContentType::from(content_type);
280
281    if !status.is_client_error() && !status.is_server_error() {
282        let content = resp.text().await?;
283        match content_type {
284            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
285            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::RetrieveFileOut`"))),
286            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::RetrieveFileOut`")))),
287        }
288    } else {
289        let content = resp.text().await?;
290        let entity: Option<FilesApiRoutesRetrieveFileError> = serde_json::from_str(&content).ok();
291        Err(Error::ResponseError(ResponseContent { status, content, entity }))
292    }
293}
294
295/// Upload a file that can be used across various endpoints.  The size of individual files can be a maximum of 512 MB. The Fine-tuning API only supports .jsonl files.  Please contact us if you need to increase these storage limits.
296pub async fn files_api_routes_upload_file(configuration: &configuration::Configuration, file: std::path::PathBuf, expiry: Option<i32>, visibility: Option<&str>, purpose: Option<models::FilePurpose>) -> Result<models::UploadFileOut, Error<FilesApiRoutesUploadFileError>> {
297    // add a prefix to parameters to efficiently prevent name collisions
298    let p_form_file = file;
299    let p_form_expiry = expiry;
300    let p_form_visibility = visibility;
301    let p_form_purpose = purpose;
302
303    let uri_str = format!("{}/v1/files", configuration.base_path);
304    let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str);
305
306    if let Some(ref user_agent) = configuration.user_agent {
307        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
308    }
309    if let Some(ref token) = configuration.bearer_access_token {
310        req_builder = req_builder.bearer_auth(token.to_owned());
311    };
312    let mut multipart_form = reqwest::multipart::Form::new();
313    if let Some(param_value) = p_form_expiry {
314        multipart_form = multipart_form.text("expiry", param_value.to_string());
315    }
316    if let Some(param_value) = p_form_visibility {
317        multipart_form = multipart_form.text("visibility", param_value.to_string());
318    }
319    if let Some(param_value) = p_form_purpose {
320        multipart_form = multipart_form.text("purpose", serde_json::to_string(&param_value)?);
321    }
322    let file = TokioFile::open(&p_form_file).await?;
323    let stream = FramedRead::new(file, BytesCodec::new());
324    let file_name = p_form_file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
325    let file_part = reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(stream)).file_name(file_name);
326    multipart_form = multipart_form.part("file", file_part);
327    req_builder = req_builder.multipart(multipart_form);
328
329    let req = req_builder.build()?;
330    let resp = configuration.client.execute(req).await?;
331
332    let status = resp.status();
333    let content_type = resp
334        .headers()
335        .get("content-type")
336        .and_then(|v| v.to_str().ok())
337        .unwrap_or("application/octet-stream");
338    let content_type = super::ContentType::from(content_type);
339
340    if !status.is_client_error() && !status.is_server_error() {
341        let content = resp.text().await?;
342        match content_type {
343            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
344            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::UploadFileOut`"))),
345            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::UploadFileOut`")))),
346        }
347    } else {
348        let content = resp.text().await?;
349        let entity: Option<FilesApiRoutesUploadFileError> = serde_json::from_str(&content).ok();
350        Err(Error::ResponseError(ResponseContent { status, content, entity }))
351    }
352}
353