Skip to main content

base/interface/
model.rs

1//! `Model` trait — protocol-agnostic LLM backend interface.
2
3use crate::prompt::PromptBlock;
4use crate::provider::ApiType;
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::sync::{Arc, Mutex};
9use tokio_util::sync::CancellationToken;
10
11mod metering;
12pub use metering::OnSpent;
13
14/// Model thinking/reasoning mode.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
16#[serde(rename_all = "snake_case")]
17pub enum ThinkingMode {
18    Auto,
19    Off,
20    On,
21    OnBudget(u32),
22}
23
24/// How much work the model puts into a reply. DeepSeek accepts `low`,
25/// `high` and `max`, folding `medium` and `xhigh` into `high`.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
27#[serde(rename_all = "snake_case")]
28pub enum Effort {
29    Low,
30    Medium,
31    High,
32    Xhigh,
33    Max,
34}
35
36/// Protocol-agnostic LLM client trait.
37///
38/// Implementations translate `PromptBlock` and `ToolDef` into
39/// the API-specific wire format (Anthropic Messages, OpenAI Chat Completions).
40#[async_trait]
41pub trait Model: Send + Sync {
42    /// Which API protocol this model client uses.
43    fn api_type(&self) -> ApiType;
44
45    /// The provider id this client was built for, stamped on the reasoning
46    /// it produces so a later request to a different provider does not echo
47    /// it back. A client that routes between providers has none of its own:
48    /// each of its calls names its provider with [`ModelEvent::Served`].
49    /// `None` for a client built outside a provider route; reasoning from
50    /// such a client carries no provenance and is sent wherever it goes.
51    fn provenance(&self) -> Option<String> {
52        None
53    }
54
55    /// Stream a response from the LLM.
56    ///
57    /// Returns a stream of `ModelEvent`s (text deltas, tool use blocks).
58    /// The cancel token allows the caller to abort mid-stream.
59    async fn stream(
60        &self,
61        prompt_blocks: Vec<PromptBlock>,
62        tools: Vec<ToolDef>,
63        messages: Vec<ModelMessage>,
64        params: StreamParams,
65        cancel: CancellationToken,
66    ) -> Result<ModelStream, ModelError>;
67}
68
69/// Parameters for a streaming LLM call.
70#[derive(Debug, Clone)]
71pub struct StreamParams {
72    pub model: String,
73    pub max_tokens: u32,
74    pub thinking_mode: ThinkingMode,
75    pub effort: Option<Effort>,
76    /// Cache edits: tool_use_ids whose tool result content should be deleted from the
77    /// server-side cached prefix. Wired to the Anthropic `cache_edits` content block.
78    pub cache_edits: Vec<String>,
79    /// Where this call sits in the conversation. Carried for observers only —
80    /// no adapter reads it, and it never reaches the wire.
81    pub origin: Option<CallOrigin>,
82    /// What this turn's user message is made of. Observers only, like `origin`.
83    pub input_map: Option<InputMap>,
84    /// Have the provider search the web itself during this call, reporting
85    /// what it found as [`ModelEvent::SearchResults`]. A provider with no
86    /// search of its own refuses the call with [`ModelErrorKind::Unsupported`].
87    pub provider_search: Option<ProviderSearch>,
88    /// Where the client reports usage it learns before the call ends, so a
89    /// call that never reaches [`ModelEvent::EndTurn`] is still counted, and
90    /// what the call is charged to.
91    pub usage_tap: UsageTap,
92}
93
94/// Usage a client has learned of a call so far — the input side, which an
95/// Anthropic stream reports when it opens — and the node the call is charged
96/// to. [`ModelEvent::EndTurn`]'s usage supersedes what was reported.
97/// Reporting to a tap nobody made does nothing.
98///
99/// The charge is counted once, by whoever routes the call, through
100/// [`UsageTap::metered`]: everything above the client only says where it
101/// goes.
102#[derive(Clone, Default)]
103pub struct UsageTap {
104    reported: Option<Arc<Mutex<Option<Usage>>>>,
105    charge: Option<Arc<crate::interface::budget_policy::SpendNode>>,
106}
107
108impl UsageTap {
109    pub fn new() -> Self {
110        Self {
111            reported: Some(Arc::default()),
112            charge: None,
113        }
114    }
115
116    /// A tap whose call is charged to `node`.
117    pub fn charging(node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
118        Self {
119            reported: None,
120            charge: Some(node),
121        }
122    }
123
124    /// A fresh tap for one attempt at the call, charged where this one is.
125    pub fn for_attempt(&self) -> Self {
126        Self {
127            charge: self.charge.clone(),
128            ..Self::new()
129        }
130    }
131
132    pub fn charge(&self) -> Option<&Arc<crate::interface::budget_policy::SpendNode>> {
133        self.charge.as_ref()
134    }
135
136    pub fn report(&self, usage: Usage) {
137        if let Some(slot) = &self.reported {
138            *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(usage);
139        }
140    }
141
142    pub fn reported(&self) -> Option<Usage> {
143        self.reported
144            .as_ref()
145            .and_then(|slot| *slot.lock().unwrap_or_else(|e| e.into_inner()))
146    }
147}
148
149impl std::fmt::Debug for UsageTap {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.debug_struct("UsageTap")
152            .field("reported", &self.reported())
153            .field("charged", &self.charge.is_some())
154            .finish()
155    }
156}
157
158/// A web search the provider runs itself, inside the call.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct ProviderSearch {
161    /// The most searches the call may make.
162    pub max_uses: u32,
163}
164
165/// One page a provider's own web search found.
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct SearchHit {
168    pub title: String,
169    pub url: String,
170}
171
172/// The composition of the user message a turn was started by.
173///
174/// A user message goes out as one message whose first block holds the prompt
175/// text, and it has to stay that way: splitting the sources into separate
176/// content blocks would change the bytes the model receives. So composition is
177/// expressed as coordinates over the message rather than in its structure —
178/// the same reason [`crate::prompt::PromptBlock::name`] is a
179/// field and not a delimiter inside the content.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct InputMap {
182    /// Index into the request's messages. Resolved when the request is
183    /// assembled, not when the message was pushed: compaction rewrites the
184    /// message list in between, and an index captured earlier would point at
185    /// whatever moved into that slot.
186    pub user_message: usize,
187    pub spans: Vec<InputSpan>,
188}
189
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191pub struct InputSpan {
192    /// One of the constants in [`input_source`].
193    pub source: String,
194    /// Which content block of the message.
195    pub block: usize,
196    /// Byte range within that block's text. Absent for a non-text block, which
197    /// has no interior to point into.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub range: Option<(usize, usize)>,
200}
201
202/// Values for [`InputSpan::source`].
203pub mod input_source {
204    /// What the user actually typed.
205    pub const USER_PROMPT: &str = "user_prompt";
206    /// An `@server:scheme://path` reference resolved and inlined into the
207    /// prompt text.
208    pub const MCP_RESOURCE: &str = "mcp_resource";
209    /// A file or image the user attached, carried as its own content block.
210    pub const ATTACHMENT: &str = "attachment";
211}
212
213/// Which session issued a call, and what the call is doing there.
214///
215/// Every model call has one, auxiliary calls included: naming the *kind* of
216/// call keeps the session known (so concurrent sessions' auxiliary calls are
217/// not filed under one shared name) while still refusing to give an
218/// auxiliary call turn coordinates it does not have.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct CallOrigin {
221    pub session_id: String,
222    /// The session that spawned this one — a sub-agent's parent. `None` for a
223    /// top-level session. This is what lets a set of recordings be read as one
224    /// tree rather than as unrelated files.
225    pub parent_session_id: Option<String>,
226    /// Which kind of agent this session runs, for a sub-agent that has one.
227    pub agent_type: Option<String>,
228    /// The turn this call belongs to, the same `turn_id` the session's events carry; `None` for a call outside any turn or whose caller does not know it.
229    pub turn_id: Option<String>,
230    pub kind: CallKind,
231}
232
233#[derive(Debug, Clone, PartialEq, Eq)]
234#[non_exhaustive]
235pub enum CallKind {
236    /// A call the turn loop made.
237    Turn {
238        turn: u32,
239        /// Index of this model call within its turn — a turn that calls tools
240        /// runs several.
241        step: u32,
242    },
243    /// A call made outside any turn: compaction, memory extraction, permission
244    /// classification, session titling, a hook.
245    ///
246    /// `purpose` is a free string on purpose. The set grows with the engine,
247    /// and an enum would mean editing this crate for every addition; the
248    /// conventional values are the constants in [`call_purpose`]. Readers
249    /// treat it as opaque, and it takes no part in replay divergence checks —
250    /// renaming a classification must not turn a passing replay red.
251    Auxiliary { purpose: String },
252}
253
254impl CallOrigin {
255    /// A turn-loop call in `session_id`.
256    pub fn turn(session_id: impl Into<String>, turn: u32, step: u32) -> Self {
257        Self {
258            session_id: session_id.into(),
259            parent_session_id: None,
260            agent_type: None,
261            turn_id: None,
262            kind: CallKind::Turn { turn, step },
263        }
264    }
265
266    /// A call outside any turn, still belonging to `session_id`.
267    pub fn auxiliary(session_id: impl Into<String>, purpose: impl Into<String>) -> Self {
268        Self {
269            session_id: session_id.into(),
270            parent_session_id: None,
271            agent_type: None,
272            turn_id: None,
273            kind: CallKind::Auxiliary {
274                purpose: purpose.into(),
275            },
276        }
277    }
278
279    pub fn with_lineage(
280        mut self,
281        parent_session_id: Option<String>,
282        agent_type: Option<String>,
283    ) -> Self {
284        self.parent_session_id = parent_session_id;
285        self.agent_type = agent_type;
286        self
287    }
288
289    pub fn with_turn_id(mut self, turn_id: impl Into<String>) -> Self {
290        self.turn_id = Some(turn_id.into());
291        self
292    }
293
294    /// Turn coordinates, or `(0, 0)` for a call that has none.
295    pub fn turn_step(&self) -> (u32, u32) {
296        match &self.kind {
297            CallKind::Turn { turn, step } => (*turn, *step),
298            CallKind::Auxiliary { .. } => (0, 0),
299        }
300    }
301
302    pub fn purpose(&self) -> Option<&str> {
303        match &self.kind {
304            CallKind::Turn { .. } => None,
305            CallKind::Auxiliary { purpose } => Some(purpose),
306        }
307    }
308}
309
310/// Conventional values for [`CallKind::Auxiliary::purpose`].
311pub mod call_purpose {
312    pub const COMPACT: &str = "compact";
313    pub const MEMORY: &str = "memory";
314    pub const TITLE: &str = "title";
315    pub const HOOK: &str = "hook";
316    /// Team aggregation picking or merging its agents' results.
317    pub const TEAM_JUDGE: &str = "team_judge";
318    /// The provider searching the web for a `WebSearch` call.
319    pub const WEB_SEARCH: &str = "web_search";
320    /// A model answering a `WebFetch` call's `prompt` from the fetched page.
321    pub const WEB_FETCH: &str = "web_fetch";
322}
323
324/// Tool definition sent to the model.
325#[derive(Debug, Clone, Serialize, Deserialize)]
326#[non_exhaustive]
327pub struct ToolDef {
328    pub name: String,
329    pub description: String,
330    pub input_schema: Value,
331    /// Where this tool came from — `builtin`, `mcp:<server>`, `plugin:<id>`.
332    ///
333    /// Annotation only, like [`crate::prompt::PromptBlock::source`]:
334    /// both adapters translate a `ToolDef` field by field, so this one is
335    /// simply not copied and never reaches the wire.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub source: Option<String>,
338}
339
340impl ToolDef {
341    pub fn new(
342        name: impl Into<String>,
343        description: impl Into<String>,
344        input_schema: Value,
345    ) -> Self {
346        Self {
347            name: name.into(),
348            description: description.into(),
349            input_schema,
350            source: None,
351        }
352    }
353    pub fn with_source(mut self, source: impl Into<String>) -> Self {
354        self.source = Some(source.into());
355        self
356    }
357}
358
359/// A message in the model's conversation history.
360#[derive(Debug, Clone, Serialize, Deserialize)]
361pub struct ModelMessage {
362    pub role: MessageRole,
363    pub content: Vec<ModelContentBlock>,
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
367#[serde(rename_all = "snake_case")]
368pub enum MessageRole {
369    User,
370    Assistant,
371    System,
372}
373
374/// Token cost to charge a [`ModelContentBlock::Image`] in context-budget
375/// estimates.
376///
377/// Anthropic bills images at roughly `width * height / 750` tokens, capped near
378/// 1600 for an image at the ~1.15 MP resize ceiling. We do not have pixel
379/// dimensions at this layer, so we charge the ceiling — deliberately
380/// pessimistic, because under-counting context is what causes a request to be
381/// rejected for length.
382///
383/// The trap this constant exists to avoid: estimating an image the same way as
384/// text (`data.len() / 4`) reads a 1 MB screenshot as ~250_000 tokens, which
385/// would trip compaction immediately on the first image the user pastes. The
386/// base64 payload length says almost nothing about the token cost.
387pub const IMAGE_TOKEN_ESTIMATE: usize = 1600;
388
389/// Token cost to charge a [`ModelContentBlock::Document`]: a PDF is billed as
390/// its text plus a picture per page, roughly 3000 tokens per ~50 KB page, so
391/// the estimate follows the decoded size and never drops below an image's.
392pub fn document_token_estimate(base64_len: usize) -> usize {
393    (base64_len / 4 * 3 / 20).max(IMAGE_TOKEN_ESTIMATE)
394}
395
396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397#[serde(tag = "type", rename_all = "snake_case")]
398pub enum ModelContentBlock {
399    Text {
400        text: String,
401    },
402    /// A base64-encoded image. Carries the same two fields the Anthropic API's
403    /// `source` object needs, kept flat here because every provider that
404    /// supports images needs exactly these and nothing more.
405    ///
406    /// `data` is **not** logged or Debug-printed usefully — it is megabytes of
407    /// base64. Anything that renders a message for humans or for a token
408    /// estimate must special-case this variant rather than falling through to
409    /// a generic text path.
410    Image {
411        /// e.g. `image/png`, `image/jpeg`.
412        media_type: String,
413        /// Base64-encoded bytes, no data-URI prefix.
414        data: String,
415    },
416    /// A base64-encoded document, PDF in practice. Like [`Image`](Self::Image)
417    /// its `data` is megabytes of base64 and must never be rendered as text.
418    Document {
419        media_type: String,
420        data: String,
421        #[serde(default, skip_serializing_if = "Option::is_none")]
422        title: Option<String>,
423    },
424    /// An extended-thinking block, with the signature that closed it if the
425    /// provider sent one.
426    ///
427    /// When thinking is enabled and the assistant's turn contained tool use,
428    /// the Anthropic API requires the previous assistant turn's thinking
429    /// blocks to be echoed back *with their signatures* on the following
430    /// request. Blocks without a signature (reasoning from an
431    /// OpenAI-compatible endpoint, or a relay that never sends one) are kept
432    /// for the transcript and are never sent to the Anthropic API.
433    Thinking {
434        text: String,
435        #[serde(default, skip_serializing_if = "Option::is_none")]
436        signature: Option<String>,
437        /// [`Model::provenance`] of the client that produced it.
438        #[serde(default, skip_serializing_if = "Option::is_none")]
439        provider: Option<String>,
440    },
441    /// Thinking the API chose to encrypt. Opaque to us; must still be echoed
442    /// back verbatim for the same reason as [`ModelContentBlock::Thinking`].
443    RedactedThinking {
444        data: String,
445        #[serde(default, skip_serializing_if = "Option::is_none")]
446        provider: Option<String>,
447    },
448    ToolUse {
449        id: String,
450        name: String,
451        input: Value,
452    },
453    ToolResult {
454        tool_use_id: String,
455        content: String,
456        is_error: Option<bool>,
457    },
458}
459
460impl ModelContentBlock {
461    /// Reasoning another provider produced. Only that provider can verify or
462    /// use it, so it is never sent to `provenance`. Blocks without a recorded
463    /// provider, and requests to a client without one, are not foreign.
464    pub fn is_foreign_reasoning(&self, provenance: Option<&str>) -> bool {
465        let produced_by = match self {
466            ModelContentBlock::Thinking { provider, .. }
467            | ModelContentBlock::RedactedThinking { provider, .. } => provider.as_deref(),
468            _ => return false,
469        };
470        matches!((produced_by, provenance), (Some(a), Some(b)) if a != b)
471    }
472}
473
474pub type ModelStream =
475    Box<dyn futures::Stream<Item = Result<ModelEvent, ModelError>> + Send + Unpin>;
476
477#[derive(Debug, Clone, Serialize, Deserialize)]
478#[serde(tag = "kind", rename_all = "snake_case")]
479pub enum ModelEvent {
480    /// The provider this call went to, first in the stream of a call that
481    /// was routed; the call's reasoning is stamped with it.
482    Served {
483        provider: String,
484        #[serde(default)]
485        model: String,
486    },
487    TextDelta {
488        text: String,
489    },
490    /// Incremental extended-thinking text. Emitted so hosts can render the
491    /// model's reasoning as it streams; the accumulated text plus the
492    /// signature from [`ModelEvent::ThinkingSignature`] become a
493    /// [`ModelContentBlock::Thinking`] in the transcript.
494    ThinkingDelta {
495        text: String,
496    },
497    /// The signature that closes the current thinking block. The API sends it
498    /// once, at the end of the block.
499    ThinkingSignature {
500        signature: String,
501    },
502    /// A thinking block the API encrypted; opaque, forwarded whole.
503    RedactedThinking {
504        data: String,
505    },
506    /// The model has started a tool call; its arguments are still streaming.
507    /// The call itself is the [`ModelEvent::ToolUse`] that follows.
508    ToolUseStart {
509        id: String,
510        name: String,
511    },
512    ToolUse {
513        id: String,
514        name: String,
515        input: Value,
516    },
517    /// A tool call whose arguments are not a JSON value — usually cut off
518    /// because the reply reached its output limit. It is not run; it is
519    /// answered with an error so the model can call again.
520    MalformedToolUse {
521        id: String,
522        name: String,
523        /// The arguments as they arrived.
524        raw_input: String,
525    },
526    /// One raw fragment of a tool call's arguments, exactly as the model
527    /// produced it. Observational only: the adapter still concatenates the
528    /// fragments and emits the assembled [`ModelEvent::ToolUse`], which is what
529    /// the engine acts on. Forwarded alongside it because a malformed or
530    /// truncated argument stream is precisely the case worth investigating
531    /// afterwards, and concatenation destroys the evidence.
532    ToolArgsDelta {
533        id: String,
534        partial_json: String,
535    },
536    ContentBlockStart {
537        index: usize,
538        block: ModelContentBlock,
539    },
540    ContentBlockStop {
541        index: usize,
542    },
543    /// What a search the provider ran itself found (see
544    /// [`StreamParams::provider_search`]), in the order it reported them.
545    SearchResults {
546        hits: Vec<SearchHit>,
547    },
548    /// The stream stopped without the provider saying the reply was done —
549    /// no end marker, no finish reason. What arrived is taken as the whole
550    /// reply; the [`ModelEvent::EndTurn`] that follows is the adapter's, not
551    /// the provider's.
552    Truncated,
553    EndTurn {
554        stop_reason: String,
555        usage: Usage,
556    },
557}
558
559#[derive(
560    Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
561)]
562pub struct Usage {
563    pub input_tokens: u32,
564    pub output_tokens: u32,
565    /// Tokens written into the prompt cache by this call, and tokens read
566    /// back from it. Both are priced differently from ordinary input — a
567    /// cache read costs a fraction of one — so a report that folded them
568    /// into `input_tokens` would overcharge and one that dropped them
569    /// undercharges by whatever the cache covered.
570    ///
571    /// `#[serde(default)]` because recordings written before these existed
572    /// must still read back.
573    #[serde(default)]
574    pub cache_creation_input_tokens: u32,
575    #[serde(default)]
576    pub cache_read_input_tokens: u32,
577}
578
579impl Usage {
580    /// This and one more call's worth.
581    ///
582    /// A provider reports usage per call and a turn is several calls, so
583    /// summing is what anyone asking "what did that cost" has to do. Saturating
584    /// because a turn that overflowed a `u32` of tokens has a bigger problem
585    /// than an inexact total, and wrapping to nearly zero would be the one
586    /// answer worse than the true one.
587    pub fn plus(self, other: Usage) -> Usage {
588        Usage {
589            input_tokens: self.input_tokens.saturating_add(other.input_tokens),
590            output_tokens: self.output_tokens.saturating_add(other.output_tokens),
591            cache_creation_input_tokens: self
592                .cache_creation_input_tokens
593                .saturating_add(other.cache_creation_input_tokens),
594            cache_read_input_tokens: self
595                .cache_read_input_tokens
596                .saturating_add(other.cache_read_input_tokens),
597        }
598    }
599}
600
601/// What kind of failure a model call had. Assigned once, by the protocol
602/// client that saw it; everything above reads it.
603#[non_exhaustive]
604#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
605#[serde(rename_all = "snake_case")]
606pub enum ModelErrorKind {
607    /// 429, or a body saying `rate_limit_error`.
608    RateLimited,
609    /// 503, 529, or a body saying `overloaded_error`.
610    Overloaded,
611    /// 408, 500, 502, 504: the server side failed and the request was fine.
612    Unavailable,
613    /// Nothing usable came back: connection reset, DNS, TLS.
614    Transport,
615    /// No response headers, or no next event, within the idle window.
616    Timeout,
617    /// The stream broke off before the message ended.
618    StreamInterrupted,
619    /// The request was refused for its size.
620    ContextTooLong,
621    /// Any other 4xx.
622    InvalidRequest,
623    NotFound,
624    /// 401, 403.
625    Auth,
626    /// There was no credential to send, so nothing was sent.
627    NoCredentials,
628    /// 402, or a body saying `billing_error`.
629    Billing,
630    /// The egress policy refused the connection.
631    Denied,
632    /// Any other 5xx.
633    ServerError,
634    /// The response could not be read: SSE framing, JSON shape.
635    Protocol,
636    Cancelled,
637    /// The provider cannot do what the call asked of it.
638    Unsupported,
639    /// A replay was asked for a call its recording does not hold, and the
640    /// call is one a replay is allowed to go without — the caller skips it
641    /// rather than reporting a failure.
642    NotRecorded,
643    /// Every provider in the order was out of quota or failed to take the
644    /// call; the message says why for each.
645    ProvidersUnavailable,
646}
647
648impl ModelErrorKind {
649    pub fn as_str(self) -> &'static str {
650        match self {
651            Self::RateLimited => "rate_limited",
652            Self::Overloaded => "overloaded",
653            Self::Unavailable => "unavailable",
654            Self::Transport => "transport",
655            Self::Timeout => "timeout",
656            Self::StreamInterrupted => "stream_interrupted",
657            Self::ContextTooLong => "context_too_long",
658            Self::InvalidRequest => "invalid_request",
659            Self::NotFound => "not_found",
660            Self::Auth => "auth",
661            Self::NoCredentials => "no_credentials",
662            Self::Billing => "billing",
663            Self::Denied => "denied",
664            Self::ServerError => "server_error",
665            Self::Protocol => "protocol",
666            Self::Cancelled => "cancelled",
667            Self::Unsupported => "unsupported",
668            Self::NotRecorded => "not_recorded",
669            Self::ProvidersUnavailable => "providers_unavailable",
670        }
671    }
672
673    /// What a client's backoff policy is told about a request that failed
674    /// before its first byte.
675    pub fn request_failure(self) -> crate::interface::backoff::RequestFailure {
676        use crate::interface::backoff::RequestFailure;
677        match self {
678            Self::RateLimited => RequestFailure::RateLimited,
679            Self::Overloaded | Self::Unavailable => RequestFailure::Overloaded,
680            Self::Transport | Self::Timeout => RequestFailure::Transport,
681            _ => RequestFailure::Other,
682        }
683    }
684
685    /// Whether the same request, sent again a little later, may well succeed.
686    pub fn transient(self) -> bool {
687        matches!(
688            self,
689            Self::RateLimited
690                | Self::Overloaded
691                | Self::Unavailable
692                | Self::Transport
693                | Self::Timeout
694                | Self::StreamInterrupted
695        )
696    }
697}
698
699impl std::fmt::Display for ModelErrorKind {
700    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
701        f.write_str(self.as_str())
702    }
703}
704
705/// A failed model call, as the protocol client classified it.
706#[non_exhaustive]
707#[derive(Debug, Clone, PartialEq, Eq)]
708pub struct ModelError {
709    pub kind: ModelErrorKind,
710    /// The HTTP status, when the failure had one.
711    pub status: Option<u16>,
712    /// How long the provider asked to be left alone, when it said.
713    pub retry_after: Option<std::time::Duration>,
714    pub message: String,
715}
716
717impl ModelError {
718    pub fn new(kind: ModelErrorKind, message: impl Into<String>) -> Self {
719        Self {
720            kind,
721            status: None,
722            retry_after: None,
723            message: message.into(),
724        }
725    }
726
727    pub fn with_status(mut self, status: u16) -> Self {
728        self.status = Some(status);
729        self
730    }
731
732    pub fn with_retry_after(mut self, retry_after: Option<std::time::Duration>) -> Self {
733        self.retry_after = retry_after;
734        self
735    }
736
737    pub fn cancelled() -> Self {
738        Self::new(ModelErrorKind::Cancelled, "")
739    }
740
741    pub fn rate_limited() -> Self {
742        Self::new(ModelErrorKind::RateLimited, "")
743    }
744
745    pub fn overloaded() -> Self {
746        Self::new(ModelErrorKind::Overloaded, "")
747    }
748
749    /// A call not sent: the budget it would spend into cannot pay for it.
750    pub fn unaffordable(why: &str) -> Self {
751        Self::new(ModelErrorKind::InvalidRequest, format!("not sent: {why}"))
752    }
753
754    pub fn auth(message: impl Into<String>) -> Self {
755        Self::new(ModelErrorKind::Auth, message)
756    }
757
758    pub fn transport(message: impl Into<String>) -> Self {
759        Self::new(ModelErrorKind::Transport, message)
760    }
761
762    pub fn timeout(message: impl Into<String>) -> Self {
763        Self::new(ModelErrorKind::Timeout, message)
764    }
765
766    pub fn stream_interrupted(message: impl Into<String>) -> Self {
767        Self::new(ModelErrorKind::StreamInterrupted, message)
768    }
769
770    pub fn protocol(message: impl Into<String>) -> Self {
771        Self::new(ModelErrorKind::Protocol, message)
772    }
773
774    pub fn invalid_request(message: impl Into<String>) -> Self {
775        Self::new(ModelErrorKind::InvalidRequest, message)
776    }
777
778    pub fn unsupported(message: impl Into<String>) -> Self {
779        Self::new(ModelErrorKind::Unsupported, message)
780    }
781
782    pub fn not_recorded(message: impl Into<String>) -> Self {
783        Self::new(ModelErrorKind::NotRecorded, message)
784    }
785}
786
787impl std::fmt::Display for ModelError {
788    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
789        f.write_str(self.kind.as_str())?;
790        if let Some(status) = self.status {
791            write!(f, " (HTTP {status})")?;
792        }
793        if !self.message.is_empty() {
794            write!(f, ": {}", self.message)?;
795        }
796        Ok(())
797    }
798}
799
800impl std::error::Error for ModelError {}