* use reqwest

* support multipart form
* fix audio apits
This commit is contained in:
Dongri Jin
2024-07-09 18:47:51 +09:00
parent be660448f4
commit 3e5286dad6
18 changed files with 489 additions and 675 deletions

View File

@ -1,6 +1,6 @@
[package]
name = "openai-api-rs"
version = "4.1.1"
version = "5.0.0"
edition = "2021"
authors = ["Dongri Jin <dongrium@gmail.com>"]
license = "MIT"
@ -9,16 +9,17 @@ repository = "https://github.com/dongri/openai-api-rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies.reqwest]
version = "0.12"
features = ["json", "multipart"]
[dependencies.tokio]
version = "1"
features = ["full"]
[dependencies.serde]
version = "1"
features = ["derive"]
default-features = false
[dependencies.serde_json]
version = "1"
default-features = false
[dependencies.minreq]
version = "2"
default-features = false
features = ["https-rustls", "json-using-serde", "proxy"]

View File

@ -7,7 +7,7 @@ Check out the [docs.rs](https://docs.rs/openai-api-rs/).
Cargo.toml
```toml
[dependencies]
openai-api-rs = "4.1.1"
openai-api-rs = "5.0.0"
```
## Usage
@ -48,13 +48,14 @@ $ export OPENAI_API_BASE=https://api.openai.com/v1
## Example of chat completion
```rust
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::chat_completion::{self, ChatCompletionRequest};
use openai_api_rs::v1::common::GPT4_O;
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
GPT4_O.to_string(),
@ -65,7 +66,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}],
);
let result = client.chat_completion(req)?;
let result = client.chat_completion(req).await?;
println!("Content: {:?}", result.choices[0].message.content);
println!("Response Headers: {:?}", result.headers);

View File

@ -1,4 +1,4 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::assistant::AssistantRequest;
use openai_api_rs::v1::common::GPT4_O;
use openai_api_rs::v1::message::{CreateMessageRequest, MessageRole};
@ -7,8 +7,9 @@ use openai_api_rs::v1::thread::CreateThreadRequest;
use std::collections::HashMap;
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut tools = HashMap::new();
tools.insert("type".to_string(), "code_interpreter".to_string());
@ -21,11 +22,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let req = req.clone().tools(vec![tools]);
println!("AssistantRequest: {:?}", req);
let result = client.create_assistant(req)?;
let result = client.create_assistant(req).await?;
println!("Create Assistant Result ID: {:?}", result.id);
let thread_req = CreateThreadRequest::new();
let thread_result = client.create_thread(thread_req)?;
let thread_result = client.create_thread(thread_req).await?;
println!("Create Thread Result ID: {:?}", thread_result.id.clone());
let message_req = CreateMessageRequest::new(
@ -33,16 +34,19 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
"`I need to solve the equation 3x + 11 = 14. Can you help me?".to_string(),
);
let message_result = client.create_message(thread_result.id.clone(), message_req)?;
let message_result = client
.create_message(thread_result.id.clone(), message_req)
.await?;
println!("Create Message Result ID: {:?}", message_result.id.clone());
let run_req = CreateRunRequest::new(result.id);
let run_result = client.create_run(thread_result.id.clone(), run_req)?;
let run_result = client.create_run(thread_result.id.clone(), run_req).await?;
println!("Create Run Result ID: {:?}", run_result.id.clone());
loop {
let run_result = client
.retrieve_run(thread_result.id.clone(), run_result.id.clone())
.await
.unwrap();
if run_result.status == "completed" {
break;
@ -52,7 +56,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}
let list_message_result = client.list_messages(thread_result.id.clone()).unwrap();
let list_message_result = client
.list_messages(thread_result.id.clone())
.await
.unwrap();
for data in list_message_result.data {
for content in data.content {
println!(

22
examples/audio_speech.rs Normal file
View File

@ -0,0 +1,22 @@
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::audio::{self, AudioSpeechRequest, TTS_1};
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioSpeechRequest::new(
TTS_1.to_string(),
String::from("Money is not the problem, the problem is no money."),
audio::VOICE_ALLOY.to_string(),
String::from("examples/data/problem.mp3"),
);
let result = client.audio_speech(req).await?;
println!("{:?}", result);
Ok(())
}
// OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example audio_speech

View File

@ -0,0 +1,20 @@
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::audio::{AudioTranscriptionRequest, WHISPER_1};
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioTranscriptionRequest::new(
"examples/data/problem.mp3".to_string(),
WHISPER_1.to_string(),
);
let result = client.audio_transcription(req).await?;
println!("{:?}", result);
Ok(())
}
// OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example audio_translations

View File

@ -0,0 +1,20 @@
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::audio::{AudioTranslationRequest, WHISPER_1};
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioTranslationRequest::new(
"examples/data/problem_cn.mp3".to_string(),
WHISPER_1.to_string(),
);
let result = client.audio_translation(req).await?;
println!("{:?}", result);
Ok(())
}
// OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example audio_transcriptions

View File

@ -1,10 +1,11 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::chat_completion::{self, ChatCompletionRequest};
use openai_api_rs::v1::common::GPT4_O;
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
GPT4_O.to_string(),
@ -15,7 +16,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}],
);
let result = client.chat_completion(req)?;
let result = client.chat_completion(req).await?;
println!("Content: {:?}", result.choices[0].message.content);
println!("Response Headers: {:?}", result.headers);

View File

@ -1,9 +1,10 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::completion::{self, CompletionRequest};
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = CompletionRequest::new(
completion::GPT3_TEXT_DAVINCI_003.to_string(),
@ -16,7 +17,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.presence_penalty(0.6)
.frequency_penalty(0.0);
let result = client.completion(req)?;
let result = client.completion(req).await?;
println!("{:}", result.choices[0].text);
Ok(())

BIN
examples/data/problem.mp3 Normal file

Binary file not shown.

Binary file not shown.

View File

@ -1,16 +1,17 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::common::TEXT_EMBEDDING_3_SMALL;
use openai_api_rs::v1::embedding::EmbeddingRequest;
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut req =
EmbeddingRequest::new(TEXT_EMBEDDING_3_SMALL.to_string(), "story time".to_string());
req.dimensions = Some(10);
let result = client.embedding(req)?;
let result = client.embedding(req).await?;
println!("{:?}", result.data);
Ok(())

View File

@ -1,6 +1,6 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::chat_completion::{self, ChatCompletionRequest};
use openai_api_rs::v1::common::GPT3_5_TURBO_0613;
use openai_api_rs::v1::common::GPT4_O;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::{env, vec};
@ -14,8 +14,9 @@ fn get_coin_price(coin: &str) -> f64 {
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
@ -28,7 +29,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let req = ChatCompletionRequest::new(
GPT3_5_TURBO_0613.to_string(),
GPT4_O.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
@ -53,7 +54,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// let serialized = serde_json::to_string(&req).unwrap();
// println!("{}", serialized);
let result = client.chat_completion(req)?;
let result = client.chat_completion(req).await?;
match result.choices[0].finish_reason {
None => {

View File

@ -1,6 +1,6 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::chat_completion::{self, ChatCompletionRequest};
use openai_api_rs::v1::common::GPT3_5_TURBO_0613;
use openai_api_rs::v1::common::GPT4_O;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::{env, vec};
@ -14,8 +14,9 @@ fn get_coin_price(coin: &str) -> f64 {
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let mut properties = HashMap::new();
properties.insert(
@ -28,7 +29,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let req = ChatCompletionRequest::new(
GPT3_5_TURBO_0613.to_string(),
GPT4_O.to_string(),
vec![chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
content: chat_completion::Content::Text(String::from("What is the price of Ethereum?")),
@ -48,7 +49,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
},
}]);
let result = client.chat_completion(req)?;
let result = client.chat_completion(req).await?;
match result.choices[0].finish_reason {
None => {
@ -79,7 +80,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("price: {}", price);
let req = ChatCompletionRequest::new(
GPT3_5_TURBO_0613.to_string(),
GPT4_O.to_string(),
vec![
chat_completion::ChatCompletionMessage {
role: chat_completion::MessageRole::user,
@ -99,7 +100,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
],
);
let result = client.chat_completion(req)?;
let result = client.chat_completion(req).await?;
println!("{:?}", result.choices[0].message.content);
}
}

View File

@ -1,21 +0,0 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::audio::{self, AudioSpeechRequest, TTS_1};
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = AudioSpeechRequest::new(
TTS_1.to_string(),
String::from("Money is not problem, Problem is no money"),
audio::VOICE_ALLOY.to_string(),
String::from("problem.mp3"),
);
let result = client.audio_speech(req)?;
println!("{:?}", result);
Ok(())
}
// OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example text_to_speech

View File

@ -1,10 +1,11 @@
use openai_api_rs::v1::api::Client;
use openai_api_rs::v1::api::OpenAIClient;
use openai_api_rs::v1::chat_completion::{self, ChatCompletionRequest};
use openai_api_rs::v1::common::GPT4_VISION_PREVIEW;
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new(env::var("OPENAI_API_KEY").unwrap().to_string());
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = OpenAIClient::new(env::var("OPENAI_API_KEY").unwrap().to_string());
let req = ChatCompletionRequest::new(
GPT4_VISION_PREVIEW.to_string(),
@ -30,7 +31,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}],
);
let result = client.chat_completion(req)?;
let result = client.chat_completion(req).await?;
println!("{:?}", result.choices[0].message.content);
Ok(())

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
use std::collections::HashMap;
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::impl_builder_methods;
@ -115,8 +115,8 @@ impl AudioSpeechRequest {
impl_builder_methods!(AudioSpeechRequest,);
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug)]
pub struct AudioSpeechResponse {
pub result: bool,
pub headers: Option<HashMap<String, String>>,
pub headers: Option<HeaderMap>,
}

View File

@ -1,15 +1,26 @@
use reqwest::{self};
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub struct APIError {
pub message: String,
pub enum APIError {
ReqwestError(reqwest::Error),
CustomError { message: String },
}
impl fmt::Display for APIError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "APIError: {}", self.message)
match self {
APIError::ReqwestError(err) => write!(f, "ReqwestError: {}", err),
APIError::CustomError { message } => write!(f, "APIError: {}", message),
}
}
}
impl Error for APIError {}
impl From<reqwest::Error> for APIError {
fn from(err: reqwest::Error) -> APIError {
APIError::ReqwestError(err)
}
}