1use serde_json::Value;
2use std::{fmt, time::Duration};
3
4pub const OUT_OF_CREDITS: &str = "out of AI credits";
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Kind {
10 OutOfCredits,
12 SubscriptionRequired,
14 RateLimited,
16 Busy,
19 Pending,
22 Unauthorized,
24 PermissionDenied,
25 ContextLimit,
26 TimedOut,
27 Connection,
29 Transport,
30 Unavailable,
32 Rejected,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct Failure {
39 pub kind: Kind,
41 pub code: Option<String>,
43 pub detail: String,
45 pub retry_after: Option<Duration>,
47}
48
49impl Failure {
50 pub fn model_error(&self) -> agent_provider_config::protocol::ModelError {
52 use agent_provider_config::protocol::{ErrorKind, ModelError};
53 ModelError::new(match self.kind {
54 Kind::OutOfCredits | Kind::SubscriptionRequired => ErrorKind::CreditsExhausted,
55 Kind::Unauthorized => ErrorKind::Authentication,
56 Kind::PermissionDenied => ErrorKind::PermissionDenied,
57 Kind::ContextLimit => ErrorKind::ContextLimit,
58 Kind::TimedOut => ErrorKind::TimedOut,
59 Kind::Connection | Kind::Transport => ErrorKind::Transport,
60 Kind::RateLimited => ErrorKind::RateLimited,
61 Kind::Unavailable => ErrorKind::Unavailable,
62 Kind::Rejected => ErrorKind::InvalidRequest,
63 Kind::Busy | Kind::Pending => ErrorKind::Provider,
64 })
65 }
66
67 #[must_use]
69 pub const fn retryable(&self) -> bool {
70 matches!(
71 self.kind,
72 Kind::RateLimited | Kind::Busy | Kind::TimedOut | Kind::Connection
73 )
74 }
75
76 pub fn refused_unprocessed(&self, status: u16) -> bool {
82 matches!(status, 429 | 503 | 529) && matches!(self.kind, Kind::RateLimited | Kind::Busy)
83 }
84
85 #[must_use]
87 pub fn transport(timed_out: bool, connect: bool) -> Self {
88 Self {
89 kind: if timed_out {
90 Kind::TimedOut
91 } else if connect {
92 Kind::Connection
93 } else {
94 Kind::Transport
95 },
96 code: None,
97 detail: if timed_out {
98 "the model endpoint timed out".into()
99 } else {
100 "the model endpoint could not be reached".into()
101 },
102 retry_after: None,
103 }
104 }
105
106 #[must_use]
110 pub fn from_http(status: u16, body: &str, retry_after: Option<&str>) -> Self {
111 let parsed: Value = serde_json::from_str(body).unwrap_or(Value::Null);
112 let error = parsed.get("error").unwrap_or(&parsed);
113 let codes = [error.get("code"), error.get("type"), parsed.get("code")];
116 let code = codes
118 .iter()
119 .filter_map(|value| value.and_then(Value::as_str))
120 .find(|code| billing_code(code))
121 .or_else(|| {
122 codes
123 .iter()
124 .filter_map(|value| value.and_then(Value::as_str))
125 .find(|code| recognized_code(code))
126 })
127 .map(str::to_owned);
128 let message = error
131 .get("message")
132 .and_then(Value::as_str)
133 .unwrap_or_default()
134 .chars()
135 .take(4096)
136 .collect::<String>()
137 .to_ascii_lowercase();
138 let kind = match (status, code.as_deref()) {
139 _ if message.contains("credit balance is too low")
140 || message.contains("insufficient credits") =>
141 {
142 Kind::OutOfCredits
143 }
144 (_, Some("subscription_required")) => Kind::SubscriptionRequired,
145 (402, _) => Kind::OutOfCredits,
146 (_, Some(code)) if billing_code(code) => Kind::OutOfCredits,
147 (
148 _,
149 Some("context_length_exceeded" | "context_window_exceeded" | "prompt_too_long"),
150 )
151 | (413, _) => Kind::ContextLimit,
152 (_, Some("authentication_error" | "invalid_api_key")) => Kind::Unauthorized,
153 (_, Some("permission_error")) => Kind::PermissionDenied,
154 (_, Some("overloaded_error")) => Kind::Busy,
155 (409, Some("request_pending")) => Kind::Pending,
156 (_, Some("rate_limit_error" | "rate_limit_exceeded")) | (429, _) => Kind::RateLimited,
157 (401, _) => Kind::Unauthorized,
158 (403, _) => Kind::PermissionDenied,
159 (
160 503,
161 Some(
162 "service_disabled"
163 | "pricing_unavailable"
164 | "pricing_disabled"
165 | "provider_unavailable",
166 ),
167 ) => Kind::Unavailable,
168 _ if message.contains("prompt is too long")
169 || message.contains("maximum context length") =>
170 {
171 Kind::ContextLimit
172 }
173 (408 | 504, _) => Kind::TimedOut,
174 (500 | 502 | 503 | 529, _) => Kind::Busy,
175 _ => Kind::Rejected,
176 };
177 let detail = match kind {
178 Kind::OutOfCredits => format!(
179 "{OUT_OF_CREDITS}: this machine's included credit cannot cover the request. \
180 Add credit or connect your own API key in AI & credits"
181 ),
182 Kind::SubscriptionRequired => {
183 "metered AI needs an active subscription for this machine".into()
184 }
185 Kind::Pending => "the model call's outcome is pending reconciliation; \
186 it was not retried so it cannot be charged twice"
187 .into(),
188 _ => format!("the model endpoint answered HTTP {status}"),
189 };
190 Self {
191 kind,
192 code,
193 detail,
194 retry_after: retry_after
195 .and_then(|value| value.trim().parse::<f64>().ok())
196 .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok()),
197 }
198 }
199}
200
201fn recognized_code(code: &str) -> bool {
202 matches!(
203 code,
204 "request_pending"
205 | "service_disabled"
206 | "pricing_unavailable"
207 | "pricing_disabled"
208 | "provider_unavailable"
209 | "context_length_exceeded"
210 | "context_window_exceeded"
211 | "invalid_api_key"
212 | "prompt_too_long"
213 | "authentication_error"
214 | "permission_error"
215 | "rate_limit_error"
216 | "rate_limit_exceeded"
217 | "overloaded_error"
218 )
219}
220
221fn billing_code(code: &str) -> bool {
222 matches!(
223 code,
224 "subscription_required"
225 | "insufficient_credit"
226 | "insufficient_credits"
227 | "credit_exhausted"
228 | "credits_exhausted"
229 | "insufficient_quota"
230 | "credit_balance_too_low"
231 | "billing_hard_limit_reached"
232 )
233}
234
235impl fmt::Display for Failure {
236 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
237 match &self.code {
238 Some(code) if !self.detail.contains(code.as_str()) => {
239 write!(formatter, "{} ({code})", self.detail)
240 }
241 _ => formatter.write_str(&self.detail),
242 }
243 }
244}