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::Serialize;
7use url::Url;
8
9use crate::{
10    batches::Batch,
11    errors::OapiError,
12    rest::post::{Post, PostNoStream},
13};
14
15/// Creates and executes a batch from an uploaded JSONL file of requests.
16#[derive(Debug, Default, Clone, Serialize)]
17pub struct CreateBatchRequest {
18    /// The ID of the uploaded JSONL input file.
19    pub input_file_id: String,
20    /// The API endpoint the batch runs against, e.g.
21    /// `/v1/chat/completions`.
22    pub endpoint: String,
23    /// The time window within which the batch should be processed. Only
24    /// `24h` is currently supported.
25    pub completion_window: CompletionWindow,
26    /// Up to 16 arbitrary key-value metadata pairs attached to the
27    /// batch.
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub metadata: Option<std::collections::HashMap<String, String>>,
30    /// Additional JSON properties flattened into the request body, for
31    /// fields not covered by the typed struct.
32    #[serde(flatten, skip_serializing_if = "Option::is_none")]
33    pub extra_body: Option<serde_json::Map<String, serde_json::Value>>,
34}
35
36/// The time window within which a batch must complete.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum CompletionWindow {
39    /// The only currently supported window: 24 hours.
40    #[default]
41    Hours24,
42}
43
44impl CompletionWindow {
45    /// The wire value of the completion window.
46    #[must_use]
47    pub fn as_str(self) -> &'static str {
48        match self {
49            CompletionWindow::Hours24 => "24h",
50        }
51    }
52}
53
54impl Serialize for CompletionWindow {
55    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
56        serializer.serialize_str(self.as_str())
57    }
58}
59
60impl Post for CreateBatchRequest {
61    fn is_streaming(&self) -> bool {
62        false
63    }
64
65    /// Builds the URL for the request.
66    ///
67    /// `base_url` should be like <https://api.openai.com/v1>
68    fn build_url(&self, base_url: &str) -> Result<String, OapiError> {
69        let mut url = Url::parse(base_url.trim_end_matches('/')).map_err(OapiError::UrlError)?;
70        url.path_segments_mut()
71            .map_err(|_| OapiError::UrlCannotBeBase(base_url.to_string()))?
72            .push("batches");
73        Ok(url.to_string())
74    }
75}
76
77impl PostNoStream for CreateBatchRequest {
78    type Response = Batch;
79}