Skip to content

Commit

Permalink
Add custom error
Browse files Browse the repository at this point in the history
  • Loading branch information
Dongri Jin committed Mar 4, 2023
1 parent 95bef4a commit d3223be
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 32 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "openai-api-rs"
version = "0.1.3"
version = "0.1.4"
edition = "2021"
authors = ["Dongri Jin <[email protected]>"]
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Cargo.toml
```toml
[dependencies]
openai-api-rs = "0.1.3"
openai-api-rs = "0.1.4"
```

## Example:
Expand Down
65 changes: 35 additions & 30 deletions src/v1/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::v1::chat_completion::{ChatCompletionRequest, ChatCompletionResponse};
use crate::v1::completion::{CompletionRequest, CompletionResponse};
use crate::v1::edit::{EditRequest, EditResponse};
use crate::v1::embedding::{EmbeddingRequest, EmbeddingResponse};
use crate::v1::error::APIError;
use crate::v1::file::{
FileDeleteRequest, FileDeleteResponse, FileListResponse, FileRetrieveContentRequest,
FileRetrieveContentResponse, FileRetrieveRequest, FileRetrieveResponse, FileUploadRequest,
Expand All @@ -12,7 +13,6 @@ use crate::v1::image::{
ImageVariationRequest, ImageVariationResponse,
};
use reqwest::Response;
use std::io::Error;

const APU_URL_V1: &str = "https://api.openai.com/v1";

Expand All @@ -29,7 +29,7 @@ impl Client {
&self,
path: &str,
params: &T,
) -> Result<Response, Error> {
) -> Result<Response, APIError> {
let client = reqwest::Client::new();
let url = format!("{APU_URL_V1}{path}");
let res = client
Expand All @@ -45,16 +45,15 @@ impl Client {
match res {
Ok(res) => match res.status().is_success() {
true => Ok(res),
false => Err(Error::new(
std::io::ErrorKind::Other,
format!("{}: {}", res.status(), res.text().await.unwrap()),
)),
false => Err(APIError {
message: format!("{}: {}", res.status(), res.text().await.unwrap()),
}),
},
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 url = format!("{APU_URL_V1}{path}");
let res = client
Expand All @@ -69,16 +68,15 @@ impl Client {
match res {
Ok(res) => match res.status().is_success() {
true => Ok(res),
false => Err(Error::new(
std::io::ErrorKind::Other,
format!("{}: {}", res.status(), res.text().await.unwrap()),
)),
false => Err(APIError {
message: format!("{}: {}", res.status(), res.text().await.unwrap()),
}),
},
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 url = format!("{APU_URL_V1}{path}");
let res = client
Expand All @@ -93,16 +91,15 @@ impl Client {
match res {
Ok(res) => match res.status().is_success() {
true => Ok(res),
false => Err(Error::new(
std::io::ErrorKind::Other,
format!("{}: {}", res.status(), res.text().await.unwrap()),
)),
false => Err(APIError {
message: format!("{}: {}", res.status(), res.text().await.unwrap()),
}),
},
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 r = res.json::<CompletionResponse>().await;
match r {
Expand All @@ -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 r = res.json::<EditResponse>().await;
match r {
Expand All @@ -123,7 +120,7 @@ impl Client {
pub async fn image_generation(
&self,
req: ImageGenerationRequest,
) -> Result<ImageGenerationResponse, Error> {
) -> Result<ImageGenerationResponse, APIError> {
let res = self.post("/images/generations", &req).await?;
let r = res.json::<ImageGenerationResponse>().await;
match r {
Expand All @@ -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 r = res.json::<ImageEditResponse>().await;
match r {
Expand All @@ -144,7 +141,7 @@ impl Client {
pub async fn image_variation(
&self,
req: ImageVariationRequest,
) -> Result<ImageVariationResponse, Error> {
) -> Result<ImageVariationResponse, APIError> {
let res = self.post("/images/variations", &req).await?;
let r = res.json::<ImageVariationResponse>().await;
match r {
Expand All @@ -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 r = res.json::<EmbeddingResponse>().await;
match r {
Expand All @@ -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 r = res.json::<FileListResponse>().await;
match r {
Expand All @@ -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 r = res.json::<FileUploadResponse>().await;
match r {
Expand All @@ -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
.delete(&format!("{}/{}", "/files", req.file_id))
.await?;
Expand All @@ -194,7 +197,7 @@ impl Client {
pub async fn file_retrieve(
&self,
req: FileRetrieveRequest,
) -> Result<FileRetrieveResponse, Error> {
) -> Result<FileRetrieveResponse, APIError> {
let res = self.get(&format!("{}/{}", "/files", req.file_id)).await?;
let r = res.json::<FileRetrieveResponse>().await;
match r {
Expand All @@ -206,7 +209,7 @@ impl Client {
pub async fn file_retrieve_content(
&self,
req: FileRetrieveContentRequest,
) -> Result<FileRetrieveContentResponse, Error> {
) -> Result<FileRetrieveContentResponse, APIError> {
let res = self
.get(&format!("{}/{}/content", "/files", req.file_id))
.await?;
Expand All @@ -220,7 +223,7 @@ impl Client {
pub async fn chat_completion(
&self,
req: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, Error> {
) -> Result<ChatCompletionResponse, APIError> {
let res = self.post("/chat/completions", &req).await?;
let r = res.json::<ChatCompletionResponse>().await;
match r {
Expand All @@ -229,7 +232,9 @@ impl Client {
}
}

fn new_error(&self, err: reqwest::Error) -> Error {
Error::new(std::io::ErrorKind::Other, err)
fn new_error(&self, err: reqwest::Error) -> APIError {
APIError {
message: err.to_string(),
}
}
}
15 changes: 15 additions & 0 deletions src/v1/error.rs
Original file line number Diff line number Diff line change
@@ -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 {}
1 change: 1 addition & 0 deletions src/v1/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod common;
pub mod error;

pub mod chat_completion;
pub mod completion;
Expand Down

0 comments on commit d3223be

Please sign in to comment.