pub struct Chat { /* private fields */ }Expand description
处理聊天完成请求,包括流式和非流式模式。
Implementations§
Source§impl Chat
impl Chat
Sourcepub async fn create(
&self,
param: ChatParam,
) -> Result<ChatCompletion, OpenAIError>
pub async fn create( &self, param: ChatParam, ) -> Result<ChatCompletion, OpenAIError>
创建一个聊天完成。
此方法向API发送请求,并在单个响应中返回完整的完成结果。
§参数
param- 聊天完成的一组参数,例如模型和消息。 可以使用ChatParam创建。
§示例
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!("What is Rust?")];
let request = ChatParam::new("Qwen/Qwen3-235B-A22B-Instruct-2507", &messages);
let response = client.chat().create(request).await?;
println!("{:#?}", response);
Ok(())
}Sourcepub async fn create_stream(
&self,
param: ChatParam,
) -> Result<ReceiverStream<Result<ChatCompletionChunk, OpenAIError>>, OpenAIError>
pub async fn create_stream( &self, param: ChatParam, ) -> Result<ReceiverStream<Result<ChatCompletionChunk, OpenAIError>>, OpenAIError>
创建一个流式聊天完成。
此方法返回 ChatCompletionChunk 事件流。这对于实时显示生成的完成结果非常有用。
§参数
param- 聊天完成的一组参数,例如模型和消息。 可以使用ChatParam创建。
§示例
use openai4rs::*;
use futures::StreamExt;
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 short story.")];
let request = ChatParam::new("Qwen/Qwen3-235B-A22B-Instruct-2507", &messages);
let mut stream = client.chat().create_stream(request).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(())
}Auto Trait Implementations§
impl Freeze for Chat
impl !RefUnwindSafe for Chat
impl Send for Chat
impl Sync for Chat
impl Unpin for Chat
impl !UnwindSafe for Chat
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