openai-interface 0.14.0

A low-level Rust interface for the OpenAI API
Documentation
//! Per-request authentication and header options.
//!
//! Every request method takes a [`RequestOptions`] value, which decides how
//! the request authenticates and which extra headers are attached. The
//! default is no authentication; [`RequestOptions::bearer`] reproduces the
//! classic `Authorization: Bearer <token>` behavior of OpenAI and most
//! compatible providers.
//!
//! # Examples
//!
//! Plain OpenAI-style bearer auth:
//!
//! ```
//! use openai_interface::rest::RequestOptions;
//!
//! let options = RequestOptions::bearer("sk-...");
//! # assert!(matches!(options.auth, openai_interface::rest::Auth::Bearer(_)));
//! ```
//!
//! Azure OpenAI authenticates with an `api-key` header instead:
//!
//! ```
//! use openai_interface::rest::RequestOptions;
//!
//! let options = RequestOptions::new()
//!     .with_header("api-key", "...")
//!     .unwrap();
//! ```
//!
//! Anthropic uses `x-api-key` plus a version header:
//!
//! ```
//! use openai_interface::rest::RequestOptions;
//!
//! let options = RequestOptions::new()
//!     .with_header("x-api-key", "...")
//!     .unwrap()
//!     .with_header("anthropic-version", "2023-06-01")
//!     .unwrap();
//! ```
//!
//! Extra headers may also be layered on top of bearer auth, e.g. the
//! `OpenAI-Organization` header:
//!
//! ```
//! use openai_interface::rest::RequestOptions;
//!
//! let options = RequestOptions::bearer("sk-...")
//!     .with_header("OpenAI-Organization", "org-...")
//!     .unwrap();
//! ```

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};

use crate::errors::OapiError;

/// How a request authenticates itself.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Auth {
    /// Send no authentication header at all. Useful when the credentials
    /// travel in an extra header set via
    /// [`RequestOptions::with_header`] (Azure `api-key`, Anthropic
    /// `x-api-key`, ...), or for unauthenticated endpoints.
    #[default]
    None,
    /// The classic `Authorization: Bearer <token>` header used by OpenAI and
    /// most compatible providers.
    Bearer(String),
}

/// Per-request authentication and header options.
///
/// Passed to every request method instead of a bare API key. Authentication
/// headers ([`Auth`]) are applied first; [`RequestOptions::extra_headers`]
/// are applied afterwards, so they can supply additional credentials of
/// their own.
#[derive(Debug, Clone, Default)]
pub struct RequestOptions {
    /// How the request authenticates itself. Defaults to [`Auth::None`].
    pub auth: Auth,
    /// Additional headers attached verbatim to the request, e.g.
    /// `OpenAI-Organization`, Azure `api-key` or Anthropic
    /// `anthropic-version`.
    pub extra_headers: HeaderMap,
}

impl RequestOptions {
    /// Creates options without authentication and without extra headers.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates options authenticating with `Authorization: Bearer <token>`,
    /// the scheme used by OpenAI and most compatible providers.
    #[must_use]
    pub fn bearer(token: impl Into<String>) -> Self {
        Self {
            auth: Auth::Bearer(token.into()),
            extra_headers: HeaderMap::new(),
        }
    }

    /// Adds an extra header, e.g. `api-key` for Azure or `x-api-key` plus
    /// `anthropic-version` for Anthropic.
    ///
    /// Header names and values are validated eagerly; use
    /// [`RequestOptions::extra_headers`] directly if you already hold typed
    /// [`HeaderName`]/[`HeaderValue`]s.
    ///
    /// # Errors
    ///
    /// Returns [`OapiError::InvalidHeader`] if the name or value is not a
    /// valid HTTP header.
    pub fn with_header(mut self, name: &str, value: &str) -> Result<Self, OapiError> {
        let name = HeaderName::from_bytes(name.as_bytes())
            .map_err(|e| OapiError::InvalidHeader(format!("{name}: {e}")))?;
        let value = HeaderValue::from_str(value)
            .map_err(|e| OapiError::InvalidHeader(format!("{name}: {e}")))?;
        self.extra_headers.insert(name, value);
        Ok(self)
    }
}