Skip to main content

adk_vision/
backend.rs

1//! [`BackendDescriptor`]: what a backend is, where it runs, how it answers and what it costs.
2
3use std::fmt;
4
5use adk_core::{UnitRate, UsageUnit};
6use serde::{Deserialize, Serialize};
7
8use crate::geometry::CoordFrame;
9
10/// A backend's stable identifier, such as `rf-detr-m` or `sam-3.1`.
11#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct BackendId(String);
14
15impl BackendId {
16    /// A backend identifier.
17    pub fn new(id: impl Into<String>) -> Self {
18        Self(id.into())
19    }
20
21    /// The identifier as text.
22    pub fn as_str(&self) -> &str {
23        &self.0
24    }
25}
26
27impl fmt::Display for BackendId {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        f.write_str(&self.0)
30    }
31}
32
33impl From<&str> for BackendId {
34    fn from(id: &str) -> Self {
35        Self::new(id)
36    }
37}
38
39/// Where a backend's computation happens, which decides whether an image leaves the
40/// machine.
41///
42/// Mirrors `adk_core::DataLocality` (spec 3.7 X6: `InProcess` for `adk-mistralrs`,
43/// `Loopback` for a client at a loopback address, `Remote` otherwise), with the hosts a
44/// remote backend sends to, which the egress policy checks.
45#[non_exhaustive]
46#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "camelCase", tag = "kind")]
48pub enum Locality {
49    /// In this process.
50    InProcess,
51    /// A server on this machine, reached over loopback.
52    Loopback,
53    /// Off the machine: images reach it only through the egress gate.
54    Remote {
55        /// The hosts the backend sends to; the egress policy checks each.
56        hosts: Vec<String>,
57    },
58}
59
60impl Locality {
61    /// `true` for [`Remote`](Self::Remote).
62    pub fn is_remote(&self) -> bool {
63        matches!(self, Self::Remote { .. })
64    }
65}
66
67/// How a priced backend is billed.
68#[non_exhaustive]
69#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
71pub enum PriceRef {
72    /// Billed per unit by the runtime: `sam-3.1` at $2.50 per 1,000 images.
73    PerUnit {
74        /// The spend-key vendor, such as `meta`.
75        vendor: String,
76        /// The model, as the catalog names it.
77        model: String,
78        /// The rate.
79        rate: UnitRate,
80        /// The fewest units one request is billed for (`sam-3.1` video bills 50 frames).
81        /// Moves into the rate as `UnitRate::with_minimum_per_request` once adk-core has it
82        /// (spec 3.7 X3).
83        #[serde(default)]
84        min_units_per_request: u64,
85    },
86    /// Billed per token by the model call itself, which meters its tokens through the
87    /// current `ModelCallScope`; the runtime records the call's images at zero cost.
88    Tokens {
89        /// The spend-key vendor.
90        vendor: String,
91        /// The model.
92        model: String,
93    },
94}
95
96impl PriceRef {
97    /// The spend-key vendor.
98    pub fn vendor(&self) -> &str {
99        match self {
100            Self::PerUnit { vendor, .. } | Self::Tokens { vendor, .. } => vendor,
101        }
102    }
103
104    /// The model.
105    pub fn model(&self) -> &str {
106        match self {
107            Self::PerUnit { model, .. } | Self::Tokens { model, .. } => model,
108        }
109    }
110
111    /// The cost of a request that uses `amount` units of the priced unit, in micro-USD, or
112    /// `None` for token-billed backends.
113    ///
114    /// # Example
115    ///
116    /// ```
117    /// use adk_core::{UnitRate, UsageUnit};
118    /// use adk_vision::PriceRef;
119    ///
120    /// let sam = PriceRef::PerUnit {
121    ///     vendor: "meta".into(),
122    ///     model: "sam-3.1".into(),
123    ///     rate: UnitRate::new(UsageUnit::Images, 2_500_000, 1_000),
124    ///     min_units_per_request: 0,
125    /// };
126    /// assert_eq!(sam.request_cost(1), Some(2_500));
127    /// ```
128    pub fn request_cost(&self, amount: u64) -> Option<u64> {
129        match self {
130            Self::PerUnit { rate, min_units_per_request, .. } => {
131                Some(rate.cost_micro_usd(amount.max(*min_units_per_request)))
132            }
133            Self::Tokens { .. } => None,
134        }
135    }
136
137    /// The unit a per-unit price bills in.
138    pub fn unit(&self) -> Option<UsageUnit> {
139        match self {
140            Self::PerUnit { rate, .. } => Some(rate.unit),
141            Self::Tokens { .. } => None,
142        }
143    }
144}
145
146/// What a backend does with an image larger than its limits.
147#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(rename_all = "camelCase")]
149pub enum Oversize {
150    /// The runtime downscales it to the limit and records the resize in the transform chain.
151    Downscale,
152    /// The runtime refuses it, naming the limit.
153    Refuse,
154}
155
156/// The largest image a backend takes.
157///
158/// # Example
159///
160/// ```
161/// use adk_vision::InputLimits;
162///
163/// // Claude 4.7 and later: 2,576 px on the long edge.
164/// let limits = InputLimits::long_edge(2576);
165/// assert_eq!(limits.fit((5152, 3000)), Some((2576, 1500)));
166/// assert_eq!(limits.fit((1000, 800)), None);
167/// ```
168#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase")]
170pub struct InputLimits {
171    /// Longest side in pixels.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub max_long_edge: Option<u32>,
174    /// Total pixels.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub max_pixels: Option<u64>,
177    /// What happens to a larger image.
178    pub oversize: Oversize,
179}
180
181impl InputLimits {
182    /// No limit.
183    pub const fn unlimited() -> Self {
184        Self { max_long_edge: None, max_pixels: None, oversize: Oversize::Downscale }
185    }
186
187    /// At most `pixels` on the long edge, larger images downscaled.
188    pub const fn long_edge(pixels: u32) -> Self {
189        Self { max_long_edge: Some(pixels), max_pixels: None, oversize: Oversize::Downscale }
190    }
191
192    /// Sets the total-pixel limit.
193    pub const fn with_max_pixels(mut self, pixels: u64) -> Self {
194        self.max_pixels = Some(pixels);
195        self
196    }
197
198    /// Refuses larger images instead of downscaling them.
199    pub const fn refusing(mut self) -> Self {
200        self.oversize = Oversize::Refuse;
201        self
202    }
203
204    /// `true` when an image of `size` is within the limits.
205    pub fn admits(&self, size: (u32, u32)) -> bool {
206        let long = size.0.max(size.1);
207        let pixels = u64::from(size.0) * u64::from(size.1);
208        self.max_long_edge.is_none_or(|max| long <= max)
209            && self.max_pixels.is_none_or(|max| pixels <= max)
210    }
211
212    /// The size an image of `size` is downscaled to, keeping its aspect ratio, or `None`
213    /// when it is within the limits.
214    pub fn fit(&self, size: (u32, u32)) -> Option<(u32, u32)> {
215        if self.admits(size) {
216            return None;
217        }
218        let (w, h) = (f64::from(size.0), f64::from(size.1));
219        let mut scale = 1.0f64;
220        if let Some(max) = self.max_long_edge {
221            scale = scale.min(f64::from(max) / w.max(h));
222        }
223        if let Some(max) = self.max_pixels {
224            scale = scale.min((max as f64 / (w * h)).sqrt());
225        }
226        let mut fitted = (((w * scale).round() as u32).max(1), ((h * scale).round() as u32).max(1));
227        // Rounding may leave a side or the pixel count a hair over; step down until it fits.
228        while !self.admits(fitted) && (fitted.0 > 1 || fitted.1 > 1) {
229            if fitted.0 >= fitted.1 {
230                fitted.0 -= 1;
231                fitted.1 = ((f64::from(fitted.0) * h / w).round() as u32).max(1);
232            } else {
233                fitted.1 -= 1;
234                fitted.0 = ((f64::from(fitted.1) * w / h).round() as u32).max(1);
235            }
236        }
237        Some(fitted)
238    }
239
240    /// The limits in words, for error messages.
241    pub fn describe(&self) -> String {
242        match (self.max_long_edge, self.max_pixels) {
243            (Some(edge), Some(px)) => format!("{edge} px on the long edge and {px} pixels"),
244            (Some(edge), None) => format!("{edge} px on the long edge"),
245            (None, Some(px)) => format!("{px} pixels"),
246            (None, None) => "any size".to_string(),
247        }
248    }
249}
250
251impl Default for InputLimits {
252    fn default() -> Self {
253        Self::unlimited()
254    }
255}
256
257/// What a backend is, where it runs, the frame it answers in, what it costs and what it
258/// takes.
259///
260/// # Example
261///
262/// ```
263/// use adk_vision::{BackendDescriptor, CoordFrame, InputLimits, Letterbox, Locality};
264///
265/// let rf_detr = BackendDescriptor::new(
266///     "rf-detr-m",
267///     Locality::InProcess,
268///     CoordFrame::ModelInput { width: 576, height: 576, letterbox: Letterbox::Center },
269/// )
270/// .with_manifest("rf-detr-m");
271/// assert!(!rf_detr.locality.is_remote());
272/// assert!(rf_detr.price.is_none());
273/// ```
274#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct BackendDescriptor {
277    /// The backend's identifier.
278    pub id: BackendId,
279    /// Where it runs.
280    pub locality: Locality,
281    /// The providers a remote backend sends to, by the id their responses carry in
282    /// `LlmResponse::provider` (`anthropic`, `gemini`, `bedrock`), which `provider` egress
283    /// rules match; empty when unknown.
284    #[serde(default, skip_serializing_if = "Vec::is_empty")]
285    pub providers: Vec<String>,
286    /// The coordinate frame its regions are in.
287    pub frame: CoordFrame,
288    /// How it is billed; `None` for local backends, which record units at zero cost.
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub price: Option<PriceRef>,
291    /// The model manifest entry it runs, for model-backed backends.
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub manifest: Option<String>,
294    /// The largest image it takes.
295    #[serde(default)]
296    pub limits: InputLimits,
297    /// How a token-billed backend's cost is estimated before its request, so the run's
298    /// budget can refuse it before any image leaves (spec 3.7 ยง7.9).
299    #[serde(default, skip_serializing_if = "Option::is_none")]
300    pub token_estimate: Option<crate::budget::TokenEstimate>,
301    /// The most open-vocabulary concepts one request takes (`sam-3.1` takes one), so a
302    /// call with more is held and metered as one request per that many concepts; `None` for
303    /// no limit.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub concepts_per_request: Option<u32>,
306}
307
308impl BackendDescriptor {
309    /// A descriptor with no price, no manifest and no input limit.
310    pub fn new(id: impl Into<String>, locality: Locality, frame: CoordFrame) -> Self {
311        Self {
312            id: BackendId::new(id),
313            locality,
314            providers: Vec::new(),
315            frame,
316            price: None,
317            manifest: None,
318            limits: InputLimits::unlimited(),
319            token_estimate: None,
320            concepts_per_request: None,
321        }
322    }
323
324    /// Names a provider the backend sends to, for `provider` egress rules.
325    ///
326    /// # Example
327    ///
328    /// ```
329    /// use adk_vision::{BackendDescriptor, CoordFrame, Locality};
330    ///
331    /// let sam = BackendDescriptor::new(
332    ///     "sam-3.1",
333    ///     Locality::Remote { hosts: vec!["api.meta.ai".into()] },
334    ///     CoordFrame::SentPixels,
335    /// )
336    /// .with_provider("muse");
337    /// assert_eq!(sam.providers, ["muse"]);
338    /// ```
339    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
340        let provider = provider.into();
341        if !self.providers.contains(&provider) {
342            self.providers.push(provider);
343        }
344        self
345    }
346
347    /// Sets the preflight estimate of a token-billed backend.
348    pub fn with_token_estimate(mut self, estimate: crate::budget::TokenEstimate) -> Self {
349        self.token_estimate = Some(estimate);
350        self
351    }
352
353    /// Sets the price.
354    pub fn with_price(mut self, price: PriceRef) -> Self {
355        self.price = Some(price);
356        self
357    }
358
359    /// Names the model manifest entry.
360    pub fn with_manifest(mut self, manifest: impl Into<String>) -> Self {
361        self.manifest = Some(manifest.into());
362        self
363    }
364
365    /// Sets the input limits.
366    pub fn with_limits(mut self, limits: InputLimits) -> Self {
367        self.limits = limits;
368        self
369    }
370
371    /// Takes at most `concepts` open-vocabulary concepts per request.
372    pub fn with_concepts_per_request(mut self, concepts: u32) -> Self {
373        self.concepts_per_request = Some(concepts.max(1));
374        self
375    }
376
377    /// The requests a call with `concepts` concepts and, separately, other prompts makes:
378    /// one per [`concepts_per_request`](Self::concepts_per_request) concepts, and one for
379    /// the other prompts; always 1 for a backend with no limit.
380    ///
381    /// # Example
382    ///
383    /// ```
384    /// use adk_vision::{BackendDescriptor, CoordFrame, Locality};
385    ///
386    /// let sam = BackendDescriptor::new("sam-3.1", Locality::Remote { hosts: vec![] }, CoordFrame::SentPixels)
387    ///     .with_concepts_per_request(1);
388    /// assert_eq!(sam.requests_for(5, false), 5);
389    /// assert_eq!(sam.requests_for(2, true), 3);
390    /// ```
391    pub fn requests_for(&self, concepts: usize, other_prompts: bool) -> u64 {
392        match self.concepts_per_request {
393            Some(per) => {
394                let per = per.max(1) as usize;
395                (concepts.div_ceil(per) + usize::from(other_prompts)).max(1) as u64
396            }
397            None => 1,
398        }
399    }
400}