【Rust】OpenAIのAPIを使ってみる

APIキーをenvファイルに設定しなければならないので、OSSとして使うのは無理があるな…

use dotenv::dotenv;
use std::env;
use openai_api_rust::*;
use openai_api_rust::chat::*;
use openai_api_rust::completions::*;

fn main() {
    let _ = dotenv();
    let auth = Auth::new(&env::var("OPENAI_API_KEY").unwrap());
    let openai = OpenAI::new(auth, "https://api.openai.com/v1/");
    let body = ChatBody {
        model: "gpt-3.5-turbo".to_string(),
        max_tokens: Some(100),
        temperature: Some(0_f32),
        top_p: Some(0_f32),
        n: Some(2),
        stream: Some(false),
        stop: None,
        presence_penalty: None,
        frequency_penalty: None,
        logit_bias: None,
        user: None,
        messages: vec![Message { role: Role::User, content: "有名なキャラクターは?".to_string() }],
    };
    let rs = openai.chat_completion_create(&body);
    let choice = rs.unwrap().choices;
    let message = &choice[0].message.as_ref().unwrap();
    println!{"{}", message.content};
}

Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.14s
Running `target/debug/sample`
有名なキャラクターには、以下のようなものがあります。

– ミッキーマウス(ディズニーキャラクター)
– マリオ(任天堂のゲーム「スーパーマリオブラザーズ」の主人公)
– ピカチュウ(ポケモンの一匹)