use serde::{Deserialize, Serialize};
#[cfg(all(feature = "_api", not(target_family = "wasm")))]
#[derive(Debug, thiserror::Error)]
pub enum OpenAIError {
#[error("http error: {0}")]
Reqwest(#[from] reqwest::Error),
#[error("{0}")]
ApiError(ApiError),
#[error("failed to deserialize api response: error:{0} content:{1}")]
JSONDeserialize(serde_json::Error, String),
#[error("failed to save file: {0}")]
FileSaveError(String),
#[error("failed to read file: {0}")]
FileReadError(String),
#[error("stream failed: {0}")]
StreamError(Box<StreamError>),
#[error("invalid args: {0}")]
InvalidArgument(String),
}
#[cfg(all(feature = "_api", target_family = "wasm"))]
#[derive(Debug, thiserror::Error)]
pub enum OpenAIError {
#[error("http error: {0}")]
Reqwest(#[from] reqwest::Error),
#[error("{0}")]
ApiError(ApiError),
#[error("failed to deserialize api response: error:{0} content:{1}")]
JSONDeserialize(serde_json::Error, String),
#[error("invalid args: {0}")]
InvalidArgument(String),
}
#[cfg(not(feature = "_api"))]
#[derive(Debug)]
pub enum OpenAIError {
InvalidArgument(String),
}
#[cfg(not(feature = "_api"))]
impl std::fmt::Display for OpenAIError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OpenAIError::InvalidArgument(msg) => write!(f, "invalid args: {}", msg),
}
}
}
#[cfg(not(feature = "_api"))]
impl std::error::Error for OpenAIError {}
#[cfg(all(feature = "_api", not(target_family = "wasm")))]
#[derive(Debug, thiserror::Error)]
pub enum StreamError {
#[error("{0}")]
ReqwestEventSource(#[from] reqwest_eventsource::Error),
#[error("Unknown event: {0:#?}")]
UnknownEvent(eventsource_stream::Event),
#[error("EventStream error: {0}")]
EventStream(String),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ApiError {
pub message: String,
pub r#type: Option<String>,
pub param: Option<String>,
pub code: Option<String>,
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut parts = Vec::new();
if let Some(r#type) = &self.r#type {
parts.push(format!("{}:", r#type));
}
parts.push(self.message.clone());
if let Some(param) = &self.param {
parts.push(format!("(param: {param})"));
}
if let Some(code) = &self.code {
parts.push(format!("(code: {code})"));
}
write!(f, "{}", parts.join(" "))
}
}
impl std::error::Error for ApiError {}
#[derive(Debug, Deserialize, Serialize)]
pub struct WrappedError {
pub error: ApiError,
}
#[cfg(feature = "_api")]
pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> OpenAIError {
let json_content = String::from_utf8_lossy(bytes);
tracing::error!("failed deserialization of: {}", json_content);
OpenAIError::JSONDeserialize(e, json_content.to_string())
}