Created
May 18, 2023 00:46
-
-
Save junichiro/8045b8541ea4199d9d10debdd2e3d060 to your computer and use it in GitHub Desktop.
Rust で OpenAI API を呼ぶ例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use async_openai::{Client, types::{CreateCompletionRequestArgs}}; | |
pub struct OpenAi { | |
client: Client, | |
model: String, | |
max_tokens: u16, | |
} | |
impl OpenAi { | |
pub fn new(model: String, max_tokens: u16) -> Self { | |
let client = Client::new(); | |
Self { | |
client, | |
model, | |
max_tokens, | |
} | |
} | |
pub async fn ask(&self, input: &str) -> String { | |
// Create request using builder pattern | |
// Every request struct has companion builder struct with same name + Args suffix | |
let request = CreateCompletionRequestArgs::default() | |
.model(&self.model) | |
.prompt(format!("以下の結果をHTMLに変換して答えてください。{}", input)) | |
.max_tokens(self.max_tokens) | |
.build() | |
.unwrap(); | |
// Call API | |
let response = self.client.completions().create(request).await.unwrap(); | |
let response_text = format!("{}", response.choices.first().unwrap().text); | |
response_text | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
async_openai
で API KEY を指定しない場合、default で環境変数に設定されている OPENAI_API_KEY という変数の値が使われます。https://docs.rs/async-openai/latest/async_openai/