Add custom error

This commit is contained in:
Dongri Jin
2023-03-05 07:37:39 +09:00
parent 95bef4a7b8
commit d3223befbd
5 changed files with 53 additions and 32 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "openai-api-rs" name = "openai-api-rs"
version = "0.1.3" version = "0.1.4"
edition = "2021" edition = "2021"
authors = ["Dongri Jin <dongrify@gmail.com>"] authors = ["Dongri Jin <dongrify@gmail.com>"]
license = "MIT" license = "MIT"

View File

@ -4,7 +4,7 @@
Cargo.toml Cargo.toml
```toml ```toml
[dependencies] [dependencies]
openai-api-rs = "0.1.3" openai-api-rs = "0.1.4"
``` ```
## Example: ## Example:

View File

@ -2,6 +2,7 @@ use crate::v1::chat_completion::{ChatCompletionRequest, ChatCompletionResponse};
use crate::v1::completion::{CompletionRequest, CompletionResponse}; use crate::v1::completion::{CompletionRequest, CompletionResponse};
use crate::v1::edit::{EditRequest, EditResponse}; use crate::v1::edit::{EditRequest, EditResponse};
use crate::v1::embedding::{EmbeddingRequest, EmbeddingResponse}; use crate::v1::embedding::{EmbeddingRequest, EmbeddingResponse};
use crate::v1::error::APIError;
use crate::v1::file::{ use crate::v1::file::{
FileDeleteRequest, FileDeleteResponse, FileListResponse, FileRetrieveContentRequest, FileDeleteRequest, FileDeleteResponse, FileListResponse, FileRetrieveContentRequest,
FileRetrieveContentResponse, FileRetrieveRequest, FileRetrieveResponse, FileUploadRequest, FileRetrieveContentResponse, FileRetrieveRequest, FileRetrieveResponse, FileUploadRequest,
@ -12,7 +13,6 @@ use crate::v1::image::{
ImageVariationRequest, ImageVariationResponse, ImageVariationRequest, ImageVariationResponse,
}; };
use reqwest::Response; use reqwest::Response;
use std::io::Error;
const APU_URL_V1: &str = "https://api.openai.com/v1"; const APU_URL_V1: &str = "https://api.openai.com/v1";
@ -29,7 +29,7 @@ impl Client {
&self, &self,
path: &str, path: &str,
params: &T, params: &T,
) -> Result<Response, Error> { ) -> Result<Response, APIError> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let url = format!("{APU_URL_V1}{path}"); let url = format!("{APU_URL_V1}{path}");
let res = client let res = client
@ -45,16 +45,15 @@ impl Client {
match res { match res {
Ok(res) => match res.status().is_success() { Ok(res) => match res.status().is_success() {
true => Ok(res), true => Ok(res),
false => Err(Error::new( false => Err(APIError {
std::io::ErrorKind::Other, message: format!("{}: {}", res.status(), res.text().await.unwrap()),
format!("{}: {}", res.status(), res.text().await.unwrap()), }),
)),
}, },
Err(e) => Err(self.new_error(e)), Err(e) => Err(self.new_error(e)),
} }
} }
pub async fn get(&self, path: &str) -> Result<Response, Error> { pub async fn get(&self, path: &str) -> Result<Response, APIError> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let url = format!("{APU_URL_V1}{path}"); let url = format!("{APU_URL_V1}{path}");
let res = client let res = client
@ -69,16 +68,15 @@ impl Client {
match res { match res {
Ok(res) => match res.status().is_success() { Ok(res) => match res.status().is_success() {
true => Ok(res), true => Ok(res),
false => Err(Error::new( false => Err(APIError {
std::io::ErrorKind::Other, message: format!("{}: {}", res.status(), res.text().await.unwrap()),
format!("{}: {}", res.status(), res.text().await.unwrap()), }),
)),
}, },
Err(e) => Err(self.new_error(e)), Err(e) => Err(self.new_error(e)),
} }
} }
pub async fn delete(&self, path: &str) -> Result<Response, Error> { pub async fn delete(&self, path: &str) -> Result<Response, APIError> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let url = format!("{APU_URL_V1}{path}"); let url = format!("{APU_URL_V1}{path}");
let res = client let res = client
@ -93,16 +91,15 @@ impl Client {
match res { match res {
Ok(res) => match res.status().is_success() { Ok(res) => match res.status().is_success() {
true => Ok(res), true => Ok(res),
false => Err(Error::new( false => Err(APIError {
std::io::ErrorKind::Other, message: format!("{}: {}", res.status(), res.text().await.unwrap()),
format!("{}: {}", res.status(), res.text().await.unwrap()), }),
)),
}, },
Err(e) => Err(self.new_error(e)), Err(e) => Err(self.new_error(e)),
} }
} }
pub async fn completion(&self, req: CompletionRequest) -> Result<CompletionResponse, Error> { pub async fn completion(&self, req: CompletionRequest) -> Result<CompletionResponse, APIError> {
let res = self.post("/completions", &req).await?; let res = self.post("/completions", &req).await?;
let r = res.json::<CompletionResponse>().await; let r = res.json::<CompletionResponse>().await;
match r { match r {
@ -111,7 +108,7 @@ impl Client {
} }
} }
pub async fn edit(&self, req: EditRequest) -> Result<EditResponse, Error> { pub async fn edit(&self, req: EditRequest) -> Result<EditResponse, APIError> {
let res = self.post("/edits", &req).await?; let res = self.post("/edits", &req).await?;
let r = res.json::<EditResponse>().await; let r = res.json::<EditResponse>().await;
match r { match r {
@ -123,7 +120,7 @@ impl Client {
pub async fn image_generation( pub async fn image_generation(
&self, &self,
req: ImageGenerationRequest, req: ImageGenerationRequest,
) -> Result<ImageGenerationResponse, Error> { ) -> Result<ImageGenerationResponse, APIError> {
let res = self.post("/images/generations", &req).await?; let res = self.post("/images/generations", &req).await?;
let r = res.json::<ImageGenerationResponse>().await; let r = res.json::<ImageGenerationResponse>().await;
match r { match r {
@ -132,7 +129,7 @@ impl Client {
} }
} }
pub async fn image_edit(&self, req: ImageEditRequest) -> Result<ImageEditResponse, Error> { pub async fn image_edit(&self, req: ImageEditRequest) -> Result<ImageEditResponse, APIError> {
let res = self.post("/images/edits", &req).await?; let res = self.post("/images/edits", &req).await?;
let r = res.json::<ImageEditResponse>().await; let r = res.json::<ImageEditResponse>().await;
match r { match r {
@ -144,7 +141,7 @@ impl Client {
pub async fn image_variation( pub async fn image_variation(
&self, &self,
req: ImageVariationRequest, req: ImageVariationRequest,
) -> Result<ImageVariationResponse, Error> { ) -> Result<ImageVariationResponse, APIError> {
let res = self.post("/images/variations", &req).await?; let res = self.post("/images/variations", &req).await?;
let r = res.json::<ImageVariationResponse>().await; let r = res.json::<ImageVariationResponse>().await;
match r { match r {
@ -153,7 +150,7 @@ impl Client {
} }
} }
pub async fn embedding(&self, req: EmbeddingRequest) -> Result<EmbeddingResponse, Error> { pub async fn embedding(&self, req: EmbeddingRequest) -> Result<EmbeddingResponse, APIError> {
let res = self.post("/embeddings", &req).await?; let res = self.post("/embeddings", &req).await?;
let r = res.json::<EmbeddingResponse>().await; let r = res.json::<EmbeddingResponse>().await;
match r { match r {
@ -162,7 +159,7 @@ impl Client {
} }
} }
pub async fn file_list(&self) -> Result<FileListResponse, Error> { pub async fn file_list(&self) -> Result<FileListResponse, APIError> {
let res = self.get("/files").await?; let res = self.get("/files").await?;
let r = res.json::<FileListResponse>().await; let r = res.json::<FileListResponse>().await;
match r { match r {
@ -171,7 +168,10 @@ impl Client {
} }
} }
pub async fn file_upload(&self, req: FileUploadRequest) -> Result<FileUploadResponse, Error> { pub async fn file_upload(
&self,
req: FileUploadRequest,
) -> Result<FileUploadResponse, APIError> {
let res = self.post("/files", &req).await?; let res = self.post("/files", &req).await?;
let r = res.json::<FileUploadResponse>().await; let r = res.json::<FileUploadResponse>().await;
match r { match r {
@ -180,7 +180,10 @@ impl Client {
} }
} }
pub async fn file_delete(&self, req: FileDeleteRequest) -> Result<FileDeleteResponse, Error> { pub async fn file_delete(
&self,
req: FileDeleteRequest,
) -> Result<FileDeleteResponse, APIError> {
let res = self let res = self
.delete(&format!("{}/{}", "/files", req.file_id)) .delete(&format!("{}/{}", "/files", req.file_id))
.await?; .await?;
@ -194,7 +197,7 @@ impl Client {
pub async fn file_retrieve( pub async fn file_retrieve(
&self, &self,
req: FileRetrieveRequest, req: FileRetrieveRequest,
) -> Result<FileRetrieveResponse, Error> { ) -> Result<FileRetrieveResponse, APIError> {
let res = self.get(&format!("{}/{}", "/files", req.file_id)).await?; let res = self.get(&format!("{}/{}", "/files", req.file_id)).await?;
let r = res.json::<FileRetrieveResponse>().await; let r = res.json::<FileRetrieveResponse>().await;
match r { match r {
@ -206,7 +209,7 @@ impl Client {
pub async fn file_retrieve_content( pub async fn file_retrieve_content(
&self, &self,
req: FileRetrieveContentRequest, req: FileRetrieveContentRequest,
) -> Result<FileRetrieveContentResponse, Error> { ) -> Result<FileRetrieveContentResponse, APIError> {
let res = self let res = self
.get(&format!("{}/{}/content", "/files", req.file_id)) .get(&format!("{}/{}/content", "/files", req.file_id))
.await?; .await?;
@ -220,7 +223,7 @@ impl Client {
pub async fn chat_completion( pub async fn chat_completion(
&self, &self,
req: ChatCompletionRequest, req: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, Error> { ) -> Result<ChatCompletionResponse, APIError> {
let res = self.post("/chat/completions", &req).await?; let res = self.post("/chat/completions", &req).await?;
let r = res.json::<ChatCompletionResponse>().await; let r = res.json::<ChatCompletionResponse>().await;
match r { match r {
@ -229,7 +232,9 @@ impl Client {
} }
} }
fn new_error(&self, err: reqwest::Error) -> Error { fn new_error(&self, err: reqwest::Error) -> APIError {
Error::new(std::io::ErrorKind::Other, err) APIError {
message: err.to_string(),
}
} }
} }

15
src/v1/error.rs Normal file
View File

@ -0,0 +1,15 @@
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub struct APIError {
pub message: String,
}
impl fmt::Display for APIError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "APIError: {}", self.message)
}
}
impl Error for APIError {}

View File

@ -1,4 +1,5 @@
pub mod common; pub mod common;
pub mod error;
pub mod chat_completion; pub mod chat_completion;
pub mod completion; pub mod completion;