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