OpenAI

Struct OpenAI 

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

用于与OpenAI兼容API交互的OpenAI客户端

这是主要的客户端结构体,提供对聊天补全、文本补全和模型列表功能的访问。 它使用async/await进行非阻塞操作并支持流式响应。

§特性

  • 聊天补全: 支持流式和非流式的聊天补全
  • 工具调用: 支持在聊天补全中进行函数调用
  • 推理模式: 支持推理模型如qwq-32b
  • 文本补全: 支持传统的文本补全API
  • 模型管理: 列出和检索模型信息
  • 线程安全: 可以在线程间安全使用

§示例

§基本用法

use openai4rs::OpenAI;
use dotenvy::dotenv;
#[tokio::main]
async fn main() {
    dotenv().ok();
    let client = OpenAI::from_env().unwrap();

    // 使用客户端进行各种操作
    let models = client.models().list(openai4rs::ModelsParam::new()).await.unwrap();
    println!("Available models: {:#?}", models);
}

Implementations§

Source§

impl OpenAI

Source

pub fn new(api_key: &str, base_url: &str) -> OpenAI

使用指定的API密钥和基础URL创建新的OpenAI客户端。

§参数
  • api_key - 您的OpenAI API密钥
  • base_url - API的基础URL (例如 “https://api.openai.com/v1”)
§示例
use openai4rs::OpenAI;

let client = OpenAI::new("your-api-key", "https://api.openai.com/v1");
Source

pub fn with_config(config: Config) -> OpenAI

使用自定义配置创建新的OpenAI客户端。

这允许您一次设置所有配置选项。

§参数
  • config - 自定义的Config实例
§示例
use openai4rs::{Config, OpenAI};
use openai4rs::header::HeaderValue;
use std::time::Duration;

let mut config = Config::new("your-api-key".to_string(), "https://api.openai.com/v1".to_string());
config.with_retry_count(5)
      .with_timeout(Duration::from_secs(60))
      .with_user_agent(HeaderValue::from_static("My-Custom-User-Agent"));

let client = OpenAI::with_config(config);
Source

pub fn from_env() -> Result<Self, String>

从环境变量创建新的OpenAI客户端。

查找以下环境变量:

  • OPENAI_API_KEY (必需): 您的API密钥
  • OPENAI_BASE_URL (可选): 基础URL,默认为 “https://api.openai.com/v1”
  • OPENAI_TIMEOUT (可选): 请求超时时间(秒),默认为60
  • OPENAI_CONNECT_TIMEOUT (可选): 连接超时时间(秒),默认为10
  • OPENAI_RETRY_COUNT (可选): 重试次数,默认为5
  • OPENAI_PROXY (可选): HTTP代理URL
  • OPENAI_USER_AGENT (可选): 自定义用户代理字符串
§错误

如果环境变量中未设置OPENAI_API_KEY,则返回错误。

§示例
# 设置环境变量
export OPENAI_API_KEY="sk-your-api-key"
export OPENAI_BASE_URL="https://api.openai.com/v1"  # 可选
export OPENAI_TIMEOUT="120"  # 可选,120秒
export OPENAI_RETRY_COUNT="3"  # 可选,3次重试
use openai4rs::OpenAI;
use dotenvy::dotenv;
#[tokio::main]
async fn main() -> Result<(), String> {
    dotenv().ok();
    let client = OpenAI::from_env()?;

    // 客户端已准备就绪
    println!("Connected to: {}", client.base_url().await);
    Ok(())
}
Source§

impl OpenAI

Source

pub async fn update_config<F>(&self, update_fn: F)
where F: FnOnce(&mut Config),

更新客户端配置并重新创建HTTP客户端。

此方法允许您修改现有客户端的配置,并使用新设置自动重新创建内部HTTP客户端。

§参数
  • update_fn - 更新配置的函数
§示例
use openai4rs::OpenAI;
use std::time::Duration;
#[tokio::main]
async fn main() {
let client = OpenAI::new("key", "https://api.openai.com/v1");

// 一次更新多个设置
client.update_config(|config| {
    config.with_timeout(Duration::from_secs(60))
          .with_retry_count(3)
          .with_proxy("http://localhost:8080");
}).await;
}
Source

pub fn chat(&self) -> &Chat

返回对聊天补全客户端的引用。

使用此客户端执行聊天补全,包括流式响应、工具调用和推理模式交互。

§示例
§基本聊天补全
use openai4rs::*;
use dotenvy::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let client = OpenAI::from_env()?;
    let messages = vec![user!("Hello, how are you?")];
   
    let response = client
        .chat()
        .create(ChatParam::new("Qwen/Qwen3-235B-A22B-Instruct-2507", &messages))
        .await?;
   
    println!("Response: {:#?}", response);
    Ok(())
}
§流式聊天补全
use futures::StreamExt;
use openai4rs::*;
use dotenvy::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let client = OpenAI::from_env()?;
    let messages = vec![user!("Tell me a story")];
   
    let mut stream = client
        .chat()
        .create_stream(
            ChatParam::new("Qwen/Qwen3-235B-A22B-Instruct-2507", &messages)
                .max_completion_tokens(64),
        )
        .await?;
   
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        if let Some(choice) = chunk.choices.first() {
            if let Some(content) = &choice.delta.content {
                print!("{}", content);
            }
        }
    }
    Ok(())
}
Source

pub fn completions(&self) -> &Completions

返回对补全客户端的引用。

用于传统的文本补全(非聊天格式)。

§示例
use openai4rs::{OpenAI, CompletionsParam};
use dotenvy::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let client = OpenAI::from_env()?;
    let response = client
        .completions()
        .create(CompletionsParam::new("Qwen/Qwen3-235B-A22B-Instruct-2507", "Write a poem about the Rust programming language").max_tokens(64))
        .await;

    println!("Response: {:#?}", response);
    Ok(())
}
Source

pub fn models(&self) -> &Models

返回对模型客户端的引用。

用于列出可用模型或检索模型信息。

§示例
use openai4rs::OpenAI;
use dotenvy::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let client = OpenAI::from_env()?;
    // 列出所有可用模型
    let models = client
        .models()
        .list(Default::default())
        .await?;

    for model in models.data {
        println!("Model: {}", model.id);
    }
    Ok(())
}
Source

pub fn embeddings(&self) -> &Embeddings

返回对嵌入客户端的引用。

使用此客户端为搜索、聚类和其他机器学习任务生成文本的向量表示。

§示例
§基本嵌入生成
use openai4rs::*;
use dotenvy::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let client = OpenAI::from_env()?;

    let response = client
        .embeddings()
        .create(EmbeddingsParam::new("text-embedding-ada-002", "Hello, world!"))
        .await?;

    println!("Generated {} embeddings", response.len());
    println!("Total tokens used: {}", response.total_tokens());
    Ok(())
}
§多文本嵌入
use openai4rs::*;
use dotenvy::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenv().ok();
    let client = OpenAI::from_env()?;
    let texts = vec!["Hello, world!", "How are you?", "Rust is awesome!"];

    let response = client
        .embeddings()
        .create(EmbeddingsParam::new("text-embedding-ada-002", texts))
        .await?;

    println!("Generated {} embeddings", response.len());
    for (i, embedding) in response.embeddings().iter().enumerate() {
        println!("Embedding {}: {} dimensions", i, embedding.dimensions());
    }
    Ok(())
}
Source

pub async fn base_url(&self) -> String

返回当前的基础URL。

Source

pub async fn api_key(&self) -> String

返回当前的API密钥。

Source

pub async fn config(&self) -> RwLockReadGuard<'_, Config>

返回当前的配置。

Source

pub async fn with_base_url(&self, base_url: impl Into<String>)

更新客户端的基础URL。

此操作不会重建HTTP客户端,因为它在每个请求中都会使用。

Source

pub async fn with_api_key(&self, api_key: impl Into<String>)

更新客户端的API密钥。

此操作不会重建HTTP客户端,因为API密钥在每个请求的头部中发送。

Source

pub async fn with_timeout(&self, timeout: Duration)

更新客户端的请求超时时间(以秒为单位)。

此操作将使用新设置重建内部HttpService。

Source

pub async fn with_connect_timeout(&self, connect_timeout: Duration)

更新客户端的连接超时时间(以秒为单位)。

此操作将使用新设置重建内部HttpService。

Source

pub async fn with_retry_count(&self, retry_count: usize)

更新客户端的最大重试次数。

此操作不会重建HTTP客户端,因为它在每次重试时都会使用。

Source

pub async fn with_proxy(&self, proxy: impl Into<String>)

更新客户端的HTTP代理。

此操作将使用新设置重建内部HttpService。

Source

pub async fn with_user_agent(&self, user_agent: HeaderValue)

更新客户端的自定义用户代理。

此操作将使用新设置重建内部HttpService。

Auto Trait Implementations§

§

impl Freeze for OpenAI

§

impl !RefUnwindSafe for OpenAI

§

impl Send for OpenAI

§

impl Sync for OpenAI

§

impl Unpin for OpenAI

§

impl !UnwindSafe for OpenAI

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

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