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