1use serde::{Deserialize, Serialize};
4
5#[derive(Debug, thiserror::Error)]
6pub enum OpenAIError {
7 #[error("http error: {0}")]
9 Reqwest(#[from] reqwest::Error),
10 #[error("{0}")]
12 ApiError(ApiError),
13 #[error("failed to deserialize api response: error:{0} content:{1}")]
15 JSONDeserialize(serde_json::Error, String),
16 #[error("failed to save file: {0}")]
18 FileSaveError(String),
19 #[error("failed to read file: {0}")]
21 FileReadError(String),
22 #[error("stream failed: {0}")]
24 StreamError(StreamError),
25 #[error("invalid args: {0}")]
28 InvalidArgument(String),
29}
30
31#[derive(Debug, thiserror::Error)]
32pub enum StreamError {
33 #[error("{0}")]
35 ReqwestEventSource(#[from] reqwest_eventsource::Error),
36 #[error("Unknown event: {0:#?}")]
38 UnknownEvent(eventsource_stream::Event),
39}
40
41#[derive(Debug, Serialize, Deserialize, Clone)]
43pub struct ApiError {
44 pub message: String,
45 pub r#type: Option<String>,
46 pub param: Option<String>,
47 pub code: Option<String>,
48}
49
50impl std::fmt::Display for ApiError {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 let mut parts = Vec::new();
56
57 if let Some(r#type) = &self.r#type {
58 parts.push(format!("{}:", r#type));
59 }
60
61 parts.push(self.message.clone());
62
63 if let Some(param) = &self.param {
64 parts.push(format!("(param: {param})"));
65 }
66
67 if let Some(code) = &self.code {
68 parts.push(format!("(code: {code})"));
69 }
70
71 write!(f, "{}", parts.join(" "))
72 }
73}
74
75#[derive(Debug, Deserialize, Serialize)]
77pub struct WrappedError {
78 pub error: ApiError,
79}
80
81pub(crate) fn map_deserialization_error(e: serde_json::Error, bytes: &[u8]) -> OpenAIError {
82 let json_content = String::from_utf8_lossy(bytes);
83 tracing::error!("failed deserialization of: {}", json_content);
84
85 OpenAIError::JSONDeserialize(e, json_content.to_string())
86}