llm/
error.rs

1use std::fmt;
2
3/// Error types that can occur when interacting with LLM providers.
4#[derive(Debug)]
5pub enum LLMError {
6    /// HTTP request/response errors
7    HttpError(String),
8    /// Authentication and authorization errors
9    AuthError(String),
10    /// Invalid request parameters or format
11    InvalidRequest(String),
12    /// Errors returned by the LLM provider
13    ProviderError(String),
14    /// API response parsing or format error
15    ResponseFormatError {
16        message: String,
17        raw_response: String,
18    },
19    /// Generic error
20    Generic(String),
21    /// JSON serialization/deserialization errors
22    JsonError(String),
23    /// Tool configuration error
24    ToolConfigError(String),
25    /// Retry attempts exceeded
26    RetryExceeded { attempts: usize, last_error: String },
27}
28
29impl fmt::Display for LLMError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            LLMError::HttpError(e) => write!(f, "HTTP Error: {e}"),
33            LLMError::AuthError(e) => write!(f, "Auth Error: {e}"),
34            LLMError::InvalidRequest(e) => write!(f, "Invalid Request: {e}"),
35            LLMError::ProviderError(e) => write!(f, "Provider Error: {e}"),
36            LLMError::Generic(e) => write!(f, "Generic Error : {e}"),
37            LLMError::ResponseFormatError {
38                message,
39                raw_response,
40            } => {
41                write!(
42                    f,
43                    "Response Format Error: {message}. Raw response: {raw_response}"
44                )
45            }
46            LLMError::JsonError(e) => write!(f, "JSON Parse Error: {e}"),
47            LLMError::ToolConfigError(e) => write!(f, "Tool Configuration Error: {e}"),
48            LLMError::RetryExceeded {
49                attempts,
50                last_error,
51            } => write!(
52                f,
53                "Retry attempts exceeded after {attempts} tries: {last_error}"
54            ),
55        }
56    }
57}
58
59impl std::error::Error for LLMError {}
60
61/// Converts reqwest HTTP errors into LlmErrors
62impl From<reqwest::Error> for LLMError {
63    fn from(err: reqwest::Error) -> Self {
64        LLMError::HttpError(err.to_string())
65    }
66}
67
68impl From<serde_json::Error> for LLMError {
69    fn from(err: serde_json::Error) -> Self {
70        LLMError::JsonError(format!(
71            "{} at line {} column {}",
72            err,
73            err.line(),
74            err.column()
75        ))
76    }
77}