1use serde::Deserialize;
3
4#[derive(Debug, thiserror::Error)]
5pub enum OpenAIError {
6 #[error("http error: {0}")]
8 Reqwest(#[from] reqwest::Error),
9 #[error("{0}")]
11 ApiError(ApiError),
12 #[error("failed to deserialize api response: {0}")]
14 JSONDeserialize(serde_json::Error),
15 #[error("failed to save file: {0}")]
17 FileSaveError(String),
18 #[error("failed to read file: {0}")]
20 FileReadError(String),
21 #[error("stream failed: {0}")]
23 StreamError(String),
24 #[error("invalid args: {0}")]
27 InvalidArgument(String),
28}
29
30#[derive(Debug, Deserialize, Clone)]
32pub struct ApiError {
33 pub message: String,
34 pub r#type: Option<String>,
35 pub param: Option<String>,
36 pub code: Option<String>,
37}
38
39impl std::fmt::Display for ApiError {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 let mut parts = Vec::new();
45
46 if let Some(r#type) = &self.r#type {
47 parts.push(format!("{}:", r#type));
48 }
49
50 parts.push(self.message.clone());
51
52 if let Some(param) = &self.param {
53 parts.push(format!("(param: {param})"));
54 }
55
56 if let Some(code) = &self.code {
57 parts.push(format!("(code: {code})"));
58 }
59
60 write!(f, "{}", parts.join(" "))
61 }
62}
63
64#[derive(Debug, Deserialize)]
66pub(crate) struct WrappedError {
67 pub(crate) error: ApiError,
68}
69
70pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> OpenAIError {
71 tracing::error!(
72 "failed deserialization of: {}",
73 String::from_utf8_lossy(bytes)
74 );
75 OpenAIError::JSONDeserialize(e)
76}