openai-interface 0.14.0

A low-level Rust interface for the OpenAI API
Documentation
//! Create a batch job via `POST /batches`.
//!
//! > ![warn] This module is untested!
//! > If you encounter any issues, please report them on the repository.

use serde::{Deserialize, Serialize};
use url::Url;

use crate::{
    batches::Batch,
    errors::OapiError,
    rest::post::{Post, PostNoStream},
};

crate::request_body! {
    /// Creates and executes a batch from an uploaded JSONL file of requests.
    #[derive(Debug, Default, Clone, Serialize, Deserialize)]
    pub struct CreateBatchRequest {
        /// The ID of the uploaded JSONL input file.
        pub input_file_id: String,
        /// The API endpoint the batch runs against, e.g.
        /// `/v1/chat/completions`.
        pub endpoint: String,
        /// The time window within which the batch should be processed. Only
        /// `24h` is currently supported.
        pub completion_window: CompletionWindow,
        /// Up to 16 arbitrary key-value metadata pairs attached to the
        /// batch.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub metadata: Option<std::collections::HashMap<String, String>>,
    }
}

/// The time window within which a batch must complete.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum CompletionWindow {
    /// The only currently supported window: 24 hours.
    #[default]
    #[serde(rename = "24h")]
    Hours24,
}

impl CompletionWindow {
    /// The wire value of the completion window.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            CompletionWindow::Hours24 => "24h",
        }
    }
}

impl Post for CreateBatchRequest {
    fn is_streaming(&self) -> bool {
        false
    }

    /// Builds the URL for the request.
    ///
    /// `base_url` should be like <https://api.openai.com/v1>
    fn build_url(&self, base_url: &str) -> Result<String, OapiError> {
        let mut url = Url::parse(base_url.trim_end_matches('/')).map_err(OapiError::UrlError)?;
        url.path_segments_mut()
            .map_err(|_| OapiError::UrlCannotBeBase(base_url.to_string()))?
            .push("batches");
        Ok(url.to_string())
    }
}

impl PostNoStream for CreateBatchRequest {
    type Response = Batch;
}