Skip to content

Instantly share code, notes, and snippets.

@junichiro
Created May 18, 2023 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junichiro/8045b8541ea4199d9d10debdd2e3d060 to your computer and use it in GitHub Desktop.
Save junichiro/8045b8541ea4199d9d10debdd2e3d060 to your computer and use it in GitHub Desktop.
Rust で OpenAI API を呼ぶ例
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
}
}
@junichiro
Copy link
Author

async_openai で API KEY を指定しない場合、default で環境変数に設定されている OPENAI_API_KEY という変数の値が使われます。

https://docs.rs/async-openai/latest/async_openai/

// Create a client with api key from env var OPENAI_API_KEY and default base url.
let client = Client::new();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment