use thiserror::Error;
#[derive(Debug, Error)]
pub enum LlmError {
#[error("model input rejected: {0}")]
InvalidInput(String),
#[error("llm request cancelled")]
Cancelled,
#[error("llm request deadline exceeded")]
DeadlineExceeded,
#[error("llm circuit breaker is open; failing fast")]
CircuitOpen,
#[error("llm transport error: {0}")]
Transport(#[from] reqwest::Error),
#[error("llm api error: status {status}, body: {body}")]
Api {
status: u16,
body: String,
},
#[error("llm response decode error: {0}")]
Decode(#[from] serde_json::Error),
#[error("llm stream protocol error: {0}")]
StreamProtocol(String),
#[error("llm stream utf-8 error: {0}")]
InvalidUtf8(#[from] std::string::FromUtf8Error),
}
impl LlmError {
pub fn is_context_overflow(&self) -> bool {
let Self::Api {
status: 400 | 413,
body,
} = self
else {
return false;
};
let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
return false;
};
value
.pointer("/error/code")
.and_then(serde_json::Value::as_str)
== Some("context_length_exceeded")
}
pub fn is_retryable(&self) -> bool {
match self {
LlmError::Transport(_) | LlmError::StreamProtocol(_) | LlmError::InvalidUtf8(_) => true,
LlmError::Api { status, .. } => {
*status == 408 || *status == 429 || (500..600).contains(status)
}
LlmError::InvalidInput(_)
| LlmError::CircuitOpen
| LlmError::Decode(_)
| LlmError::Cancelled
| LlmError::DeadlineExceeded => false,
}
}
}
pub type Result<T> = std::result::Result<T, LlmError>;