mutil-ai 0.7.0

A beginner-friendly, provider-neutral Rust AI SDK with a strict normalization layer.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
use std::fmt;
use std::time::Duration;

use thiserror::Error;

use crate::retry::RetrySource;

/// Convenience alias for results returned by this crate.
pub type Result<T> = std::result::Result<T, Error>;

/// Stable high-level classification for SDK errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorKind {
    /// No API key was configured, or the provider rejected it (HTTP 401).
    Authentication,
    /// The credentials are valid but lack access to the resource (HTTP 403).
    PermissionDenied,
    /// The requested resource does not exist (HTTP 404).
    NotFound,
    /// The provider rejected the request as malformed (HTTP 400-class).
    InvalidRequest,
    /// The prompt or output exceeds the model's context window.
    ContextLengthExceeded,
    /// The request or output was blocked by a safety or content policy.
    ContentFiltered,
    /// The provider is rate limiting the account (HTTP 429).
    RateLimited,
    /// The provider is temporarily overloaded (e.g. HTTP 425 or 529).
    Overloaded,
    /// The request timed out.
    Timeout,
    /// A network-level failure prevented reaching the provider.
    Connection,
    /// The request was cancelled by the caller.
    Cancelled,
    /// A response body could not be decoded.
    Decode,
    /// The provider emitted a malformed or unexpected stream event.
    StreamProtocol,
    /// The provider itself reported an internal error (HTTP 5xx).
    ProviderInternal,
    /// The selected provider does not support the requested operation.
    Unsupported,
    /// The SDK or provider client was misconfigured.
    Configuration,
    /// Request normalization failed.
    Normalization,
    /// A tool invocation failed or referenced an unknown tool.
    Tool,
    /// The agent loop exhausted its step budget.
    MaxSteps,
    /// The error could not be classified.
    Unknown,
}

impl ErrorKind {
    /// Stable snake_case identifier for this kind, suitable for logs and
    /// metrics.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Authentication => "authentication",
            Self::PermissionDenied => "permission_denied",
            Self::NotFound => "not_found",
            Self::InvalidRequest => "invalid_request",
            Self::ContextLengthExceeded => "context_length_exceeded",
            Self::ContentFiltered => "content_filtered",
            Self::RateLimited => "rate_limited",
            Self::Overloaded => "overloaded",
            Self::Timeout => "timeout",
            Self::Connection => "connection",
            Self::Cancelled => "cancelled",
            Self::Decode => "decode",
            Self::StreamProtocol => "stream_protocol",
            Self::ProviderInternal => "provider_internal",
            Self::Unsupported => "unsupported",
            Self::Configuration => "configuration",
            Self::Normalization => "normalization",
            Self::Tool => "tool",
            Self::MaxSteps => "max_steps",
            Self::Unknown => "unknown",
        }
    }

    /// Whether errors of this kind are normally safe to retry.
    pub const fn is_retryable(self) -> bool {
        matches!(
            self,
            Self::RateLimited
                | Self::Overloaded
                | Self::Timeout
                | Self::Connection
                | Self::ProviderInternal
        )
    }
}

/// Safe, provider-neutral summary of a structured error response.
///
/// The provider message itself is never retained. Only its byte length is
/// exposed, while code/type/status tokens are sanitized and length-limited.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProviderErrorInfo {
    /// Machine-readable provider code, such as `context_length_exceeded`.
    pub code: Option<String>,
    /// Provider error type/category, such as `invalid_request_error`.
    pub error_type: Option<String>,
    /// Provider status token, such as `INVALID_ARGUMENT`.
    pub status: Option<String>,
    /// Byte length of the provider's human-readable message, if present.
    pub message_bytes: Option<usize>,
    /// Number of structured `details` entries, when the provider returns them.
    pub details_count: usize,
}

/// The error type returned by this crate's public API.
///
/// Its [`Display`](std::fmt::Display) output is safe to log: the `Api`
/// variant never embeds the raw provider response body, and the `Debug`
/// output redacts it. Use [`Error::kind`] for stable classification and
/// [`Error::raw_body`] when you explicitly need the provider body.
#[derive(Error)]
pub enum Error {
    /// No API key was configured for the provider.
    #[error("missing API key: {0}")]
    MissingApiKey(String),

    /// The HTTP request to the provider failed at the transport level.
    #[error("HTTP request failed")]
    Http(#[source] reqwest::Error),

    /// The request was cancelled before it completed.
    #[error("request cancelled")]
    Cancelled,

    /// The request exceeded its configured timeout.
    #[error("request timed out: {0}")]
    Timeout(String),

    /// A response body was not valid JSON.
    #[error("invalid JSON: {0}")]
    Json(#[from] serde_json::Error),

    /// The provider's stream emitted a malformed or unexpected event.
    #[error("stream protocol error: {0}")]
    StreamProtocol(String),

    /// The provider reported an error inside a stream.
    #[error("provider stream error (raw payload redacted)")]
    ProviderStream(String),

    /// A decoded response exceeded its configured resource budget.
    #[error("response exceeded {resource} limit of {limit}")]
    ResponseLimit {
        /// Name of the bounded resource, without provider content.
        resource: &'static str,
        /// Configured maximum.
        limit: usize,
    },

    #[error("{provider} returned HTTP {status}")]
    Api {
        /// The provider identifier, such as `openai`.
        provider: &'static str,
        /// HTTP status code returned by the provider.
        status: u16,
        /// Raw response body. Excluded from log-safe output; see
        /// [`Error::raw_body`].
        body: String,
        /// Parsed server-directed retry delay, when present.
        retry_after: Option<Duration>,
        /// Which header produced `retry_after`.
        retry_source: Option<RetrySource>,
        /// Provider request id copied from response metadata, when present.
        request_id: Option<String>,
    },

    /// A provider was configured without a model.
    #[error("provider `{0}` is not configured with a model")]
    MissingModel(&'static str),

    /// The request could not be built as specified.
    #[error("invalid request: {0}")]
    InvalidRequest(String),

    /// The selected provider does not support the requested operation.
    #[error("unsupported operation: {0}")]
    Unsupported(String),

    /// The model requested a tool that was never registered.
    #[error("tool `{0}` was requested by the model but is not registered")]
    ToolNotFound(String),

    /// A registered tool returned an error while executing.
    #[error("tool `{tool}` failed: {message}")]
    ToolFailed {
        /// Name of the tool that failed.
        tool: String,
        /// Error message reported by the tool.
        message: String,
    },

    /// The agent loop exceeded its configured step budget.
    #[error("agent exceeded max_steps={0}")]
    MaxSteps(usize),

    /// A request could not be normalized for the target protocol.
    #[error("normalization error: {0}")]
    Normalize(String),

    /// A retry policy configuration was invalid.
    #[error("invalid retry policy: {0}")]
    InvalidRetryPolicy(String),

    /// An HTTP header value was invalid.
    #[error("invalid HTTP header value: {0}")]
    HeaderValue(#[from] reqwest::header::InvalidHeaderValue),

    /// An HTTP header name was invalid.
    #[error("invalid HTTP header name: {0}")]
    HeaderName(#[from] reqwest::header::InvalidHeaderName),

    /// An attempt was made to override a header the SDK manages itself.
    #[error("protected HTTP header cannot be overridden: {0}")]
    ProtectedHeader(String),

    /// A header value contained non-ASCII characters.
    #[error("HTTP header `{name}` must be ASCII for interoperability")]
    NonAsciiHeaderValue {
        /// Name of the offending header.
        name: String,
    },

    /// An extra body field collided with a canonical SDK field.
    #[error("{protocol} extra body field `{field}` cannot override a canonical SDK field")]
    ReservedExtraBodyField {
        /// The provider protocol that rejected the field.
        protocol: &'static str,
        /// The reserved field name.
        field: String,
    },

    /// An extra query parameter collided with an endpoint-reserved name.
    #[error("{protocol} extra query parameter `{parameter}` is reserved by the endpoint")]
    ReservedExtraQuery {
        /// The provider protocol that rejected the parameter.
        protocol: &'static str,
        /// The reserved parameter name.
        parameter: String,
    },

    /// A base URL or endpoint could not be parsed.
    #[error("invalid endpoint: {0}")]
    InvalidEndpoint(String),

    /// A provider profile configuration was invalid.
    #[error("invalid provider profile: {0}")]
    InvalidProfile(String),
}

struct RedactedBody(usize);

impl From<reqwest::Error> for Error {
    fn from(error: reqwest::Error) -> Self {
        Self::Http(error.without_url())
    }
}

impl fmt::Debug for RedactedBody {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "<redacted {} bytes>", self.0)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingApiKey(value) => {
                formatter.debug_tuple("MissingApiKey").field(value).finish()
            }
            Self::Http(error) => formatter
                .debug_struct("Http")
                .field("kind", &classify_reqwest_error(error))
                .finish(),
            Self::Cancelled => formatter.write_str("Cancelled"),
            Self::Timeout(message) => formatter.debug_tuple("Timeout").field(message).finish(),
            Self::Json(error) => formatter.debug_tuple("Json").field(error).finish(),
            Self::StreamProtocol(value) => formatter
                .debug_tuple("StreamProtocol")
                .field(value)
                .finish(),
            Self::ProviderStream(value) => formatter
                .debug_tuple("ProviderStream")
                .field(&RedactedBody(value.len()))
                .finish(),
            Self::ResponseLimit { resource, limit } => formatter
                .debug_struct("ResponseLimit")
                .field("resource", resource)
                .field("limit", limit)
                .finish(),
            Self::Api {
                provider,
                status,
                body,
                retry_after,
                retry_source,
                request_id,
            } => formatter
                .debug_struct("Api")
                .field("provider", provider)
                .field("status", status)
                .field("body", &RedactedBody(body.len()))
                .field("retry_after", retry_after)
                .field("retry_source", retry_source)
                .field("request_id", request_id)
                .finish(),
            Self::MissingModel(value) => {
                formatter.debug_tuple("MissingModel").field(value).finish()
            }
            Self::InvalidRequest(value) => formatter
                .debug_tuple("InvalidRequest")
                .field(value)
                .finish(),
            Self::Unsupported(value) => formatter.debug_tuple("Unsupported").field(value).finish(),
            Self::ToolNotFound(value) => {
                formatter.debug_tuple("ToolNotFound").field(value).finish()
            }
            Self::ToolFailed { tool, message } => formatter
                .debug_struct("ToolFailed")
                .field("tool", tool)
                .field("message", message)
                .finish(),
            Self::MaxSteps(value) => formatter.debug_tuple("MaxSteps").field(value).finish(),
            Self::Normalize(value) => formatter.debug_tuple("Normalize").field(value).finish(),
            Self::InvalidRetryPolicy(value) => formatter
                .debug_tuple("InvalidRetryPolicy")
                .field(value)
                .finish(),
            Self::HeaderValue(error) => formatter.debug_tuple("HeaderValue").field(error).finish(),
            Self::HeaderName(error) => formatter.debug_tuple("HeaderName").field(error).finish(),
            Self::ProtectedHeader(value) => formatter
                .debug_tuple("ProtectedHeader")
                .field(value)
                .finish(),
            Self::NonAsciiHeaderValue { name } => formatter
                .debug_struct("NonAsciiHeaderValue")
                .field("name", name)
                .finish(),
            Self::ReservedExtraBodyField { protocol, field } => formatter
                .debug_struct("ReservedExtraBodyField")
                .field("protocol", protocol)
                .field("field", field)
                .finish(),
            Self::ReservedExtraQuery {
                protocol,
                parameter,
            } => formatter
                .debug_struct("ReservedExtraQuery")
                .field("protocol", protocol)
                .field("parameter", parameter)
                .finish(),
            Self::InvalidEndpoint(value) => formatter
                .debug_tuple("InvalidEndpoint")
                .field(value)
                .finish(),
            Self::InvalidProfile(value) => formatter
                .debug_tuple("InvalidProfile")
                .field(value)
                .finish(),
        }
    }
}

impl Error {
    /// Classify this error into a stable, provider-neutral [`ErrorKind`].
    pub fn kind(&self) -> ErrorKind {
        match self {
            Self::MissingApiKey(_) => ErrorKind::Authentication,
            Self::Http(error) => classify_reqwest_error(error),
            Self::Cancelled => ErrorKind::Cancelled,
            Self::Timeout(_) => ErrorKind::Timeout,
            Self::Json(_) => ErrorKind::Decode,
            Self::StreamProtocol(_) => ErrorKind::StreamProtocol,
            Self::ProviderStream(value) => classify_provider_stream(value),
            Self::ResponseLimit { .. } => ErrorKind::Decode,
            Self::Api { status, body, .. } => classify_api_error(*status, body),
            Self::MissingModel(_) => ErrorKind::Configuration,
            Self::InvalidRequest(_) => ErrorKind::InvalidRequest,
            Self::Unsupported(_) => ErrorKind::Unsupported,
            Self::ToolNotFound(_) | Self::ToolFailed { .. } => ErrorKind::Tool,
            Self::MaxSteps(_) => ErrorKind::MaxSteps,
            Self::Normalize(_) => ErrorKind::Normalization,
            Self::InvalidRetryPolicy(_)
            | Self::HeaderValue(_)
            | Self::HeaderName(_)
            | Self::ProtectedHeader(_)
            | Self::NonAsciiHeaderValue { .. }
            | Self::ReservedExtraBodyField { .. }
            | Self::ReservedExtraQuery { .. }
            | Self::InvalidEndpoint(_)
            | Self::InvalidProfile(_) => ErrorKind::Configuration,
        }
    }

    /// Provider HTTP status, when this error came from an API response.
    pub fn status(&self) -> Option<u16> {
        match self {
            Self::Api { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// Provider name, when this error came from an API response.
    pub fn provider(&self) -> Option<&str> {
        match self {
            Self::Api { provider, .. } => Some(provider),
            _ => None,
        }
    }

    /// Provider request id, when the response exposed one.
    pub fn request_id(&self) -> Option<&str> {
        match self {
            Self::Api { request_id, .. } => request_id.as_deref(),
            _ => None,
        }
    }

    /// Return the raw provider error body.
    ///
    /// This is intentionally opt-in because provider errors can echo request
    /// content, account data, or other sensitive values. Prefer
    /// [`Self::body_bytes`], [`Self::status`], and [`Self::request_id`] for
    /// logs and metrics.
    pub fn raw_body(&self) -> Option<&str> {
        match self {
            Self::Api { body, .. } | Self::ProviderStream(body) => Some(body),
            _ => None,
        }
    }

    /// Decoded provider error-body size in bytes, without exposing the body.
    pub fn body_bytes(&self) -> Option<usize> {
        match self {
            Self::Api { body, .. } | Self::ProviderStream(body) => Some(body.len()),
            _ => None,
        }
    }

    /// Parse a safe, provider-neutral summary of a structured API error.
    ///
    /// Provider messages are never included. Codes, types, and status tokens
    /// are only returned when they are short, ASCII machine tokens.
    pub fn provider_error(&self) -> Option<ProviderErrorInfo> {
        match self {
            Self::Api { body, .. } | Self::ProviderStream(body) => Some(parse_provider_error(body)),
            _ => None,
        }
    }

    /// Return the parsed `Retry-After` duration, if this error came from an
    /// HTTP response that supplied one.
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::Api { retry_after, .. } => *retry_after,
            _ => None,
        }
    }

    /// Return which response header produced the retry delay.
    pub fn retry_source(&self) -> Option<RetrySource> {
        match self {
            Self::Api { retry_source, .. } => *retry_source,
            _ => None,
        }
    }

    /// Whether this error is normally safe to retry.
    ///
    /// This is a conservative classification. Callers should still avoid
    /// retrying non-idempotent operations unless they have an idempotency key.
    pub fn is_retryable(&self) -> bool {
        self.kind().is_retryable()
    }
}

fn parse_provider_error(body: &str) -> ProviderErrorInfo {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
        return ProviderErrorInfo {
            message_bytes: Some(body.len()),
            ..ProviderErrorInfo::default()
        };
    };

    let top = value.as_object();
    let nested = top
        .and_then(|object| object.get("error"))
        .and_then(serde_json::Value::as_object);
    let error_value = top.and_then(|object| object.get("error"));

    let code = nested
        .and_then(|object| object.get("code"))
        .or_else(|| top.and_then(|object| object.get("error_code")))
        .or_else(|| top.and_then(|object| object.get("code")))
        .and_then(provider_token);
    let error_type = nested
        .and_then(|object| object.get("type"))
        .or_else(|| top.and_then(|object| object.get("type")))
        .and_then(provider_token);
    let status = nested
        .and_then(|object| object.get("status"))
        .or_else(|| top.and_then(|object| object.get("status")))
        .and_then(provider_token);
    let message = nested
        .and_then(|object| object.get("message"))
        .or_else(|| top.and_then(|object| object.get("message")))
        .or_else(|| top.and_then(|object| object.get("error_msg")))
        .or_else(|| top.and_then(|object| object.get("error_description")))
        .or(error_value);
    let message_bytes = match message {
        Some(serde_json::Value::String(message)) => Some(message.len()),
        _ => None,
    };
    let details_count = nested
        .and_then(|object| object.get("details"))
        .or_else(|| top.and_then(|object| object.get("details")))
        .and_then(serde_json::Value::as_array)
        .map_or(0, Vec::len);

    ProviderErrorInfo {
        code,
        error_type,
        status,
        message_bytes,
        details_count,
    }
}

fn provider_token(value: &serde_json::Value) -> Option<String> {
    let token = match value {
        serde_json::Value::String(token) => token.trim(),
        serde_json::Value::Number(token) => return Some(token.to_string()),
        _ => return None,
    };
    if token.is_empty() || token.len() > 96 {
        return None;
    }
    if !token.bytes().all(|byte| {
        byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':' | b'/')
    }) {
        return None;
    }
    Some(token.to_string())
}

/// How much of a provider message is scanned before classification gives up.
const MESSAGE_SCAN_LIMIT: usize = 8 * 1024;

/// Message phrases that report a context-window rejection, collected across the
/// public error shapes of mainstream chat APIs. Deliberately narrow: each
/// phrase names the window or the token budget, so an unrelated malformed
/// request cannot be mistaken for an overflow.
const CONTEXT_LENGTH_MARKERS: &[&str] = &[
    "context_length_exceeded",
    "context length",
    "context window",
    "context limit",
    "context too long",
    "prompt is too long",
    "too many tokens",
    "reduce the length",
    "input length",
];

/// Message phrases that report a safety or content-policy rejection.
const CONTENT_FILTER_MARKERS: &[&str] = &[
    "content_filter",
    "content filter",
    "content policy",
    "content safety",
    "safety policy",
    "policy violation",
    "filtered due to",
];

fn classify_api_error(status: u16, body: &str) -> ErrorKind {
    let parsed = serde_json::from_str::<serde_json::Value>(body).ok();
    // The token layer is not status-gated (unchanged from before): a provider
    // that labels its failure always gets that label honoured.
    if let Some(kind) = classify_error_tokens(parsed.as_ref()) {
        return kind;
    }
    // Only the generic invalid-request band is refined from message text: a
    // rate limit or a 5xx keeps its own kind whatever the body says.
    if matches!(classify_status(status), ErrorKind::InvalidRequest)
        && let Some(kind) = classify_error_message(parsed.as_ref(), body)
    {
        return kind;
    }
    classify_status(status)
}

/// Classify an in-band provider stream error payload, which carries no HTTP
/// status to gate on. Falls back to the previous blanket
/// [`ErrorKind::ProviderInternal`] when the payload says nothing more.
fn classify_provider_stream(payload: &str) -> ErrorKind {
    let parsed = serde_json::from_str::<serde_json::Value>(payload).ok();
    classify_error_tokens(parsed.as_ref())
        .or_else(|| classify_error_message(parsed.as_ref(), payload))
        .unwrap_or(ErrorKind::ProviderInternal)
}

fn classify_error_tokens(parsed: Option<&serde_json::Value>) -> Option<ErrorKind> {
    let value = parsed?;
    error_tokens(value)
        .iter()
        .find_map(|token| classify_token(token))
}

/// Refine a kind from the provider's own wording. `parsed` is the payload once
/// it has been read as JSON; a body that is not JSON at all (a gateway error
/// page, a plain-text 400) is scanned as-is.
fn classify_error_message(parsed: Option<&serde_json::Value>, payload: &str) -> Option<ErrorKind> {
    let text = match parsed {
        Some(value) => provider_message_text(value)?,
        None => scan_prefix(payload),
    };
    let lower = text.to_ascii_lowercase();
    // Context first: a rejection can quote both conditions, and shrinking the
    // request is the actionable reading.
    if CONTEXT_LENGTH_MARKERS
        .iter()
        .any(|marker| lower.contains(marker))
    {
        return Some(ErrorKind::ContextLengthExceeded);
    }
    if CONTENT_FILTER_MARKERS
        .iter()
        .any(|marker| lower.contains(marker))
    {
        return Some(ErrorKind::ContentFiltered);
    }
    None
}

fn classify_token(token: &str) -> Option<ErrorKind> {
    match token.to_ascii_lowercase().as_str() {
        "context_length_exceeded"
        | "context_length_exceeded_error"
        | "context_too_long"
        | "prompt_too_long"
        | "max_tokens_exceeded" => Some(ErrorKind::ContextLengthExceeded),
        "content_filter"
        | "content_filtered"
        | "content_policy_violation"
        | "safety"
        | "safety_blocked" => Some(ErrorKind::ContentFiltered),
        _ => None,
    }
}

/// Machine-readable tokens from the error containers providers use: the top
/// level, an `error` member, and the Responses `response.error` member.
///
/// `error_code` is read alongside `code` because that is the field name several
/// compatible APIs use at the top level of an error body.
fn error_tokens(value: &serde_json::Value) -> Vec<String> {
    const FIELDS: [&str; 4] = ["code", "error_code", "type", "status"];
    let mut tokens = Vec::new();
    for node in error_nodes(value) {
        for field in FIELDS {
            if let Some(token) = node.get(field).and_then(provider_token) {
                tokens.push(token);
            }
        }
    }
    tokens
}

/// Error-bearing objects in one payload, outermost first.
fn error_nodes(value: &serde_json::Value) -> Vec<&serde_json::Value> {
    let mut nodes = Vec::new();
    if value.is_object() || value.is_string() {
        nodes.push(value);
    }
    for path in [
        ["error"].as_slice(),
        ["error", "error"].as_slice(),
        ["response", "error"].as_slice(),
    ] {
        let mut node = value;
        for key in path {
            node = match node.get(key) {
                Some(next) => next,
                None => break,
            };
        }
        if (node.is_object() || node.is_string()) && !nodes.contains(&node) {
            nodes.push(node);
        }
    }
    nodes
}

/// The human-readable part of an error payload, capped so a large body cannot
/// make classification expensive.
///
/// Only message-bearing fields are read; request content echoed under other
/// keys cannot influence the classification.
fn provider_message_text(value: &serde_json::Value) -> Option<String> {
    for node in error_nodes(value) {
        if let Some(text) = node.as_str() {
            return Some(scan_prefix(text));
        }
        for field in [
            "message",
            "error_message",
            "error_msg",
            "error_description",
            "reason",
        ] {
            if let Some(text) = node.get(field).and_then(serde_json::Value::as_str) {
                return Some(scan_prefix(text));
            }
        }
    }
    None
}

/// First [`MESSAGE_SCAN_LIMIT`] bytes of `text`, truncated to a char boundary.
fn scan_prefix(text: &str) -> String {
    let mut end = text.len().min(MESSAGE_SCAN_LIMIT);
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    text[..end].to_string()
}

fn classify_status(status: u16) -> ErrorKind {
    match status {
        401 => ErrorKind::Authentication,
        403 => ErrorKind::PermissionDenied,
        404 => ErrorKind::NotFound,
        408 => ErrorKind::Timeout,
        425 => ErrorKind::Overloaded,
        429 => ErrorKind::RateLimited,
        400 | 409 | 413 | 415 | 416 | 422 => ErrorKind::InvalidRequest,
        500..=599 => ErrorKind::ProviderInternal,
        _ => ErrorKind::Unknown,
    }
}

fn classify_reqwest_error(error: &reqwest::Error) -> ErrorKind {
    if error.is_timeout() {
        ErrorKind::Timeout
    } else if error.is_connect() || error.is_request() || error.is_body() {
        ErrorKind::Connection
    } else if error.is_decode() {
        ErrorKind::Decode
    } else if error.is_builder() {
        ErrorKind::InvalidRequest
    } else {
        ErrorKind::Unknown
    }
}