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
impl OpenAI
Sourcepub fn with_config(config: Config) -> OpenAI
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);Sourcepub fn from_env() -> Result<Self, String>
pub fn from_env() -> Result<Self, String>
从环境变量创建新的OpenAI客户端。
查找以下环境变量:
OPENAI_API_KEY(必需): 您的API密钥OPENAI_BASE_URL(可选): 基础URL,默认为 “https://api.openai.com/v1”OPENAI_TIMEOUT(可选): 请求超时时间(秒),默认为60OPENAI_CONNECT_TIMEOUT(可选): 连接超时时间(秒),默认为10OPENAI_RETRY_COUNT(可选): 重试次数,默认为5OPENAI_PROXY(可选): HTTP代理URLOPENAI_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
impl OpenAI
Sourcepub async fn update_config<F>(&self, update_fn: F)
pub async fn update_config<F>(&self, update_fn: F)
更新客户端配置并重新创建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;
}Sourcepub fn chat(&self) -> &Chat
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(())
}Sourcepub fn completions(&self) -> &Completions
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(())
}Sourcepub fn models(&self) -> &Models
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(())
}Sourcepub fn embeddings(&self) -> &Embeddings
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(())
}Sourcepub async fn config(&self) -> RwLockReadGuard<'_, Config>
pub async fn config(&self) -> RwLockReadGuard<'_, Config>
返回当前的配置。
Sourcepub async fn with_base_url(&self, base_url: impl Into<String>)
pub async fn with_base_url(&self, base_url: impl Into<String>)
更新客户端的基础URL。
此操作不会重建HTTP客户端,因为它在每个请求中都会使用。
Sourcepub async fn with_api_key(&self, api_key: impl Into<String>)
pub async fn with_api_key(&self, api_key: impl Into<String>)
更新客户端的API密钥。
此操作不会重建HTTP客户端,因为API密钥在每个请求的头部中发送。
Sourcepub async fn with_timeout(&self, timeout: Duration)
pub async fn with_timeout(&self, timeout: Duration)
更新客户端的请求超时时间(以秒为单位)。
此操作将使用新设置重建内部HttpService。
Sourcepub async fn with_connect_timeout(&self, connect_timeout: Duration)
pub async fn with_connect_timeout(&self, connect_timeout: Duration)
更新客户端的连接超时时间(以秒为单位)。
此操作将使用新设置重建内部HttpService。
Sourcepub async fn with_retry_count(&self, retry_count: usize)
pub async fn with_retry_count(&self, retry_count: usize)
更新客户端的最大重试次数。
此操作不会重建HTTP客户端,因为它在每次重试时都会使用。
Sourcepub async fn with_proxy(&self, proxy: impl Into<String>)
pub async fn with_proxy(&self, proxy: impl Into<String>)
更新客户端的HTTP代理。
此操作将使用新设置重建内部HttpService。
Sourcepub async fn with_user_agent(&self, user_agent: HeaderValue)
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more