openai-client-base 0.8.1

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_speech`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateSpeechError {
    UnknownValue(serde_json::Value),
}

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

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

/// Generates audio from the input text.
#[bon::builder]
pub async fn create_speech(
    configuration: &configuration::Configuration,
    create_speech_request: models::CreateSpeechRequest,
) -> Result<reqwest::Response, Error<CreateSpeechError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_speech_request = create_speech_request;

    let uri_str = format!("{}/audio/speech", 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_speech_request);

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

    let status = resp.status();

    if !status.is_client_error() && !status.is_server_error() {
        Ok(resp)
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateSpeechError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Transcribes audio into the input language.
#[bon::builder]
pub async fn create_transcription(
    configuration: &configuration::Configuration,
    file: std::path::PathBuf,
    model: &str,
    language: Option<&str>,
    prompt: Option<&str>,
    response_format: Option<models::AudioResponseFormat>,
    temperature: Option<f64>,
    include: Option<Vec<models::TranscriptionInclude>>,
    timestamp_granularities: Option<Vec<String>>,
    stream: Option<bool>,
    chunking_strategy: Option<models::TranscriptionChunkingStrategy>,
    known_speaker_names: Option<Vec<String>>,
    known_speaker_references: Option<Vec<String>>,
) -> Result<models::CreateTranscription200Response, Error<CreateTranscriptionError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_form_file = file;
    let p_form_model = model;
    let p_form_language = language;
    let p_form_prompt = prompt;
    let p_form_response_format = response_format;
    let p_form_temperature = temperature;
    let p_form_include = include;
    let p_form_timestamp_granularities = timestamp_granularities;
    let p_form_stream = stream;
    let p_form_chunking_strategy = chunking_strategy;
    let p_form_known_speaker_names = known_speaker_names;
    let p_form_known_speaker_references = known_speaker_references;

    let uri_str = format!("{}/audio/transcriptions", 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 file to multipart form
    multipart_form = multipart_helper::add_file_to_form(multipart_form, &p_form_file, "file")?;
    multipart_form = multipart_form.text("model", p_form_model.to_string());
    if let Some(param_value) = p_form_language {
        multipart_form = multipart_form.text("language", param_value.to_string());
    }
    if let Some(param_value) = p_form_prompt {
        multipart_form = multipart_form.text("prompt", 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_temperature {
        multipart_form = multipart_form.text("temperature", param_value.to_string());
    }
    if let Some(param_value) = p_form_include {
        multipart_form = multipart_form.text(
            "include",
            param_value
                .into_iter()
                .map(|p| p.to_string())
                .collect::<Vec<String>>()
                .join(",")
                .to_string(),
        );
    }
    if let Some(param_value) = p_form_timestamp_granularities {
        multipart_form = multipart_form.text(
            "timestamp_granularities",
            param_value
                .into_iter()
                .map(|p| p.to_string())
                .collect::<Vec<String>>()
                .join(",")
                .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_chunking_strategy {
        multipart_form = multipart_form.text("chunking_strategy", param_value.to_string());
    }
    if let Some(param_value) = p_form_known_speaker_names {
        multipart_form = multipart_form.text(
            "known_speaker_names",
            param_value
                .into_iter()
                .map(|p| p.to_string())
                .collect::<Vec<String>>()
                .join(",")
                .to_string(),
        );
    }
    if let Some(param_value) = p_form_known_speaker_references {
        multipart_form = multipart_form.text(
            "known_speaker_references",
            param_value
                .into_iter()
                .map(|p| p.to_string())
                .collect::<Vec<String>>()
                .join(",")
                .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::CreateTranscription200Response`"))),
            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::CreateTranscription200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateTranscriptionError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Translates audio into English.
#[bon::builder]
pub async fn create_translation(
    configuration: &configuration::Configuration,
    file: std::path::PathBuf,
    model: &str,
    prompt: Option<&str>,
    response_format: Option<&str>,
    temperature: Option<f64>,
) -> Result<models::CreateTranslation200Response, Error<CreateTranslationError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_form_file = file;
    let p_form_model = model;
    let p_form_prompt = prompt;
    let p_form_response_format = response_format;
    let p_form_temperature = temperature;

    let uri_str = format!("{}/audio/translations", 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 file to multipart form
    multipart_form = multipart_helper::add_file_to_form(multipart_form, &p_form_file, "file")?;
    multipart_form = multipart_form.text("model", p_form_model.to_string());
    if let Some(param_value) = p_form_prompt {
        multipart_form = multipart_form.text("prompt", 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_temperature {
        multipart_form = multipart_form.text("temperature", 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::CreateTranslation200Response`"))),
            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::CreateTranslation200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateTranslationError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}