use std::fmt;
use std::time::Duration;
use reqwest::StatusCode;
#[derive(Debug, Clone)]
pub struct LlmError {
pub kind: LlmErrorKind,
pub detail: ProviderError,
hint: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LlmErrorKind {
RateLimited,
Overloaded,
ServerError,
Timeout,
Transport,
UnexpectedEof,
MalformedResponse,
Auth,
OAuth,
Forbidden,
Quota,
ContextOverflow,
InvalidRequest,
ContentPolicy,
Unknown,
}
#[derive(Debug, Default, Clone)]
pub struct ProviderError {
pub status: Option<StatusCode>,
pub provider_code: Option<String>,
pub message: String,
pub retry_after: Option<Duration>,
}
impl LlmError {
pub(crate) fn new(kind: LlmErrorKind, detail: ProviderError) -> Self {
Self { kind, detail, hint: None }
}
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
pub fn hint(&self) -> Option<&str> {
self.hint.as_deref()
}
pub fn message(kind: LlmErrorKind, message: impl Into<String>) -> Self {
Self::new(kind, ProviderError { message: message.into(), ..Default::default() })
}
pub fn transport(message: impl Into<String>) -> Self {
Self::message(LlmErrorKind::Transport, message)
}
pub(crate) fn malformed_response(message: impl Into<String>) -> Self {
Self::message(LlmErrorKind::MalformedResponse, message)
}
pub fn unexpected_eof(message: impl Into<String>) -> Self {
Self::message(LlmErrorKind::UnexpectedEof, message)
}
pub(crate) fn sse_transport(err: reqwest::Error) -> Self {
let message = match error_source_chain(&err) {
Some(chain) => format!("SSE reqwest error: {err}; source: {chain}"),
None => format!("SSE reqwest error: {err}"),
};
Self::unexpected_eof(message)
}
pub(crate) fn request_conversion(err: anyhow::Error) -> Self {
Self::message(LlmErrorKind::InvalidRequest, format!("{err:#}"))
}
pub(crate) fn response_decode(err: anyhow::Error) -> Self {
match err.downcast::<Self>() {
Ok(err) => err,
Err(err) => Self::malformed_response(format!("{err:#}")),
}
}
pub fn http(
kind: LlmErrorKind,
status: StatusCode,
code: Option<String>,
message: String,
) -> Self {
Self::new(
kind,
ProviderError {
status: Some(status),
provider_code: code,
message,
..Default::default()
},
)
}
pub fn status(&self) -> Option<StatusCode> {
self.detail.status
}
pub(crate) fn is_tool_choice_rejection(&self) -> bool {
self.kind == LlmErrorKind::InvalidRequest
&& (self.detail.status.is_some() || self.detail.provider_code.is_some())
&& self.detail.message.contains("tool_choice")
}
pub fn is_reasoning_rejection(&self) -> bool {
self.kind == LlmErrorKind::InvalidRequest
&& self.detail.message.contains("bound to a different conversation")
}
pub fn retry_delay(&self, attempt: u32) -> Option<Duration> {
const MIN_RETRY_DELAY: Duration = Duration::from_secs(1);
const MAX_RETRY_DELAY: Duration = Duration::from_secs(60);
if !self.kind.is_transient()
|| self.detail.retry_after.is_some_and(|wait| wait > MAX_RETRY_DELAY)
{
return None;
}
let backoff = Duration::from_secs(1u64 << attempt.saturating_sub(1).min(6));
Some(self.detail.retry_after.unwrap_or(backoff).clamp(MIN_RETRY_DELAY, MAX_RETRY_DELAY))
}
}
impl LlmErrorKind {
pub fn as_str(self) -> &'static str {
use LlmErrorKind::*;
match self {
RateLimited => "rate_limited",
Overloaded => "overloaded",
ServerError => "server_error",
Timeout => "timeout",
Transport => "transport",
UnexpectedEof => "unexpected_eof",
MalformedResponse => "malformed_response",
Auth => "auth",
OAuth => "oauth",
Forbidden => "forbidden",
Quota => "quota",
ContextOverflow => "context_overflow",
InvalidRequest => "invalid_request",
ContentPolicy => "content_policy",
Unknown => "unknown",
}
}
fn is_transient(self) -> bool {
use LlmErrorKind::*;
matches!(self, RateLimited | Overloaded | ServerError | Timeout | Transport | UnexpectedEof)
}
}
impl fmt::Display for LlmErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use LlmErrorKind::*;
let s = match self {
RateLimited => "rate limited",
Overloaded => "provider overloaded",
ServerError => "provider server error",
Timeout => "request timed out",
Transport => "transport error",
UnexpectedEof => "stream ended unexpectedly",
MalformedResponse => "malformed provider response",
Auth => "authentication error",
OAuth => "OAuth sign-in required",
Forbidden => "request forbidden",
Quota => "quota exceeded",
ContextOverflow => "context window exceeded",
InvalidRequest => "invalid request",
ContentPolicy => "content policy violation",
Unknown => "llm error",
};
f.write_str(s)
}
}
impl fmt::Display for LlmError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.detail.message.is_empty() {
write!(f, "{}", self.kind)
} else {
write!(f, "{}: {}", self.kind, self.detail.message)
}
}
}
impl std::error::Error for LlmError {}
impl From<serde_json::Error> for LlmError {
fn from(err: serde_json::Error) -> Self {
LlmError::malformed_response(format!("failed to decode response body: {err}"))
}
}
fn error_source_chain(err: &(dyn std::error::Error + 'static)) -> Option<String> {
let mut sources = Vec::new();
let mut current = err.source();
while let Some(source) = current {
sources.push(source.to_string());
current = source.source();
}
(!sources.is_empty()).then(|| sources.join(" <- "))
}
pub(crate) fn http_status_to_kind(status: StatusCode) -> LlmErrorKind {
match status.as_u16() {
401 => LlmErrorKind::Auth,
403 => LlmErrorKind::Forbidden,
402 => LlmErrorKind::Quota,
408 | 504 => LlmErrorKind::Timeout,
429 => LlmErrorKind::RateLimited,
503 | 529 => LlmErrorKind::Overloaded,
s if (500..600).contains(&s) => LlmErrorKind::ServerError,
s if (400..500).contains(&s) => LlmErrorKind::InvalidRequest,
_ => LlmErrorKind::Unknown,
}
}
fn is_context_overflow_message(message: &str) -> bool {
let message = message.to_ascii_lowercase();
message.contains("context_length_exceeded")
|| message.contains("maximum context")
|| message.contains("context window exceeded")
|| message.contains("input exceeds the context window")
|| message.contains("request exceeds the context window")
|| message.contains("context length exceeded")
|| message.contains("exceeds the available context size")
|| message.contains("exceeds the maximum allowed input length of")
|| message.contains("prompt is too long")
|| message.contains("request too large")
}
pub(crate) fn openai_error_kind(
code: Option<&str>,
message: Option<&str>,
fallback: LlmErrorKind,
wire_codes: fn(&str) -> Option<LlmErrorKind>,
) -> LlmErrorKind {
let context_overflow = message.is_some_and(is_context_overflow_message);
let from_code = code.and_then(|code| {
let code = code.to_ascii_lowercase();
wire_codes(&code).or_else(|| openai_kind_from_code(&code))
});
match from_code {
Some(LlmErrorKind::InvalidRequest) if context_overflow => LlmErrorKind::ContextOverflow,
Some(kind) => kind,
None if context_overflow => LlmErrorKind::ContextOverflow,
None => fallback,
}
}
fn openai_kind_from_code(code: &str) -> Option<LlmErrorKind> {
match code {
"context_length_exceeded"
| "context_window_exceeded"
| "prompt_too_long"
| "request_too_large"
| "string_above_max_length" => Some(LlmErrorKind::ContextOverflow),
"insufficient_quota"
| "exceeded_current_quota"
| "usage_limit_reached"
| "credit_balance_exhausted" => Some(LlmErrorKind::Quota),
"freeusagelimiterror" | "gousagelimiterror" | "blackusagelimiterror" => {
Some(LlmErrorKind::Quota)
}
"content_filter" | "content_policy_violation" => Some(LlmErrorKind::ContentPolicy),
"overloaded_error" => Some(LlmErrorKind::Overloaded),
"server_error" => Some(LlmErrorKind::ServerError),
"rate_limit_exceeded" | "rate_limit_error" => Some(LlmErrorKind::RateLimited),
"authentication_error" | "invalid_api_key" | "permission_denied" | "unauthenticated" => {
Some(LlmErrorKind::Auth)
}
"not_found" | "model_not_found" | "invalid_request_error" => {
Some(LlmErrorKind::InvalidRequest)
}
_ => None,
}
}
pub(crate) fn parse_error_body(
body: &str,
code_fields: &[&str],
) -> (Option<String>, Option<String>) {
match serde_json::from_str::<serde_json::Value>(body) {
Ok(value) => error_details(&value, code_fields),
Err(_) => (None, None),
}
}
pub(crate) fn error_details(
value: &serde_json::Value,
code_fields: &[&str],
) -> (Option<String>, Option<String>) {
let error = value.get("error");
let code = code_fields
.iter()
.find_map(|field| error.and_then(|e| e.get(field)).and_then(|v| v.as_str()))
.map(str::to_string);
let message = error.and_then(|e| e.get("message")).and_then(|v| v.as_str()).map(str::to_string);
(code, message)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn response_decode_preserves_classified_llm_error() {
let original = LlmError::new(
LlmErrorKind::Unknown,
ProviderError {
provider_code: Some("invalid_function_call_arguments".to_string()),
message: "malformed function call".to_string(),
..Default::default()
},
);
let err = LlmError::response_decode(original.clone().into());
assert_eq!(err.kind, original.kind);
assert_eq!(err.detail.provider_code, original.detail.provider_code);
assert_eq!(err.detail.message, original.detail.message);
}
#[test]
fn sse_byte_stream_death_maps_to_unexpected_eof() {
let reqwest_err = reqwest::Client::new().get("http://[invalid").build().unwrap_err();
let cause = std::error::Error::source(&reqwest_err).unwrap().to_string();
let err = LlmError::sse_transport(reqwest_err);
assert!(err.detail.message.contains(&format!("source: {cause}")));
assert_eq!(err.kind, LlmErrorKind::UnexpectedEof);
assert!(err.kind.is_transient(), "mid-stream death must be reconnect-eligible");
}
#[test]
fn retry_delay_backs_off_exponentially_with_clamp() {
let err = LlmError::transport("connection reset by peer");
assert_eq!(err.retry_delay(1), Some(Duration::from_secs(1)));
assert_eq!(err.retry_delay(2), Some(Duration::from_secs(2)));
assert_eq!(err.retry_delay(4), Some(Duration::from_secs(8)));
assert_eq!(err.retry_delay(20), Some(Duration::from_secs(60)), "backoff is clamped");
}
#[test]
fn retry_delay_honors_retry_after_within_clamp() {
let mut err = LlmError::http(
LlmErrorKind::RateLimited,
StatusCode::TOO_MANY_REQUESTS,
None,
"slow down".to_string(),
);
err.detail.retry_after = Some(Duration::from_secs(30));
assert_eq!(err.retry_delay(1), Some(Duration::from_secs(30)));
err.detail.retry_after = Some(Duration::from_secs(60));
assert_eq!(err.retry_delay(1), Some(Duration::from_secs(60)), "the cap itself is honored");
err.detail.retry_after = Some(Duration::ZERO);
assert_eq!(err.retry_delay(1), Some(Duration::from_secs(1)), "instant retry cannot spin");
}
#[test]
fn retry_delay_refuses_retry_after_beyond_cap() {
let mut err = LlmError::http(
LlmErrorKind::RateLimited,
StatusCode::TOO_MANY_REQUESTS,
None,
"slow down".to_string(),
);
err.detail.retry_after = Some(Duration::from_secs(61));
assert_eq!(err.retry_delay(1), None, "a Retry-After beyond the cap is not truncated");
err.detail.retry_after = Some(Duration::from_secs(3600));
assert_eq!(err.retry_delay(1), None);
assert_eq!(err.detail.retry_after, Some(Duration::from_secs(3600)), "the reset survives");
}
#[test]
fn retry_delay_is_none_for_terminal_kinds() {
assert_eq!(LlmError::malformed_response("bad json").retry_delay(1), None);
assert_eq!(LlmError::message(LlmErrorKind::Auth, "bad key").retry_delay(1), None);
}
}