openai-interface 0.13.0

A low-level Rust interface for the OpenAI API
Documentation
//! Per-request authentication and header options.
//!
//! All request methods take a [`RequestOptions`] value: it decides how the
//! request authenticates and which extra headers are attached. This example
//! shows the three common non-default setups — Azure OpenAI, Anthropic, and
//! OpenAI with an organization header.
//!
//! ```sh
//! # Azure OpenAI
//! AZURE_BASE_URL="https://YOUR-RESOURCE.openai.azure.com/openai/v1" \
//! AZURE_API_KEY=... cargo run --example custom_auth_headers azure
//!
//! # Anthropic
//! ANTHROPIC_API_KEY=... cargo run --example custom_auth_headers anthropic
//! ```
//!
//! TLS: run with the `ferritls` feature or install your own rustls crypto
//! provider — see the crate docs ("TLS Crypto Provider").

use openai_interface::chat::create::request::{Message, RequestBody};
use openai_interface::rest::post::PostNoStream;
use openai_interface::rest::{RequestOptions, default_client};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Needs the `ferritls` cargo feature; drop this line if you install
    // your own rustls crypto provider.
    #[cfg(feature = "ferritls")]
    openai_interface::rest::install_crypto_provider().ok();

    let which = std::env::args().nth(1).unwrap_or_default();

    // The per-request options: authentication scheme + extra headers.
    let (base_url, options) = match which.as_str() {
        // Azure OpenAI authenticates with the `api-key` header and accepts
        // the OpenAI-compatible surface under /openai/v1.
        "azure" => {
            let base_url = require_env("AZURE_BASE_URL")?;
            let key = require_env("AZURE_API_KEY")?;
            let options = RequestOptions::new().with_header("api-key", &key)?;
            (base_url, options)
        }
        // Anthropic authenticates with `x-api-key` plus a version header.
        "anthropic" => {
            let key = require_env("ANTHROPIC_API_KEY")?;
            let options = RequestOptions::new()
                .with_header("x-api-key", &key)?
                .with_header("anthropic-version", "2023-06-01")?;
            ("https://api.anthropic.com/v1".to_string(), options)
        }
        // Plain OpenAI: bearer auth, optionally with an organization.
        _ => {
            let key = require_env("OPENAI_API_KEY")?;
            let options = RequestOptions::bearer(key);
            ("https://api.openai.com/v1".to_string(), options)
        }
    };

    let request = RequestBody {
        messages: vec![Message::user("Say hello in one short sentence.")],
        model: std::env::var("MODEL").unwrap_or_else(|_| "gpt-4.1-mini".to_string()),
        stream: Some(false),
        ..Default::default()
    };

    let completion: openai_interface::chat::ChatCompletion = request
        .get_response(&default_client(), &base_url, &options)
        .await?;

    println!(
        "{}",
        completion.choices[0]
            .message
            .content
            .as_deref()
            .unwrap_or("(no content)")
    );
    Ok(())
}

fn require_env(name: &str) -> Result<String, Box<dyn std::error::Error>> {
    std::env::var(name).map_err(|_| format!("{name} is not set").into())
}