Skip to main content

openai_interface/batches/
create.rs

1//! Create a batch job via `POST /batches`.
2//!
3//! > ![warn] This module is untested!
4//! > If you encounter any issues, please report them on the repository.
5
6use serde::{Deserialize, Serialize};
7use url::Url;
8
9use crate::{
10    batches::Batch,
11    errors::OapiError,
12    rest::post::{Post, PostNoStream},
13};
14
15crate::request_body! {
16    /// Creates and executes a batch from an uploaded JSONL file of requests.
17    #[derive(Debug, Default, Clone, Serialize, Deserialize)]
18    pub struct CreateBatchRequest {
19        /// The ID of the uploaded JSONL input file.
20        pub input_file_id: String,
21        /// The API endpoint the batch runs against, e.g.
22        /// `/v1/chat/completions`.
23        pub endpoint: String,
24        /// The time window within which the batch should be processed. Only
25        /// `24h` is currently supported.
26        pub completion_window: CompletionWindow,
27        /// Up to 16 arbitrary key-value metadata pairs attached to the
28        /// batch.
29        #[serde(skip_serializing_if = "Option::is_none")]
30        pub metadata: Option<std::collections::HashMap<String, String>>,
31    }
32}
33
34/// The time window within which a batch must complete.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
36pub enum CompletionWindow {
37    /// The only currently supported window: 24 hours.
38    #[default]
39    #[serde(rename = "24h")]
40    Hours24,
41}
42
43impl CompletionWindow {
44    /// The wire value of the completion window.
45    #[must_use]
46    pub fn as_str(self) -> &'static str {
47        match self {
48            CompletionWindow::Hours24 => "24h",
49        }
50    }
51}
52
53impl Post for CreateBatchRequest {
54    fn is_streaming(&self) -> bool {
55        false
56    }
57
58    /// Builds the URL for the request.
59    ///
60    /// `base_url` should be like <https://api.openai.com/v1>
61    fn build_url(&self, base_url: &str) -> Result<String, OapiError> {
62        let mut url = Url::parse(base_url.trim_end_matches('/')).map_err(OapiError::UrlError)?;
63        url.path_segments_mut()
64            .map_err(|_| OapiError::UrlCannotBeBase(base_url.to_string()))?
65            .push("batches");
66        Ok(url.to_string())
67    }
68}
69
70impl PostNoStream for CreateBatchRequest {
71    type Response = Batch;
72}