use serde_json::Value;
use std::{fmt, time::Duration};
pub const OUT_OF_CREDITS: &str = "out of AI credits";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
OutOfCredits,
SubscriptionRequired,
RateLimited,
Busy,
Pending,
Unauthorized,
PermissionDenied,
ContextLimit,
TimedOut,
Connection,
Transport,
Unavailable,
Rejected,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Failure {
pub kind: Kind,
pub code: Option<String>,
pub detail: String,
pub retry_after: Option<Duration>,
}
impl Failure {
pub fn model_error(&self) -> agent_provider_config::protocol::ModelError {
use agent_provider_config::protocol::{ErrorKind, ModelError};
ModelError::new(match self.kind {
Kind::OutOfCredits | Kind::SubscriptionRequired => ErrorKind::CreditsExhausted,
Kind::Unauthorized => ErrorKind::Authentication,
Kind::PermissionDenied => ErrorKind::PermissionDenied,
Kind::ContextLimit => ErrorKind::ContextLimit,
Kind::TimedOut => ErrorKind::TimedOut,
Kind::Connection | Kind::Transport => ErrorKind::Transport,
Kind::RateLimited => ErrorKind::RateLimited,
Kind::Unavailable => ErrorKind::Unavailable,
Kind::Rejected => ErrorKind::InvalidRequest,
Kind::Busy | Kind::Pending => ErrorKind::Provider,
})
}
#[must_use]
pub const fn retryable(&self) -> bool {
matches!(
self.kind,
Kind::RateLimited | Kind::Busy | Kind::TimedOut | Kind::Connection
)
}
pub fn refused_unprocessed(&self, status: u16) -> bool {
matches!(status, 429 | 503 | 529) && matches!(self.kind, Kind::RateLimited | Kind::Busy)
}
#[must_use]
pub fn transport(timed_out: bool, connect: bool) -> Self {
Self {
kind: if timed_out {
Kind::TimedOut
} else if connect {
Kind::Connection
} else {
Kind::Transport
},
code: None,
detail: if timed_out {
"the model endpoint timed out".into()
} else {
"the model endpoint could not be reached".into()
},
retry_after: None,
}
}
#[must_use]
pub fn from_http(status: u16, body: &str, retry_after: Option<&str>) -> Self {
let parsed: Value = serde_json::from_str(body).unwrap_or(Value::Null);
let error = parsed.get("error").unwrap_or(&parsed);
let codes = [error.get("code"), error.get("type"), parsed.get("code")];
let code = codes
.iter()
.filter_map(|value| value.and_then(Value::as_str))
.find(|code| billing_code(code))
.or_else(|| {
codes
.iter()
.filter_map(|value| value.and_then(Value::as_str))
.find(|code| recognized_code(code))
})
.map(str::to_owned);
let message = error
.get("message")
.and_then(Value::as_str)
.unwrap_or_default()
.chars()
.take(4096)
.collect::<String>()
.to_ascii_lowercase();
let kind = match (status, code.as_deref()) {
_ if message.contains("credit balance is too low")
|| message.contains("insufficient credits") =>
{
Kind::OutOfCredits
}
(_, Some("subscription_required")) => Kind::SubscriptionRequired,
(402, _) => Kind::OutOfCredits,
(_, Some(code)) if billing_code(code) => Kind::OutOfCredits,
(
_,
Some("context_length_exceeded" | "context_window_exceeded" | "prompt_too_long"),
)
| (413, _) => Kind::ContextLimit,
(_, Some("authentication_error" | "invalid_api_key")) => Kind::Unauthorized,
(_, Some("permission_error")) => Kind::PermissionDenied,
(_, Some("overloaded_error")) => Kind::Busy,
(409, Some("request_pending")) => Kind::Pending,
(_, Some("rate_limit_error" | "rate_limit_exceeded")) | (429, _) => Kind::RateLimited,
(401, _) => Kind::Unauthorized,
(403, _) => Kind::PermissionDenied,
(
503,
Some(
"service_disabled"
| "pricing_unavailable"
| "pricing_disabled"
| "provider_unavailable",
),
) => Kind::Unavailable,
_ if message.contains("prompt is too long")
|| message.contains("maximum context length") =>
{
Kind::ContextLimit
}
(408 | 504, _) => Kind::TimedOut,
(500 | 502 | 503 | 529, _) => Kind::Busy,
_ => Kind::Rejected,
};
let detail = match kind {
Kind::OutOfCredits => format!(
"{OUT_OF_CREDITS}: this machine's included credit cannot cover the request. \
Add credit or connect your own API key in AI & credits"
),
Kind::SubscriptionRequired => {
"metered AI needs an active subscription for this machine".into()
}
Kind::Pending => "the model call's outcome is pending reconciliation; \
it was not retried so it cannot be charged twice"
.into(),
_ => format!("the model endpoint answered HTTP {status}"),
};
Self {
kind,
code,
detail,
retry_after: retry_after
.and_then(|value| value.trim().parse::<f64>().ok())
.and_then(|seconds| Duration::try_from_secs_f64(seconds).ok()),
}
}
}
fn recognized_code(code: &str) -> bool {
matches!(
code,
"request_pending"
| "service_disabled"
| "pricing_unavailable"
| "pricing_disabled"
| "provider_unavailable"
| "context_length_exceeded"
| "context_window_exceeded"
| "invalid_api_key"
| "prompt_too_long"
| "authentication_error"
| "permission_error"
| "rate_limit_error"
| "rate_limit_exceeded"
| "overloaded_error"
)
}
fn billing_code(code: &str) -> bool {
matches!(
code,
"subscription_required"
| "insufficient_credit"
| "insufficient_credits"
| "credit_exhausted"
| "credits_exhausted"
| "insufficient_quota"
| "credit_balance_too_low"
| "billing_hard_limit_reached"
)
}
impl fmt::Display for Failure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.code {
Some(code) if !self.detail.contains(code.as_str()) => {
write!(formatter, "{} ({code})", self.detail)
}
_ => formatter.write_str(&self.detail),
}
}
}