Rust OpenAI异步库async-openai-macros的使用:简化AI模型调用与宏驱动的API集成

Rust OpenAI异步库async-openai-macros的使用:简化AI模型调用与宏驱动的API集成

安装

在项目目录中运行以下Cargo命令:

cargo add async-openai-macros

或者在Cargo.toml中添加以下行:

async-openai-macros = "0.1.0"

使用示例

以下是一个完整的示例demo,展示如何使用async-openai-macros库简化OpenAI API调用:

use async_openai_macros::openai_api;
use serde::{Deserialize, Serialize};

// 定义API请求和响应结构体
#[derive(Debug, Serialize)]
struct ChatRequest {
    model: String,
    messages: Vec<Message>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Message {
    role: String,
    content: String,
}

#[derive(Debug, Deserialize)]
struct ChatResponse {
    choices: Vec<Choice>,
}

#[derive(Debug, Deserialize)]
struct Choice {
    message: Message,
}

// 使用宏简化API调用
#[openai_api(
    endpoint = "https://api.openai.com/v1/chat/completions",
    method = "POST",
    request = "ChatRequest",
    response = "ChatResponse"
)]
async fn chat_completion(request: ChatRequest) -> Result<ChatResponse, reqwest::Error>;

#[tokio::main]
async fn main() {
    // 准备请求数据
    let request = ChatRequest {
        model: "gpt-3.5-turbo".to_string(),
        messages: vec![Message {
            role: "user".to_string(),
            content: "Hello, how are you?".to_string(),
        }],
    };

    // 调用API
    match chat_completion(request).await {
        Ok(response) => {
            println!("Response: {:?}", response);
            if let Some(choice) = response.choices.first() {
                println!("AI回复: {}", choice.message.content);
            }
        }
        Err(e) => eprintln!("Error: {:?}", e),
    }
}

功能说明

  1. openai_api宏自动处理:

    • HTTP请求构建
    • 请求头设置(包括认证)
    • 序列化/反序列化
    • 错误处理
  2. 主要特性:

    • 异步支持(基于tokio)
    • 类型安全的API调用
    • 简化的请求/响应处理
    • 自动的错误转换

注意事项

  1. 需要设置环境变量OPENAI_API_KEY或手动配置认证信息
  2. 确保你的项目依赖了tokioreqwest作为异步运行时和HTTP客户端
  3. 所有结构体需要实现Serialize和/或Deserialize trait

所有者信息

  • Himanshu Neema

许可证

MIT License


1 回复

Rust OpenAI异步库async-openai-macros使用指南

async-openai-macros是一个简化OpenAI API调用的Rust宏库,它构建在async-openai之上,提供了更简洁的语法来与OpenAI的各种模型交互。

主要特性

  • 简化OpenAI API调用语法
  • 自动处理异步操作
  • 类型安全的请求和响应
  • 支持聊天、补全、嵌入等多种模型

安装

Cargo.toml中添加依赖:

[dependencies]
async-openai = "0.16"
async-openai-macros = "0.3"
tokio = { version = "1.0", features = ["full"] }

基本使用方法

1. 聊天补全示例

use async_openai_macros::chat_completion;

#[tokio::main]
async fn main() {
    let response = chat_completion! {
        model: "gpt-4",
        messages: [
            {"role": "system", "content": "你是一个有帮助的助手"},
            {"role": "user", "content": "Rust中的所有权是什么?"}
        ]
    }.await;
    
    println!("Response: {}", response.choices[0].message.content);
}

2. 文本补全示例

use async_openai_macros::completion;

#[tokio::main]
async fn main() {
    let response = completion! {
        model: "text-davinci-003",
        prompt: "解释Rust中的借用规则:",
        max_tokens: 100
    }.await;
    
    println!("Response: {}", response.choices[0].text);
}

3. 嵌入生成示例

use async_openai_macros::create_embedding;

#[tokio::main]
async fn main() {
    let response = create_embedding! {
        model: "text-embedding-ada-002",
        input: "Rust是一种系统编程语言"
    }.await;
    
    println!("Embedding vector: {:?}", response.data[0].embedding);
}

高级用法

流式响应处理

use async_openai_macros::chat_completion_stream;
use futures::StreamExt;

#[tokio::main]
async fn main() {
    let mut stream = chat_completion_stream! {
        model: "gpt-4",
        messages: [
            {"role": "user", "content": "用Rust实现一个简单的HTTP服务器"}
        ]
    };
    
    while let Some(response) = stream.next().await {
        if let Some(content) = &response.choices[0].delta.content {
            print!("{}", content);
        }
    }
}

带参数的调用

use async_openai_macros::chat_completion;

#[tokio::main]
async fn main() {
    let question = "Rust中的trait是什么?";
    
    let response = chat_completion! {
        model: "gpt-4",
        messages: [
            {"role": "system", "content": "你是一个Rust专家"},
            {"role": "user", "content": question}
        ],
        temperature: 0.7,
        max_tokens: 500
    }.await;
    
    println!("Answer: {}", response.choices[0].message.content);
}

配置API密钥

在使用前需要设置OpenAI API密钥:

use async_openai::config::OpenAIConfig;

#[tokio::main]
async fn main() {
    // 从环境变量中读取API密钥
    std::env::set_var("OPENAI_API_KEY", "your-api-key-here");
    
    // 或者直接配置
    let config = OpenAIConfig::new().with_api_key("your-api-key-here");
    
    // 后续宏调用会自动使用这个配置
}

错误处理

宏调用会返回Result类型,可以进行错误处理:

use async_openai_macros::chat_completion;

#[tokio::main]
async fn main() {
    match chat_completion! {
        model: "gpt-4",
        messages: [
            {"role": "user", "content": "Rust中的生命周期是什么?"}
        ]
    }.await {
        Ok(response) => println!("{}", response.choices[0].message.content),
        Err(e) => eprintln!("Error: {}", e),
    }
}

完整示例代码

以下是一个完整的聊天补全示例,包含API密钥配置和错误处理:

use async_openai::config::OpenAIConfig;
use async_openai_macros::chat_completion;
use std::env;

#[tokio::main]
async fn main() {
    // 设置OpenAI API密钥
    env::set_var("OPENAI_API_KEY", "your-api-key-here");
    
    // 或者使用直接配置方式
    // let config = OpenAIConfig::new().with_api_key("your-api-key-here");

    // 调用聊天补全API
    match chat_completion! {
        model: "gpt-4",
        messages: [
            {"role": "system", "content": "你是一个有帮助的Rust编程助手"},
            {"role": "user", "content": "请解释Rust中的所有权系统"}
        ],
        temperature: 0.7,
        max_tokens: 300
    }.await {
        Ok(response) => {
            println!("AI回复: {}", response.choices[0].message.content);
        },
        Err(e) => {
            eprintln!("调用OpenAI API出错: {}", e);
        }
    }
}

这个完整示例展示了:

  1. 如何设置API密钥
  2. 如何使用chat_completion宏
  3. 如何处理可能的错误
  4. 如何添加额外的参数如temperature和max_tokens

您可以根据需要修改模型、消息内容和其他参数来满足您的具体需求。

回到顶部