openai-client-base 0.12.0

Auto-generated Rust client for the OpenAI API
/*
 * OpenAI API
 *
 * The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details.
 *
 * The version of the OpenAPI document: 2.3.0
 *
 * Generated by: https://openapi-generator.tech
 */

#![allow(clippy::needless_return, clippy::into_iter_on_ref)]

use super::{configuration, multipart_helper, ContentType, Error};
use crate::{apis::ResponseContent, models};
use reqwest;
use serde::{de::Error as _, Deserialize, Serialize};
use tokio::fs::File as TokioFile;
use tokio_util::codec::{BytesCodec, FramedRead};

/// struct for typed errors of method [`create_image`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateImageError {
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`create_image_edit`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateImageEditError {
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`create_image_variation`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateImageVariationError {
    UnknownValue(serde_json::Value),
}

#[bon::builder]
pub async fn create_image(
    configuration: &configuration::Configuration,
    create_image_request: models::CreateImageRequest,
) -> Result<models::ImagesResponse, Error<CreateImageError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_image_request = create_image_request;

    let uri_str = format!("{}/images/generations", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_create_image_request);

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ImagesResponse`"))),
            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::ImagesResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateImageError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// You can call this endpoint with either:  - `multipart/form-data`: use binary uploads via `image` (and optional `mask`). - `application/json`: use `images` (and optional `mask`) as references with either `image_url` or `file_id`.  Note that JSON requests use `images` (array) instead of the multipart `image` field.
#[bon::builder]
pub async fn create_image_edit(
    configuration: &configuration::Configuration,
    image: std::path::PathBuf,
    prompt: &str,
    mask: Option<std::path::PathBuf>,
    background: Option<&str>,
    model: Option<&str>,
    n: Option<i32>,
    size: Option<&str>,
    response_format: Option<&str>,
    output_format: Option<&str>,
    output_compression: Option<i32>,
    user: Option<&str>,
    input_fidelity: Option<models::InputFidelity>,
    stream: Option<bool>,
    partial_images: Option<i32>,
    quality: Option<&str>,
) -> Result<models::ImagesResponse, Error<CreateImageEditError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_form_image = image;
    let p_form_prompt = prompt;
    let p_form_mask = mask;
    let p_form_background = background;
    let p_form_model = model;
    let p_form_n = n;
    let p_form_size = size;
    let p_form_response_format = response_format;
    let p_form_output_format = output_format;
    let p_form_output_compression = output_compression;
    let p_form_user = user;
    let p_form_input_fidelity = input_fidelity;
    let p_form_stream = stream;
    let p_form_partial_images = partial_images;
    let p_form_quality = quality;

    let uri_str = format!("{}/images/edits", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    let mut multipart_form = reqwest::multipart::Form::new();
    // Add image file to multipart form
    multipart_form = multipart_helper::add_file_to_form(multipart_form, &p_form_image, "image")?;
    multipart_form = multipart_form.text("prompt", p_form_prompt.to_string());
    // Add mask file if provided
    if let Some(mask_path) = p_form_mask {
        multipart_form = multipart_helper::add_file_to_form(multipart_form, &mask_path, "mask")?;
    }
    if let Some(param_value) = p_form_background {
        multipart_form = multipart_form.text("background", param_value.to_string());
    }
    if let Some(param_value) = p_form_model {
        multipart_form = multipart_form.text("model", param_value.to_string());
    }
    if let Some(param_value) = p_form_n {
        multipart_form = multipart_form.text("n", param_value.to_string());
    }
    if let Some(param_value) = p_form_size {
        multipart_form = multipart_form.text("size", param_value.to_string());
    }
    if let Some(param_value) = p_form_response_format {
        multipart_form = multipart_form.text("response_format", param_value.to_string());
    }
    if let Some(param_value) = p_form_output_format {
        multipart_form = multipart_form.text("output_format", param_value.to_string());
    }
    if let Some(param_value) = p_form_output_compression {
        multipart_form = multipart_form.text("output_compression", param_value.to_string());
    }
    if let Some(param_value) = p_form_user {
        multipart_form = multipart_form.text("user", param_value.to_string());
    }
    if let Some(param_value) = p_form_input_fidelity {
        multipart_form = multipart_form.text("input_fidelity", param_value.to_string());
    }
    if let Some(param_value) = p_form_stream {
        multipart_form = multipart_form.text("stream", param_value.to_string());
    }
    if let Some(param_value) = p_form_partial_images {
        multipart_form = multipart_form.text("partial_images", param_value.to_string());
    }
    if let Some(param_value) = p_form_quality {
        multipart_form = multipart_form.text("quality", param_value.to_string());
    }
    req_builder = req_builder.multipart(multipart_form);

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ImagesResponse`"))),
            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::ImagesResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateImageEditError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

#[bon::builder]
pub async fn create_image_variation(
    configuration: &configuration::Configuration,
    image: std::path::PathBuf,
    model: Option<&str>,
    n: Option<i32>,
    response_format: Option<&str>,
    size: Option<&str>,
    user: Option<&str>,
) -> Result<models::ImagesResponse, Error<CreateImageVariationError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_form_image = image;
    let p_form_model = model;
    let p_form_n = n;
    let p_form_response_format = response_format;
    let p_form_size = size;
    let p_form_user = user;

    let uri_str = format!("{}/images/variations", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    let mut multipart_form = reqwest::multipart::Form::new();
    // Add image file to multipart form
    multipart_form = multipart_helper::add_file_to_form(multipart_form, &p_form_image, "image")?;
    if let Some(param_value) = p_form_model {
        multipart_form = multipart_form.text("model", param_value.to_string());
    }
    if let Some(param_value) = p_form_n {
        multipart_form = multipart_form.text("n", param_value.to_string());
    }
    if let Some(param_value) = p_form_response_format {
        multipart_form = multipart_form.text("response_format", param_value.to_string());
    }
    if let Some(param_value) = p_form_size {
        multipart_form = multipart_form.text("size", param_value.to_string());
    }
    if let Some(param_value) = p_form_user {
        multipart_form = multipart_form.text("user", param_value.to_string());
    }
    req_builder = req_builder.multipart(multipart_form);

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ImagesResponse`"))),
            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::ImagesResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateImageVariationError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}