AiClient

Struct AiClient 

Source
pub struct AiClient { /* private fields */ }
Expand description

统一的AI客户端,提供跨厂商的AI服务访问接口

Unified AI client

Usage example:

use ai_lib::{AiClient, Provider, ChatCompletionRequest, Message, Role};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Switch model provider by changing Provider value
    let client = AiClient::new(Provider::Groq)?;
     
    let request = ChatCompletionRequest::new(
        "test-model".to_string(),
        vec![Message {
            role: Role::User,
            content: ai_lib::types::common::Content::Text("Hello".to_string()),
            function_call: None,
        }],
    );
     
    // Note: Set GROQ_API_KEY environment variable for actual API calls
    // Optional: Set AI_PROXY_URL environment variable to use proxy server
    // let response = client.chat_completion(request).await?;
     
    println!(
        "Client created successfully with provider: {}",
        client.provider_name()
    );
    println!("Request prepared for model: {}", request.model);
     
    Ok(())
}

§Proxy Configuration

Configure proxy server by setting the AI_PROXY_URL environment variable:

export AI_PROXY_URL=http://proxy.example.com:8080

Supported proxy formats:

  • HTTP proxy: http://proxy.example.com:8080
  • HTTPS proxy: https://proxy.example.com:8080
  • With authentication: http://user:pass@proxy.example.com:8080

Implementations§

Source§

impl AiClient

Source

pub fn default_chat_model(&self) -> String

Get the effective default chat model for this client (honors custom override)

Source

pub fn new(provider: Provider) -> Result<Self, AiLibError>

Create a new AI client

Source

pub fn builder(provider: Provider) -> AiClientBuilder

Create a new AI client builder

Source

pub fn new_with_metrics( provider: Provider, metrics: Arc<dyn Metrics>, ) -> Result<Self, AiLibError>

Create AiClient with injected metrics implementation

Source

pub fn with_options( provider: Provider, opts: ConnectionOptions, ) -> Result<Self, AiLibError>

Create client with minimal explicit options (base_url/proxy/timeout).

Fields left as None in ConnectionOptions will fall back to environment variables (e.g., OPENAI_API_KEY, AI_PROXY_URL, AI_TIMEOUT_SECS). Set disable_proxy: true to prevent automatic proxy detection from AI_PROXY_URL.

Source

pub fn connection_options(&self) -> Option<&ConnectionOptions>

Source

pub fn with_metrics(self, metrics: Arc<dyn Metrics>) -> Self

Set metrics implementation on client

Source

pub fn model_resolver(&self) -> Arc<ModelResolver>

Access the model resolver (advanced customization).

Source

pub async fn chat_completion( &self, request: ChatCompletionRequest, ) -> Result<ChatCompletionResponse, AiLibError>

Send chat completion request

Source

pub async fn chat_completion_stream( &self, request: ChatCompletionRequest, ) -> Result<Box<dyn Stream<Item = Result<ChatCompletionChunk, AiLibError>> + Send + Unpin>, AiLibError>

Streaming chat completion request

Source

pub async fn chat_completion_stream_with_cancel( &self, request: ChatCompletionRequest, ) -> Result<(Box<dyn Stream<Item = Result<ChatCompletionChunk, AiLibError>> + Send + Unpin>, CancelHandle), AiLibError>

Streaming chat completion request with cancel control

Source

pub async fn chat_completion_batch( &self, requests: Vec<ChatCompletionRequest>, concurrency_limit: Option<usize>, ) -> Result<Vec<Result<ChatCompletionResponse, AiLibError>>, AiLibError>

Batch chat completion requests

Source

pub async fn chat_completion_batch_smart( &self, requests: Vec<ChatCompletionRequest>, ) -> Result<Vec<Result<ChatCompletionResponse, AiLibError>>, AiLibError>

Smart batch processing

Source

pub async fn list_models(&self) -> Result<Vec<String>, AiLibError>

Get list of supported models

Source

pub fn switch_provider(&mut self, provider: Provider) -> Result<(), AiLibError>

Switch AI model provider

Source

pub fn provider_name(&self) -> &str

Get the active provider name reported by the underlying strategy.

Source

pub fn provider(&self) -> Provider

Get the current provider enum value

Source

pub fn build_simple_request<S: Into<String>>( &self, prompt: S, ) -> ChatCompletionRequest

Convenience helper: construct a request with the provider’s default chat model.

Source

pub fn build_simple_request_with_model<S: Into<String>>( &self, prompt: S, model: S, ) -> ChatCompletionRequest

Convenience helper: construct a request with an explicitly specified chat model.

Source

pub fn build_multimodal_request<S: Into<String>>( &self, prompt: S, ) -> Result<ChatCompletionRequest, AiLibError>

Convenience helper: construct a request with the provider’s default multimodal model.

Source

pub fn build_multimodal_request_with_model<S: Into<String>>( &self, prompt: S, model: S, ) -> ChatCompletionRequest

Convenience helper: construct a request with an explicitly specified multimodal model.

Source

pub async fn quick_chat_text<P: Into<String>>( provider: Provider, prompt: P, ) -> Result<String, AiLibError>

One-shot helper: create a client for provider, send a single user prompt

Source

pub async fn quick_chat_text_with_model<P: Into<String>, M: Into<String>>( provider: Provider, prompt: P, model: M, ) -> Result<String, AiLibError>

One-shot helper with model

Source

pub async fn quick_multimodal_text<P: Into<String>>( provider: Provider, prompt: P, ) -> Result<String, AiLibError>

One-shot helper multimodal

Source

pub async fn quick_multimodal_text_with_model<P: Into<String>, M: Into<String>>( provider: Provider, prompt: P, model: M, ) -> Result<String, AiLibError>

One-shot helper multimodal with model

Source

pub async fn quick_chat_text_with_options<P: Into<String>>( provider: Provider, prompt: P, options: ModelOptions, ) -> Result<String, AiLibError>

One-shot helper with model options

Source

pub async fn upload_file(&self, path: &str) -> Result<String, AiLibError>

Upload a local file

Auto Trait Implementations§

Blanket Implementations§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

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

§

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

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

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
§

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

§

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> 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
§

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

§

type Error = Infallible

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

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

Performs the conversion.
§

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

§

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

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

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
Source§

impl<T> ErasedDestructor for T
where T: 'static,