Client

Struct Client 

Source
pub struct Client<E>{
    pub http_client: Client,
    pub environment: E,
    pub diagnostics: Option<Arc<DiagnosticsCollector>>,
    pub cache: Option<Arc<ApiRequestCache>>,
    pub retry_config: Option<EnhancedRetryConfig>,
    pub circuit_breaker_config: Option<EnhancedCircuitBreakerConfig>,
    pub circuit_breaker: Option<EnhancedCircuitBreaker>,
    pub rate_limiting_config: Option<EnhancedRateLimitingConfig>,
    pub rate_limiter: Option<EnhancedRateLimiter>,
}
Expand description

The main client for interacting with the OpenAI API.

Provides methods for accessing different API categories like assistants, chat, embeddings, etc.

§Governing Principle : “Thin Client, Rich API”

This client follows the “Thin Client, Rich API” principle - it exposes all server-side functionality transparently while maintaining zero client-side intelligence or automatic behaviors. All operations are explicit and developer-controlled, with clear separation between information retrieval and state-changing actions.

§Example

use api_openai::{ Client, environment::{ OpenaiEnvironmentImpl, OpenAIRecommended }, Secret, ClientApiAccessors };

let secret = Secret::load_from_env("OPENAI_API_KEY")?;
let env = OpenaiEnvironmentImpl::build(secret, None, None, OpenAIRecommended::base_url().to_string(), OpenAIRecommended::realtime_base_url().to_string())?;
let client = Client::build(env)?;

// Use the client to access different APIs
let models = client.models().list().await?;

Fields§

§http_client: Client

The HTTP client used for making requests.

§environment: E

The OpenAI environment configuration.

§diagnostics: Option<Arc<DiagnosticsCollector>>

Optional diagnostics collector for monitoring requests.

§cache: Option<Arc<ApiRequestCache>>

Optional request cache for API responses.

§retry_config: Option<EnhancedRetryConfig>

Optional retry configuration for reliability.

§circuit_breaker_config: Option<EnhancedCircuitBreakerConfig>

Optional circuit breaker configuration for fault tolerance.

§circuit_breaker: Option<EnhancedCircuitBreaker>

Optional circuit breaker instance.

§rate_limiting_config: Option<EnhancedRateLimitingConfig>

Optional rate limiting configuration.

§rate_limiter: Option<EnhancedRateLimiter>

Optional rate limiter instance.

Implementations§

Source§

impl<E> Client<E>

Source

pub fn build(environment: E) -> Result<Self>

Creates a new Client instance.

§Arguments
  • environment: The OpenAI environment configuration.
§Errors

Returns OpenAIError::InvalidArgument if the API key is invalid.

Source

pub fn with_cache(self) -> Self

Enable request caching with default configuration.

Source

pub fn with_cache_config(self, config: CacheConfig) -> Self

Enable request caching with custom configuration.

Source

pub fn cache_statistics(&self) -> Option<&CacheStatistics>

Get cache statistics if caching is enabled.

Source

pub async fn clear_cache(&self)

Clear the cache if caching is enabled.

Source

pub fn with_retry(self) -> Self

Enable enhanced retry logic with default configuration. Only available when the retry feature is enabled.

Source

pub fn with_retry_config(self, config: EnhancedRetryConfig) -> Self

Enable enhanced retry logic with custom configuration. Only available when the retry feature is enabled.

Source

pub fn retry_config(&self) -> Option<&EnhancedRetryConfig>

Get retry configuration if enabled.

Source

pub fn with_circuit_breaker(self) -> Self

Enable circuit breaker logic with default configuration. Only available when the circuit_breaker feature is enabled.

Source

pub fn with_circuit_breaker_config( self, config: EnhancedCircuitBreakerConfig, ) -> Self

Enable circuit breaker logic with custom configuration. Only available when the circuit_breaker feature is enabled.

Source

pub fn circuit_breaker_config(&self) -> Option<&EnhancedCircuitBreakerConfig>

Get circuit breaker configuration if enabled.

Source

pub fn with_rate_limiting(self) -> Self

Enable rate limiting logic with default configuration. Only available when the rate_limiting feature is enabled.

Source

pub fn with_rate_limiting_config( self, config: EnhancedRateLimitingConfig, ) -> Self

Enable rate limiting logic with custom configuration. Only available when the rate_limiting feature is enabled.

Source

pub fn rate_limiting_config(&self) -> Option<&EnhancedRateLimitingConfig>

Get rate limiting configuration if enabled.

Source§

impl<E> Client<E>

Source

pub fn get_diagnostics(&self) -> Option<Arc<DiagnosticsCollector>>

Returns the diagnostics collector for monitoring requests.

§Returns
  • Some(DiagnosticsCollector) if diagnostics are enabled
  • None if diagnostics are disabled
Source

pub fn list_registered_tools(&self) -> Vec<&str>

Lists all registered custom tools.

§Returns

An empty vector as custom tool registration is not yet implemented.

Source§

impl<E> Client<E>

Source

pub fn admin(&self) -> Admin<'_, E>

Access the administrative API

Source

pub async fn list_organizations(&self) -> Result<Vec<Organization>>

List organizations (convenience method)

§Errors

Returns an error if the API request fails or if the response cannot be parsed.

Source

pub async fn get_organization(&self, org_id: &str) -> Result<Organization>

Get organization details (convenience method)

§Errors

Returns an error if the API request fails, the organization is not found, or if the response cannot be parsed.

Source

pub async fn list_users(&self, org_id: &str) -> Result<Vec<User>>

List users in organization (convenience method)

§Errors

Returns an error if the API request fails, the organization is not found, insufficient permissions, or if the response cannot be parsed.

Source

pub async fn list_projects(&self, org_id: Option<&str>) -> Result<Vec<Project>>

List projects (convenience method)

§Errors

Returns an error if the API request fails, the organization is not found (when specified), insufficient permissions, or if the response cannot be parsed.

Source

pub async fn create_project(&self, name: String) -> Result<Project>

Create project (convenience method)

§Errors

Returns an error if the API request fails, invalid project name, insufficient permissions, or if the response cannot be parsed.

Source§

impl<E> Client<E>

Source

pub fn uploads(&self) -> Uploads<'_, E>

Access the uploads API

Source

pub async fn upload_file<P: AsRef<Path>>( &self, file_path: P, purpose: &str, ) -> Result<FileObject>

Upload a file with default configuration

§Errors

Returns OpenAIError if the file upload fails.

Source

pub async fn list_files(&self, purpose: Option<&str>) -> Result<Vec<FileObject>>

List uploaded files

§Errors

Returns OpenAIError if the request fails.

Source

pub async fn get_file(&self, file_id: &str) -> Result<FileObject>

Get file information

§Errors

Returns OpenAIError if the request fails.

Source

pub async fn delete_file(&self, file_id: &str) -> Result<DeleteFileResponse>

Delete a file

§Errors

Returns OpenAIError if the request fails.

Source

pub async fn download_file(&self, file_id: &str) -> Result<Vec<u8>>

Download file content

§Errors

Returns OpenAIError if the request fails.

Source§

impl<E> Client<E>

Source

pub fn enterprise(&self) -> EnterpriseClient<'_, E>

Access enterprise features

Source§

impl<E> Client<E>

Extension trait for Client to add comparator method

Source

pub fn comparator(&self) -> ModelComparator<'_, E>

Create a model comparator for A/B testing

Trait Implementations§

Source§

impl<E> ClientApiAccessors<E> for Client<E>

Source§

fn assistants(&self) -> Assistants<'_, E>

Returns an Assistants API client.
Source§

fn audio(&self) -> Audio<'_, E>

Returns an Audio API client.
Source§

fn chat(&self) -> Chat<'_, E>

Returns a Chat API client.
Source§

fn embeddings(&self) -> Embeddings<'_, E>

Returns an Embeddings API client.
Source§

fn files(&self) -> Files<'_, E>

Returns a Files API client.
Source§

fn fine_tuning(&self) -> FineTuning<'_, E>

Returns a FineTuning API client.
Source§

fn images(&self) -> Images<'_, E>

Returns an Images API client.
Source§

fn models(&self) -> Models<'_, E>

Returns a Models API client.
Source§

fn moderations(&self) -> Moderations<'_, E>

Returns a Moderations API client.
Source§

fn realtime(&self) -> Realtime<'_, E>

Returns a Realtime API client.
Source§

fn responses(&self) -> Responses<'_, E>

Returns a Responses API client.
Source§

fn vector_stores(&self) -> VectorStores<'_, E>

Returns a VectorStores API client.
Source§

impl<E> Clone for Client<E>

Source§

fn clone(&self) -> Client<E>

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<E> Debug for Client<E>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<E> PlatformSpecificClient<E> for Client<E>

Creates a chat completion with search grounding integration. Read more
Source§

fn search_and_ground<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, _query: &'life1 str, _context: Option<&'life2 str>, _config: SearchGroundingConfig, ) -> Pin<Box<dyn Future<Output = Result<GroundedResponse>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait,

Performs search grounding for a query with optional context. Read more
Source§

fn execute_code<'life0, 'life1, 'async_trait>( &'life0 self, _code: &'life1 str, _config: CodeExecutionConfig, ) -> Pin<Box<dyn Future<Output = Result<CodeExecutionResult>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Executes code in a secure environment. Read more
Source§

fn create_chat_completion_with_code_execution<'life0, 'async_trait>( &'life0 self, _request: ChatCompletionRequest, _execution_config: CodeExecutionConfig, ) -> Pin<Box<dyn Future<Output = Result<CreateChatCompletionResponse>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Creates a chat completion with code execution capabilities. Read more
Source§

fn browse_url<'life0, 'life1, 'async_trait>( &'life0 self, _url: &'life1 str, _config: WebBrowsingConfig, ) -> Pin<Box<dyn Future<Output = Result<BrowsingResult>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Browses a URL and extracts content. Read more
Source§

fn create_chat_completion_with_browsing<'life0, 'async_trait>( &'life0 self, _request: ChatCompletionRequest, _browsing_config: WebBrowsingConfig, ) -> Pin<Box<dyn Future<Output = Result<CreateChatCompletionResponse>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Creates a chat completion with web browsing capabilities. Read more
Source§

fn generate_image<'life0, 'life1, 'async_trait>( &'life0 self, _prompt: &'life1 str, _config: ImageGenerationConfig, ) -> Pin<Box<dyn Future<Output = Result<ImageResult>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Generates an image from a prompt. Read more

Auto Trait Implementations§

§

impl<E> Freeze for Client<E>
where E: Freeze,

§

impl<E> !RefUnwindSafe for Client<E>

§

impl<E> Send for Client<E>

§

impl<E> Sync for Client<E>

§

impl<E> Unpin for Client<E>
where E: Unpin,

§

impl<E> !UnwindSafe for Client<E>

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> CloneDyn for T
where T: Clone,

Source§

fn __clone_dyn(&self, _: DontCallMe) -> *mut ()

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<C, E> EntryToVal<C> for E
where C: Collection<Entry = E>,

Source§

type Val = <C as Collection>::Val

The type of values stored in the collection. This might be distinct from Entry in complex collections. For example, in a HashMap, while Entry might be a ( key, value ) tuple, Val might only be the value part.
Source§

fn entry_to_val(self) -> <E as EntryToVal<C>>::Val

Converts an entry into a value representation specific to the type of collection. This conversion is crucial for handling operations on entries, especially when they need to be treated or accessed as individual values, such as retrieving the value part from a key-value pair in a hash map.
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> IntoResult<T> for T

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<C, Val> ValToEntry<C> for Val
where C: CollectionValToEntry<Val>,

Source§

fn val_to_entry(self) -> <C as CollectionValToEntry<Val>>::Entry

Invokes the val_to_entry function of the CollectionValToEntry trait to convert the value to an entry.

Source§

type Entry = <C as CollectionValToEntry<Val>>::Entry

Represents the type of entry that corresponds to the value within the collection. Type Entry is defined by the Collection trait.
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