ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Provider-agnostic, typed LLM errors.
//!
//! Provider modules classify failures into an [`LlmError`] at their wire
//! boundary, so downstream code branches on a small taxonomy instead of
//! re-parsing response bodies.
//!
//! [`LlmErrorKind`] says what the failure is (messaging, telemetry);
//! [`LlmError::retry_delay`] decides whether and when to retry. Richer
//! dispositions (e.g. shortening the conversation and retrying on context
//! overflow) are the caller's.

use std::fmt;
use std::time::Duration;

use reqwest::StatusCode;

/// A classified LLM call failure: the semantic [`LlmErrorKind`] plus the raw
/// [`ProviderError`] detail.
#[derive(Debug, Clone)]
pub struct LlmError {
    /// What the failure calls for, the same for every provider.
    pub kind: LlmErrorKind,
    /// What the provider said: status, code and message.
    pub detail: ProviderError,
    /// A next step for the user, set by whoever raised the failure and knows
    /// its remedy.
    hint: Option<String>,
}

/// What a failure is, in provider-agnostic terms. Variants are grouped by
/// remedy, not by HTTP status; each provider module maps its own status, code
/// and message onto them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LlmErrorKind {
    /// Throttled per unit time (HTTP 429 `rate_limit`). Transient.
    RateLimited,
    /// Provider at capacity (HTTP 503/529, `overloaded_error`). Transient.
    Overloaded,
    /// Provider-side fault (HTTP 500/502). Transient.
    ServerError,
    /// A deadline passed: the provider's or a gateway's (HTTP 408/504), or the
    /// client's own on a call that got no response in time. Transient.
    Timeout,
    /// Network-level failure talking to the provider: connect, TLS, request
    /// send, or the connection cut while reading a buffered response.
    /// Transient. A stream that opened and then died is
    /// [`Self::UnexpectedEof`]; a payload that arrived intact but could not
    /// be decoded is [`Self::MalformedResponse`].
    Transport,
    /// A stream opened but died mid-flight (idle timeout, connection cut, or
    /// premature close).
    UnexpectedEof,
    /// The provider's payload arrived but could not be decoded: undecodable
    /// JSON, bytes that were not valid SSE, an unexpected frame, or a response
    /// missing required fields. Deterministic for a given response, so never
    /// retried automatically.
    MalformedResponse,
    /// Bad or expired credential (HTTP 401, or a provider-specific auth code).
    Auth,
    /// The provider's OAuth sign-in is missing, expired, or revoked.
    OAuth,
    /// The provider understood the request but refused it without a more
    /// specific machine-readable reason (HTTP 403).
    Forbidden,
    /// Out of credits / billing / hard quota (`insufficient_quota`, HTTP 402).
    Quota,
    /// Input exceeded the model's context window.
    ContextOverflow,
    /// Malformed request: rejected by the provider (bad params, unknown
    /// model, ...) or unconvertible to the provider's wire format.
    InvalidRequest,
    /// Blocked by a safety / moderation policy.
    ContentPolicy,
    /// Unclassified — surfaced verbatim.
    Unknown,
}

/// The raw signal behind an [`LlmError`], preserved for display and telemetry.
#[derive(Debug, Default, Clone)]
pub struct ProviderError {
    /// HTTP status, when the failure came from a response. `None` for pure
    /// transport / stream errors.
    pub status: Option<StatusCode>,
    /// Provider error identifier (`error.type` / `error.code` / `error.status`).
    pub provider_code: Option<String>,
    /// Human-readable message extracted from the body, or a transport message.
    /// Callers show it to the user verbatim, so keep it short; wire-level
    /// detail (Debug dumps, raw event payloads) goes to a `tracing` log at
    /// the classification boundary instead.
    pub message: String,
    /// Server-mandated wait before retrying (the `Retry-After` header), when
    /// the provider sent one. Carried out so a caller-level retry can honor
    /// waits longer than the inline retry layer's delay cap.
    pub retry_after: Option<Duration>,
}

impl LlmError {
    pub(crate) fn new(kind: LlmErrorKind, detail: ProviderError) -> Self {
        Self { kind, detail, hint: None }
    }

    /// Attach a next step for the user.
    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()
    }

    /// A failure with only a message and no HTTP status (transport, stream, or
    /// internal). `kind` is the caller's classification.
    pub fn message(kind: LlmErrorKind, message: impl Into<String>) -> Self {
        Self::new(kind, ProviderError { message: message.into(), ..Default::default() })
    }

    /// Network-level transport failure (connect, TLS, send, connection cut).
    pub fn transport(message: impl Into<String>) -> Self {
        Self::message(LlmErrorKind::Transport, message)
    }

    /// A payload that arrived but could not be decoded into the expected shape.
    pub(crate) fn malformed_response(message: impl Into<String>) -> Self {
        Self::message(LlmErrorKind::MalformedResponse, message)
    }

    /// A stream that opened but did not complete (idle timeout, connection
    /// cut, or premature end).
    pub fn unexpected_eof(message: impl Into<String>) -> Self {
        Self::message(LlmErrorKind::UnexpectedEof, message)
    }

    /// A failed SSE body read is retryable. Preserve the source chain because
    /// reqwest's `Display` hides the underlying IO cause.
    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)
    }

    /// A request that could not be converted into the provider's wire shape;
    /// the provider never saw it.
    pub(crate) fn request_conversion(err: anyhow::Error) -> Self {
        Self::message(LlmErrorKind::InvalidRequest, format!("{err:#}"))
    }

    /// A successfully received response that could not be decoded into the
    /// shared types — a decode failure, like [`From<serde_json::Error>`].
    pub(crate) fn response_decode(err: anyhow::Error) -> Self {
        match err.downcast::<Self>() {
            Ok(err) => err,
            Err(err) => Self::malformed_response(format!("{err:#}")),
        }
    }

    /// Construct an HTTP-backed LLM error after a provider has classified it.
    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
    }

    /// Whether the provider rejected the request's `tool_choice` value. Some
    /// OpenAI-compatible backends accept only `"auto"` (e.g. OpenCode zen's
    /// Go models: `only "auto" is supported for tool_choice`); the request
    /// succeeds resent without the parameter — see
    /// [`crate::client::chat_with_tool_choice_fallback`].
    ///
    /// Requires a provider origin (an HTTP status or provider code): local
    /// [`Self::request_conversion`] errors also mention `tool_choice` but mark
    /// caller bugs, which a retry would mask.
    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")
    }

    /// Whether the provider rejected replayed reasoning as bound to a
    /// different conversation. Anthropic binds each thinking block to the
    /// tools, system prompt and messages before it, so once any of those
    /// changes (a tool that arrives late, a conversation resumed under other
    /// settings) every request replaying the block fails. Terminal as sent,
    /// but succeeds resent without the reasoning.
    pub fn is_reasoning_rejection(&self) -> bool {
        self.kind == LlmErrorKind::InvalidRequest
            && self.detail.message.contains("bound to a different conversation")
    }

    /// How long to wait before automatic retry number `attempt` (1-based), or
    /// `None` when the failure is terminal. The wait is the provider's
    /// `Retry-After` when it sent one, otherwise exponential backoff from 1s,
    /// clamped to [1s, 60s] so an instant retry cannot spin. A `Retry-After`
    /// beyond the cap is terminal, not truncated: retrying early would only
    /// re-hit a provider that asked for more room.
    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 {
    /// Stable snake_case identifier for telemetry attributes. Unlike
    /// [`Display`](fmt::Display), these values are part of the metrics schema
    /// and must not change.
    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",
        }
    }

    /// Whether an automatic retry is worthwhile: the failure is self-clearing
    /// (throttling, capacity, provider fault, deadline, network fault) or a
    /// stream that died before delivering output. Callers consume this
    /// through [`LlmError::retry_delay`].
    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 {}

/// An undeserializable body is a malformed response. This lets a buffered
/// response decode with `?`.
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(" <- "))
}

/// Coarse HTTP-status → [`LlmErrorKind`] fallback, shared by every provider.
///
/// Providers consult their own `error.type` / `error.code` / `error.status`
/// mapping first and fall back to this when the body carries no recognized code.
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,
    }
}

/// Recognize context-limit rejections from OpenAI-compatible endpoints that
/// omit a specific error code or return a generic invalid-request code.
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")
}

/// Classify a failure from the OpenAI wire family (Responses and Chat
/// Completions) by its error code and message, falling back to `fallback`
/// (the HTTP status when there is one). A context-overflow message outranks a
/// generic invalid-request code: gateways often wrap the real reason in one.
/// `wire_codes` maps the codes only that wire has been seen to emit and is
/// consulted before the shared table; it receives the code lowercased.
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,
    }
}

/// Error codes shared across the OpenAI wire family; `code` is lowercased.
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),
        // OpenCode zen usage windows (free daily cap, Go/Black plan windows),
        // served as 429 with the error class name in `error.type`. Resets are
        // hours to days away — hard quotas, not transient throttling. Zen's
        // transient `RateLimitError` stays on the 429 → RateLimited fallback.
        "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,
    }
}

/// Extract `(code, message)` from the `{"error": {...}}` body shape every
/// provider uses. Providers differ only in which field carries the error code
/// (`type` / `status` / `code`); `code_fields` are tried in order and the first
/// string value wins. Returns `(None, None)` for a non-JSON body.
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),
    }
}

/// [`parse_error_body`] over an already-decoded value.
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() {
        // A builder error gives us a reqwest source chain without network IO.
        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() {
        // Truncating an hour-long reset to the cap would retry into the same
        // limit four times over; the retry is refused and the reset kept.
        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);
    }
}