Skip to main content

AuthProvider

Enum AuthProvider 

Source
pub enum AuthProvider {
    OpenAI(OpenAIAuth),
    Azure(AzureAuth),
}
Expand description

Authentication provider for OpenAI APIs

This enum encapsulates the authentication strategy for different API providers. It handles both endpoint URL construction and HTTP header application.

§Example

use openai_tools::common::auth::AuthProvider;

// Auto-detect from environment
let auth = AuthProvider::from_env()?;

// Get endpoint for chat completions
let endpoint = auth.endpoint("chat/completions");

// Apply auth headers to a request
let mut headers = request::header::HeaderMap::new();
auth.apply_headers(&mut headers)?;

Variants§

§

OpenAI(OpenAIAuth)

OpenAI API authentication

§

Azure(AzureAuth)

Azure OpenAI API authentication

Implementations§

Source§

impl AuthProvider

Source

pub fn openai_from_env() -> Result<Self>

Creates an OpenAI authentication provider from environment variables

Reads the API key from OPENAI_API_KEY environment variable.

§Returns

Result<AuthProvider> - OpenAI auth provider or error if env var not set

§Environment Variables
VariableRequiredDescription
OPENAI_API_KEYYesOpenAI API key
§Example
use openai_tools::common::auth::AuthProvider;

let auth = AuthProvider::openai_from_env()?;
Source

pub fn azure_from_env() -> Result<Self>

Creates an Azure OpenAI authentication provider from environment variables

§Returns

Result<AuthProvider> - Azure auth provider or error if required vars not set

§Environment Variables
VariableRequiredDescription
AZURE_OPENAI_API_KEYYesAzure API key
AZURE_OPENAI_BASE_URLYesComplete endpoint URL including deployment, API path, and api-version
§Example
use openai_tools::common::auth::AuthProvider;

// With environment variables:
// AZURE_OPENAI_API_KEY=xxx
// AZURE_OPENAI_BASE_URL=https://my-resource.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview
let auth = AuthProvider::azure_from_env()?;
Source

pub fn from_env() -> Result<Self>

Creates an authentication provider by auto-detecting from environment

Tries Azure first (if AZURE_OPENAI_API_KEY is set), then falls back to OpenAI.

§Returns

Result<AuthProvider> - Detected auth provider or error

§Detection Order
  1. If AZURE_OPENAI_API_KEY is set → Azure
  2. If OPENAI_API_KEY is set → OpenAI
  3. Otherwise → Error
§Example
use openai_tools::common::auth::AuthProvider;

let auth = AuthProvider::from_env()?;
match &auth {
    AuthProvider::OpenAI(_) => println!("Using OpenAI"),
    AuthProvider::Azure(_) => println!("Using Azure"),
}
Source

pub fn endpoint(&self, path: &str) -> String

Constructs the full endpoint URL for a given API path

§Arguments
  • path - API path (e.g., “chat/completions”, “embeddings”)
§Returns

Full endpoint URL appropriate for the provider

§Example
use openai_tools::common::auth::AuthProvider;

let auth = AuthProvider::openai_from_env()?;
let url = auth.endpoint("chat/completions");
// OpenAI: https://api.openai.com/v1/chat/completions
// Azure: https://{resource}.openai.azure.com/openai/deployments/{deployment}/chat/completions?api-version={ver}
Source

pub fn apply_headers(&self, headers: &mut HeaderMap) -> Result<()>

Applies authentication headers to a request

§Arguments
  • headers - Mutable reference to header map
§Returns

Result<()> - Success or error if header value is invalid

§Header Differences
ProviderHeader NameValue Format
OpenAIAuthorizationBearer {key}
Azureapi-key{key}
Source

pub fn api_key(&self) -> &str

Returns the API key (for backward compatibility)

§Returns

The API key or token string

Source

pub fn is_azure(&self) -> bool

Returns whether this is an Azure provider

§Returns

true if Azure, false if OpenAI

Source

pub fn is_openai(&self) -> bool

Returns whether this is an OpenAI provider

§Returns

true if OpenAI, false if Azure

Source

pub fn from_url_with_key<S: Into<String>>(base_url: S, api_key: S) -> Self

Creates an authentication provider by detecting the provider from URL pattern.

This method analyzes the URL to determine whether it’s an Azure OpenAI endpoint or a standard OpenAI (or compatible) endpoint.

§Arguments
  • base_url - The complete base URL for API requests
  • api_key - The API key or token
§URL Detection
URL PatternDetected Provider
*.openai.azure.com*Azure
All othersOpenAI (or compatible)
§Returns

AuthProvider - Detected provider

§Example
use openai_tools::common::auth::AuthProvider;

// OpenAI compatible API
let openai = AuthProvider::from_url_with_key(
    "https://api.openai.com/v1",
    "sk-key",
);
assert!(openai.is_openai());

// Azure OpenAI (complete base URL)
let azure = AuthProvider::from_url_with_key(
    "https://my-resource.openai.azure.com/openai/deployments/gpt-4o?api-version=2024-08-01-preview",
    "azure-key",
);
assert!(azure.is_azure());

// Local API (Ollama, LocalAI, etc.)
let local = AuthProvider::from_url_with_key(
    "http://localhost:11434/v1",
    "dummy-key",
);
assert!(local.is_openai());  // Treated as OpenAI-compatible
Source

pub fn from_url<S: Into<String>>(base_url: S) -> Result<Self>

Creates an authentication provider from URL, using environment variables for credentials.

This is a convenience method that combines URL-based detection with environment variable-based credential loading.

§Arguments
  • base_url - The complete base URL for API requests
§Environment Variables

For Azure URLs (*.openai.azure.com):

  • AZURE_OPENAI_API_KEY (required)

For other URLs:

  • OPENAI_API_KEY (required)
§Example
use openai_tools::common::auth::AuthProvider;

// Uses OPENAI_API_KEY from environment
let auth = AuthProvider::from_url("https://api.openai.com/v1")?;

// Uses AZURE_OPENAI_API_KEY from environment
let azure = AuthProvider::from_url(
    "https://my-resource.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview"
)?;

Trait Implementations§

Source§

impl Clone for AuthProvider

Source§

fn clone(&self) -> AuthProvider

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AuthProvider

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more