1use std::fmt;
2use std::time::Duration;
3
4use thiserror::Error;
5
6use crate::retry::RetrySource;
7
8pub type Result<T> = std::result::Result<T, Error>;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub enum ErrorKind {
14 Authentication,
16 PermissionDenied,
18 NotFound,
20 InvalidRequest,
22 ContextLengthExceeded,
24 ContentFiltered,
26 RateLimited,
28 Overloaded,
30 Timeout,
32 Connection,
34 Cancelled,
36 Decode,
38 StreamProtocol,
40 ProviderInternal,
42 Unsupported,
44 Configuration,
46 Normalization,
48 Tool,
50 MaxSteps,
52 Unknown,
54}
55
56impl ErrorKind {
57 pub const fn as_str(self) -> &'static str {
60 match self {
61 Self::Authentication => "authentication",
62 Self::PermissionDenied => "permission_denied",
63 Self::NotFound => "not_found",
64 Self::InvalidRequest => "invalid_request",
65 Self::ContextLengthExceeded => "context_length_exceeded",
66 Self::ContentFiltered => "content_filtered",
67 Self::RateLimited => "rate_limited",
68 Self::Overloaded => "overloaded",
69 Self::Timeout => "timeout",
70 Self::Connection => "connection",
71 Self::Cancelled => "cancelled",
72 Self::Decode => "decode",
73 Self::StreamProtocol => "stream_protocol",
74 Self::ProviderInternal => "provider_internal",
75 Self::Unsupported => "unsupported",
76 Self::Configuration => "configuration",
77 Self::Normalization => "normalization",
78 Self::Tool => "tool",
79 Self::MaxSteps => "max_steps",
80 Self::Unknown => "unknown",
81 }
82 }
83
84 pub const fn is_retryable(self) -> bool {
86 matches!(
87 self,
88 Self::RateLimited
89 | Self::Overloaded
90 | Self::Timeout
91 | Self::Connection
92 | Self::ProviderInternal
93 )
94 }
95}
96
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
102pub struct ProviderErrorInfo {
103 pub code: Option<String>,
105 pub error_type: Option<String>,
107 pub status: Option<String>,
109 pub message_bytes: Option<usize>,
111 pub details_count: usize,
113}
114
115#[derive(Error)]
122pub enum Error {
123 #[error("missing API key: {0}")]
125 MissingApiKey(String),
126
127 #[error("HTTP request failed")]
129 Http(#[source] reqwest::Error),
130
131 #[error("request cancelled")]
133 Cancelled,
134
135 #[error("request timed out: {0}")]
137 Timeout(String),
138
139 #[error("invalid JSON: {0}")]
141 Json(#[from] serde_json::Error),
142
143 #[error("stream protocol error: {0}")]
145 StreamProtocol(String),
146
147 #[error("provider stream error (raw payload redacted)")]
149 ProviderStream(String),
150
151 #[error("response exceeded {resource} limit of {limit}")]
153 ResponseLimit {
154 resource: &'static str,
156 limit: usize,
158 },
159
160 #[error("{provider} returned HTTP {status}")]
161 Api {
162 provider: &'static str,
164 status: u16,
166 body: String,
169 retry_after: Option<Duration>,
171 retry_source: Option<RetrySource>,
173 request_id: Option<String>,
175 },
176
177 #[error("provider `{0}` is not configured with a model")]
179 MissingModel(&'static str),
180
181 #[error("invalid request: {0}")]
183 InvalidRequest(String),
184
185 #[error("unsupported operation: {0}")]
187 Unsupported(String),
188
189 #[error("tool `{0}` was requested by the model but is not registered")]
191 ToolNotFound(String),
192
193 #[error("tool `{tool}` failed: {message}")]
195 ToolFailed {
196 tool: String,
198 message: String,
200 },
201
202 #[error("agent exceeded max_steps={0}")]
204 MaxSteps(usize),
205
206 #[error("normalization error: {0}")]
208 Normalize(String),
209
210 #[error("invalid retry policy: {0}")]
212 InvalidRetryPolicy(String),
213
214 #[error("invalid HTTP header value: {0}")]
216 HeaderValue(#[from] reqwest::header::InvalidHeaderValue),
217
218 #[error("invalid HTTP header name: {0}")]
220 HeaderName(#[from] reqwest::header::InvalidHeaderName),
221
222 #[error("protected HTTP header cannot be overridden: {0}")]
224 ProtectedHeader(String),
225
226 #[error("HTTP header `{name}` must be ASCII for interoperability")]
228 NonAsciiHeaderValue {
229 name: String,
231 },
232
233 #[error("{protocol} extra body field `{field}` cannot override a canonical SDK field")]
235 ReservedExtraBodyField {
236 protocol: &'static str,
238 field: String,
240 },
241
242 #[error("{protocol} extra query parameter `{parameter}` is reserved by the endpoint")]
244 ReservedExtraQuery {
245 protocol: &'static str,
247 parameter: String,
249 },
250
251 #[error("invalid endpoint: {0}")]
253 InvalidEndpoint(String),
254
255 #[error("invalid provider profile: {0}")]
257 InvalidProfile(String),
258}
259
260struct RedactedBody(usize);
261
262impl From<reqwest::Error> for Error {
263 fn from(error: reqwest::Error) -> Self {
264 Self::Http(error.without_url())
265 }
266}
267
268impl fmt::Debug for RedactedBody {
269 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
270 write!(formatter, "<redacted {} bytes>", self.0)
271 }
272}
273
274impl fmt::Debug for Error {
275 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
276 match self {
277 Self::MissingApiKey(value) => {
278 formatter.debug_tuple("MissingApiKey").field(value).finish()
279 }
280 Self::Http(error) => formatter
281 .debug_struct("Http")
282 .field("kind", &classify_reqwest_error(error))
283 .finish(),
284 Self::Cancelled => formatter.write_str("Cancelled"),
285 Self::Timeout(message) => formatter.debug_tuple("Timeout").field(message).finish(),
286 Self::Json(error) => formatter.debug_tuple("Json").field(error).finish(),
287 Self::StreamProtocol(value) => formatter
288 .debug_tuple("StreamProtocol")
289 .field(value)
290 .finish(),
291 Self::ProviderStream(value) => formatter
292 .debug_tuple("ProviderStream")
293 .field(&RedactedBody(value.len()))
294 .finish(),
295 Self::ResponseLimit { resource, limit } => formatter
296 .debug_struct("ResponseLimit")
297 .field("resource", resource)
298 .field("limit", limit)
299 .finish(),
300 Self::Api {
301 provider,
302 status,
303 body,
304 retry_after,
305 retry_source,
306 request_id,
307 } => formatter
308 .debug_struct("Api")
309 .field("provider", provider)
310 .field("status", status)
311 .field("body", &RedactedBody(body.len()))
312 .field("retry_after", retry_after)
313 .field("retry_source", retry_source)
314 .field("request_id", request_id)
315 .finish(),
316 Self::MissingModel(value) => {
317 formatter.debug_tuple("MissingModel").field(value).finish()
318 }
319 Self::InvalidRequest(value) => formatter
320 .debug_tuple("InvalidRequest")
321 .field(value)
322 .finish(),
323 Self::Unsupported(value) => formatter.debug_tuple("Unsupported").field(value).finish(),
324 Self::ToolNotFound(value) => {
325 formatter.debug_tuple("ToolNotFound").field(value).finish()
326 }
327 Self::ToolFailed { tool, message } => formatter
328 .debug_struct("ToolFailed")
329 .field("tool", tool)
330 .field("message", message)
331 .finish(),
332 Self::MaxSteps(value) => formatter.debug_tuple("MaxSteps").field(value).finish(),
333 Self::Normalize(value) => formatter.debug_tuple("Normalize").field(value).finish(),
334 Self::InvalidRetryPolicy(value) => formatter
335 .debug_tuple("InvalidRetryPolicy")
336 .field(value)
337 .finish(),
338 Self::HeaderValue(error) => formatter.debug_tuple("HeaderValue").field(error).finish(),
339 Self::HeaderName(error) => formatter.debug_tuple("HeaderName").field(error).finish(),
340 Self::ProtectedHeader(value) => formatter
341 .debug_tuple("ProtectedHeader")
342 .field(value)
343 .finish(),
344 Self::NonAsciiHeaderValue { name } => formatter
345 .debug_struct("NonAsciiHeaderValue")
346 .field("name", name)
347 .finish(),
348 Self::ReservedExtraBodyField { protocol, field } => formatter
349 .debug_struct("ReservedExtraBodyField")
350 .field("protocol", protocol)
351 .field("field", field)
352 .finish(),
353 Self::ReservedExtraQuery {
354 protocol,
355 parameter,
356 } => formatter
357 .debug_struct("ReservedExtraQuery")
358 .field("protocol", protocol)
359 .field("parameter", parameter)
360 .finish(),
361 Self::InvalidEndpoint(value) => formatter
362 .debug_tuple("InvalidEndpoint")
363 .field(value)
364 .finish(),
365 Self::InvalidProfile(value) => formatter
366 .debug_tuple("InvalidProfile")
367 .field(value)
368 .finish(),
369 }
370 }
371}
372
373impl Error {
374 pub fn kind(&self) -> ErrorKind {
376 match self {
377 Self::MissingApiKey(_) => ErrorKind::Authentication,
378 Self::Http(error) => classify_reqwest_error(error),
379 Self::Cancelled => ErrorKind::Cancelled,
380 Self::Timeout(_) => ErrorKind::Timeout,
381 Self::Json(_) => ErrorKind::Decode,
382 Self::StreamProtocol(_) => ErrorKind::StreamProtocol,
383 Self::ProviderStream(value) => classify_provider_stream(value),
384 Self::ResponseLimit { .. } => ErrorKind::Decode,
385 Self::Api { status, body, .. } => classify_api_error(*status, body),
386 Self::MissingModel(_) => ErrorKind::Configuration,
387 Self::InvalidRequest(_) => ErrorKind::InvalidRequest,
388 Self::Unsupported(_) => ErrorKind::Unsupported,
389 Self::ToolNotFound(_) | Self::ToolFailed { .. } => ErrorKind::Tool,
390 Self::MaxSteps(_) => ErrorKind::MaxSteps,
391 Self::Normalize(_) => ErrorKind::Normalization,
392 Self::InvalidRetryPolicy(_)
393 | Self::HeaderValue(_)
394 | Self::HeaderName(_)
395 | Self::ProtectedHeader(_)
396 | Self::NonAsciiHeaderValue { .. }
397 | Self::ReservedExtraBodyField { .. }
398 | Self::ReservedExtraQuery { .. }
399 | Self::InvalidEndpoint(_)
400 | Self::InvalidProfile(_) => ErrorKind::Configuration,
401 }
402 }
403
404 pub fn status(&self) -> Option<u16> {
406 match self {
407 Self::Api { status, .. } => Some(*status),
408 _ => None,
409 }
410 }
411
412 pub fn provider(&self) -> Option<&str> {
414 match self {
415 Self::Api { provider, .. } => Some(provider),
416 _ => None,
417 }
418 }
419
420 pub fn request_id(&self) -> Option<&str> {
422 match self {
423 Self::Api { request_id, .. } => request_id.as_deref(),
424 _ => None,
425 }
426 }
427
428 pub fn raw_body(&self) -> Option<&str> {
435 match self {
436 Self::Api { body, .. } | Self::ProviderStream(body) => Some(body),
437 _ => None,
438 }
439 }
440
441 pub fn body_bytes(&self) -> Option<usize> {
443 match self {
444 Self::Api { body, .. } | Self::ProviderStream(body) => Some(body.len()),
445 _ => None,
446 }
447 }
448
449 pub fn provider_error(&self) -> Option<ProviderErrorInfo> {
454 match self {
455 Self::Api { body, .. } | Self::ProviderStream(body) => Some(parse_provider_error(body)),
456 _ => None,
457 }
458 }
459
460 pub fn retry_after(&self) -> Option<Duration> {
463 match self {
464 Self::Api { retry_after, .. } => *retry_after,
465 _ => None,
466 }
467 }
468
469 pub fn retry_source(&self) -> Option<RetrySource> {
471 match self {
472 Self::Api { retry_source, .. } => *retry_source,
473 _ => None,
474 }
475 }
476
477 pub fn is_retryable(&self) -> bool {
482 self.kind().is_retryable()
483 }
484}
485
486fn parse_provider_error(body: &str) -> ProviderErrorInfo {
487 let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
488 return ProviderErrorInfo {
489 message_bytes: Some(body.len()),
490 ..ProviderErrorInfo::default()
491 };
492 };
493
494 let top = value.as_object();
495 let nested = top
496 .and_then(|object| object.get("error"))
497 .and_then(serde_json::Value::as_object);
498 let error_value = top.and_then(|object| object.get("error"));
499
500 let code = nested
501 .and_then(|object| object.get("code"))
502 .or_else(|| top.and_then(|object| object.get("error_code")))
503 .or_else(|| top.and_then(|object| object.get("code")))
504 .and_then(provider_token);
505 let error_type = nested
506 .and_then(|object| object.get("type"))
507 .or_else(|| top.and_then(|object| object.get("type")))
508 .and_then(provider_token);
509 let status = nested
510 .and_then(|object| object.get("status"))
511 .or_else(|| top.and_then(|object| object.get("status")))
512 .and_then(provider_token);
513 let message = nested
514 .and_then(|object| object.get("message"))
515 .or_else(|| top.and_then(|object| object.get("message")))
516 .or_else(|| top.and_then(|object| object.get("error_msg")))
517 .or_else(|| top.and_then(|object| object.get("error_description")))
518 .or(error_value);
519 let message_bytes = match message {
520 Some(serde_json::Value::String(message)) => Some(message.len()),
521 _ => None,
522 };
523 let details_count = nested
524 .and_then(|object| object.get("details"))
525 .or_else(|| top.and_then(|object| object.get("details")))
526 .and_then(serde_json::Value::as_array)
527 .map_or(0, Vec::len);
528
529 ProviderErrorInfo {
530 code,
531 error_type,
532 status,
533 message_bytes,
534 details_count,
535 }
536}
537
538fn provider_token(value: &serde_json::Value) -> Option<String> {
539 let token = match value {
540 serde_json::Value::String(token) => token.trim(),
541 serde_json::Value::Number(token) => return Some(token.to_string()),
542 _ => return None,
543 };
544 if token.is_empty() || token.len() > 96 {
545 return None;
546 }
547 if !token.bytes().all(|byte| {
548 byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':' | b'/')
549 }) {
550 return None;
551 }
552 Some(token.to_string())
553}
554
555const MESSAGE_SCAN_LIMIT: usize = 8 * 1024;
557
558const CONTEXT_LENGTH_MARKERS: &[&str] = &[
563 "context_length_exceeded",
564 "context length",
565 "context window",
566 "context limit",
567 "context too long",
568 "prompt is too long",
569 "too many tokens",
570 "reduce the length",
571 "input length",
572];
573
574const CONTENT_FILTER_MARKERS: &[&str] = &[
576 "content_filter",
577 "content filter",
578 "content policy",
579 "content safety",
580 "safety policy",
581 "policy violation",
582 "filtered due to",
583];
584
585fn classify_api_error(status: u16, body: &str) -> ErrorKind {
586 let parsed = serde_json::from_str::<serde_json::Value>(body).ok();
587 if let Some(kind) = classify_error_tokens(parsed.as_ref()) {
590 return kind;
591 }
592 if matches!(classify_status(status), ErrorKind::InvalidRequest)
595 && let Some(kind) = classify_error_message(parsed.as_ref(), body)
596 {
597 return kind;
598 }
599 classify_status(status)
600}
601
602fn classify_provider_stream(payload: &str) -> ErrorKind {
606 let parsed = serde_json::from_str::<serde_json::Value>(payload).ok();
607 classify_error_tokens(parsed.as_ref())
608 .or_else(|| classify_error_message(parsed.as_ref(), payload))
609 .unwrap_or(ErrorKind::ProviderInternal)
610}
611
612fn classify_error_tokens(parsed: Option<&serde_json::Value>) -> Option<ErrorKind> {
613 let value = parsed?;
614 error_tokens(value)
615 .iter()
616 .find_map(|token| classify_token(token))
617}
618
619fn classify_error_message(parsed: Option<&serde_json::Value>, payload: &str) -> Option<ErrorKind> {
623 let text = match parsed {
624 Some(value) => provider_message_text(value)?,
625 None => scan_prefix(payload),
626 };
627 let lower = text.to_ascii_lowercase();
628 if CONTEXT_LENGTH_MARKERS
631 .iter()
632 .any(|marker| lower.contains(marker))
633 {
634 return Some(ErrorKind::ContextLengthExceeded);
635 }
636 if CONTENT_FILTER_MARKERS
637 .iter()
638 .any(|marker| lower.contains(marker))
639 {
640 return Some(ErrorKind::ContentFiltered);
641 }
642 None
643}
644
645fn classify_token(token: &str) -> Option<ErrorKind> {
646 match token.to_ascii_lowercase().as_str() {
647 "context_length_exceeded"
648 | "context_length_exceeded_error"
649 | "context_too_long"
650 | "prompt_too_long"
651 | "max_tokens_exceeded" => Some(ErrorKind::ContextLengthExceeded),
652 "content_filter"
653 | "content_filtered"
654 | "content_policy_violation"
655 | "safety"
656 | "safety_blocked" => Some(ErrorKind::ContentFiltered),
657 _ => None,
658 }
659}
660
661fn error_tokens(value: &serde_json::Value) -> Vec<String> {
667 const FIELDS: [&str; 4] = ["code", "error_code", "type", "status"];
668 let mut tokens = Vec::new();
669 for node in error_nodes(value) {
670 for field in FIELDS {
671 if let Some(token) = node.get(field).and_then(provider_token) {
672 tokens.push(token);
673 }
674 }
675 }
676 tokens
677}
678
679fn error_nodes(value: &serde_json::Value) -> Vec<&serde_json::Value> {
681 let mut nodes = Vec::new();
682 if value.is_object() || value.is_string() {
683 nodes.push(value);
684 }
685 for path in [
686 ["error"].as_slice(),
687 ["error", "error"].as_slice(),
688 ["response", "error"].as_slice(),
689 ] {
690 let mut node = value;
691 for key in path {
692 node = match node.get(key) {
693 Some(next) => next,
694 None => break,
695 };
696 }
697 if (node.is_object() || node.is_string()) && !nodes.contains(&node) {
698 nodes.push(node);
699 }
700 }
701 nodes
702}
703
704fn provider_message_text(value: &serde_json::Value) -> Option<String> {
710 for node in error_nodes(value) {
711 if let Some(text) = node.as_str() {
712 return Some(scan_prefix(text));
713 }
714 for field in [
715 "message",
716 "error_message",
717 "error_msg",
718 "error_description",
719 "reason",
720 ] {
721 if let Some(text) = node.get(field).and_then(serde_json::Value::as_str) {
722 return Some(scan_prefix(text));
723 }
724 }
725 }
726 None
727}
728
729fn scan_prefix(text: &str) -> String {
731 let mut end = text.len().min(MESSAGE_SCAN_LIMIT);
732 while !text.is_char_boundary(end) {
733 end -= 1;
734 }
735 text[..end].to_string()
736}
737
738fn classify_status(status: u16) -> ErrorKind {
739 match status {
740 401 => ErrorKind::Authentication,
741 403 => ErrorKind::PermissionDenied,
742 404 => ErrorKind::NotFound,
743 408 => ErrorKind::Timeout,
744 425 => ErrorKind::Overloaded,
745 429 => ErrorKind::RateLimited,
746 400 | 409 | 413 | 415 | 416 | 422 => ErrorKind::InvalidRequest,
747 500..=599 => ErrorKind::ProviderInternal,
748 _ => ErrorKind::Unknown,
749 }
750}
751
752fn classify_reqwest_error(error: &reqwest::Error) -> ErrorKind {
753 if error.is_timeout() {
754 ErrorKind::Timeout
755 } else if error.is_connect() || error.is_request() || error.is_body() {
756 ErrorKind::Connection
757 } else if error.is_decode() {
758 ErrorKind::Decode
759 } else if error.is_builder() {
760 ErrorKind::InvalidRequest
761 } else {
762 ErrorKind::Unknown
763 }
764}