Skip to main content

adk_core/
usage.rs

1//! Vendor-neutral usage units and per-unit prices.
2//!
3//! Token-billed model calls report [`UsageMetadata`](crate::UsageMetadata). Calls billed in
4//! other units — generated images, seconds of audio transcribed, characters synthesized —
5//! report a [`UsageVector`]: an amount per [`UsageUnit`]. A [`UnitRate`] prices one unit in
6//! integer micro-USD, so cost stays the canonical rollup across every unit.
7//!
8//! | Unit | Counts | Typical vendor billing |
9//! |------|--------|------------------------|
10//! | [`InputTokens`](UsageUnit::InputTokens) | Tokens sent to a model | Per million tokens |
11//! | [`OutputTokens`](UsageUnit::OutputTokens) | Tokens a model generated | Per million tokens |
12//! | [`Images`](UsageUnit::Images) | Images generated, edited or analysed | Per image, per thousand images |
13//! | [`AudioMillis`](UsageUnit::AudioMillis) | Milliseconds of audio processed or produced | Per hour, per minute |
14//! | [`VideoMillis`](UsageUnit::VideoMillis) | Milliseconds of video processed or produced | Per second |
15//! | [`Characters`](UsageUnit::Characters) | Characters of text synthesized or translated | Per thousand characters |
16//! | [`Pages`](UsageUnit::Pages) | Document pages processed | Per page |
17//! | [`Requests`](UsageUnit::Requests) | Requests billed as a whole | Per request |
18//! | [`Frames`](UsageUnit::Frames) | Video frames analysed | Per thousand frames, with a minimum per request |
19//!
20//! # Example
21//!
22//! ```
23//! use adk_core::{UnitRate, UsageUnit, UsageVector};
24//!
25//! // $0.18 per audio hour, billed in whole seconds rounded down.
26//! let rate = UnitRate::new(UsageUnit::AudioMillis, 180_000, 3_600_000).rounded_down_to(1_000);
27//! let usage = UsageVector::new().with(UsageUnit::AudioMillis, 90_400);
28//! assert_eq!(rate.cost_micro_usd(usage.get(UsageUnit::AudioMillis)), 4_500);
29//! assert_eq!(serde_json::to_value(&usage).unwrap(), serde_json::json!({ "audioMillis": 90_400 }));
30//! ```
31
32use std::collections::BTreeMap;
33use std::fmt;
34
35use serde::{Deserialize, Serialize};
36
37/// A unit a call's usage is counted and billed in.
38///
39/// Serialized in camelCase (`inputTokens`, `audioMillis`), the form quota and usage
40/// payloads key their maps by.
41///
42/// # Example
43///
44/// ```
45/// use adk_core::UsageUnit;
46///
47/// assert_eq!(UsageUnit::AudioMillis.as_str(), "audioMillis");
48/// assert_eq!(serde_json::from_str::<UsageUnit>("\"images\"").unwrap(), UsageUnit::Images);
49/// ```
50#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52#[non_exhaustive]
53pub enum UsageUnit {
54    /// Tokens sent to a model.
55    InputTokens,
56    /// Tokens a model generated, including thinking tokens.
57    OutputTokens,
58    /// Images generated, edited or analysed.
59    Images,
60    /// Milliseconds of audio processed or produced.
61    AudioMillis,
62    /// Milliseconds of video processed or produced.
63    VideoMillis,
64    /// Characters of text processed, such as text synthesized to speech.
65    Characters,
66    /// Document pages processed.
67    Pages,
68    /// Requests billed as a whole.
69    Requests,
70    /// Video frames analysed, such as frames a segmentation model tracked objects through.
71    Frames,
72}
73
74impl UsageUnit {
75    /// Every unit, in declaration order.
76    pub const ALL: [UsageUnit; 9] = [
77        Self::InputTokens,
78        Self::OutputTokens,
79        Self::Images,
80        Self::AudioMillis,
81        Self::VideoMillis,
82        Self::Characters,
83        Self::Pages,
84        Self::Requests,
85        Self::Frames,
86    ];
87
88    /// The unit's wire name.
89    pub const fn as_str(self) -> &'static str {
90        match self {
91            Self::InputTokens => "inputTokens",
92            Self::OutputTokens => "outputTokens",
93            Self::Images => "images",
94            Self::AudioMillis => "audioMillis",
95            Self::VideoMillis => "videoMillis",
96            Self::Characters => "characters",
97            Self::Pages => "pages",
98            Self::Requests => "requests",
99            Self::Frames => "frames",
100        }
101    }
102}
103
104impl fmt::Display for UsageUnit {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        f.write_str(self.as_str())
107    }
108}
109
110/// Usage counted per [`UsageUnit`].
111///
112/// Amounts add saturating; a unit with no usage is absent rather than zero, so two vectors
113/// that counted the same usage compare equal. Serialized as a map keyed by the unit's wire
114/// name.
115///
116/// # Example
117///
118/// ```
119/// use adk_core::{UsageUnit, UsageVector};
120///
121/// let mut total = UsageVector::new().with(UsageUnit::Images, 2);
122/// total.merge(&UsageVector::new().with(UsageUnit::Images, 1).with(UsageUnit::InputTokens, 40));
123/// assert_eq!(total.get(UsageUnit::Images), 3);
124/// assert_eq!(total.tokens(), 40);
125/// assert_eq!(total.get(UsageUnit::Pages), 0);
126/// ```
127#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(transparent)]
129pub struct UsageVector(BTreeMap<UsageUnit, u64>);
130
131impl UsageVector {
132    /// An empty vector.
133    pub fn new() -> Self {
134        Self::default()
135    }
136
137    /// Adds `amount` of `unit` and returns the vector.
138    pub fn with(mut self, unit: UsageUnit, amount: u64) -> Self {
139        self.add(unit, amount);
140        self
141    }
142
143    /// Adds `amount` of `unit`. A zero amount leaves the vector unchanged.
144    pub fn add(&mut self, unit: UsageUnit, amount: u64) {
145        if amount == 0 {
146            return;
147        }
148        let total = self.0.entry(unit).or_default();
149        *total = total.saturating_add(amount);
150    }
151
152    /// Adds every amount in `other`.
153    pub fn merge(&mut self, other: &UsageVector) {
154        for (unit, amount) in other.iter() {
155            self.add(unit, amount);
156        }
157    }
158
159    /// Takes every amount in `other` away, saturating at zero; a unit that reaches zero is
160    /// removed.
161    pub(crate) fn subtract(&mut self, other: &UsageVector) {
162        for (unit, amount) in other.iter() {
163            if let Some(total) = self.0.get_mut(&unit) {
164                *total = total.saturating_sub(amount);
165                if *total == 0 {
166                    self.0.remove(&unit);
167                }
168            }
169        }
170    }
171
172    /// The amount counted for `unit`, zero when none was.
173    pub fn get(&self, unit: UsageUnit) -> u64 {
174        self.0.get(&unit).copied().unwrap_or(0)
175    }
176
177    /// Input plus output tokens.
178    pub fn tokens(&self) -> u64 {
179        self.get(UsageUnit::InputTokens).saturating_add(self.get(UsageUnit::OutputTokens))
180    }
181
182    /// Returns `true` when no usage is counted.
183    pub fn is_empty(&self) -> bool {
184        self.0.is_empty()
185    }
186
187    /// Each unit with usage and its amount, in unit order.
188    pub fn iter(&self) -> impl Iterator<Item = (UsageUnit, u64)> + '_ {
189        self.0.iter().map(|(unit, amount)| (*unit, *amount))
190    }
191}
192
193impl FromIterator<(UsageUnit, u64)> for UsageVector {
194    fn from_iter<I: IntoIterator<Item = (UsageUnit, u64)>>(iter: I) -> Self {
195        let mut vector = Self::new();
196        for (unit, amount) in iter {
197            vector.add(unit, amount);
198        }
199        vector
200    }
201}
202
203/// A price per unit of usage: `micro_usd` for every `per` units of `unit`.
204///
205/// `granularity` is the billing step: usage is billed in whole multiples of it, rounded
206/// down, as a vendor billing "whole seconds, rounded down" bills audio milliseconds in
207/// steps of 1,000. `minimum_per_request` is the least a request that uses the unit at all
208/// is billed for, as a vendor billing "at least 50 frames per video request" does. The cost
209/// of the billed amount rounds up to a whole micro-USD.
210///
211/// # Example
212///
213/// ```
214/// use adk_core::{UnitRate, UsageUnit};
215///
216/// // $2.50 per 1,000 images.
217/// let rate = UnitRate::new(UsageUnit::Images, 2_500_000, 1_000);
218/// assert_eq!(rate.cost_micro_usd(3), 7_500);
219/// assert_eq!(rate.cost_micro_usd(0), 0);
220///
221/// // $0.20 per 1,000 frames, at least 50 frames per request.
222/// let frames = UnitRate::new(UsageUnit::Frames, 200_000, 1_000).with_minimum_per_request(50);
223/// assert_eq!(frames.cost_micro_usd(12), 10_000);
224/// assert_eq!(frames.cost_micro_usd(900), 180_000);
225/// ```
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
227#[serde(rename_all = "camelCase")]
228#[non_exhaustive]
229pub struct UnitRate {
230    /// The unit priced.
231    pub unit: UsageUnit,
232    /// Micro-USD charged for every [`per`](Self::per) units.
233    pub micro_usd: u64,
234    /// How many units [`micro_usd`](Self::micro_usd) buys. Never zero.
235    pub per: u64,
236    /// Usage is billed in whole multiples of this many units, rounded down. Never zero.
237    pub granularity: u64,
238    /// The fewest units a request that uses the unit is billed for; zero for no minimum.
239    #[serde(default, skip_serializing_if = "is_zero")]
240    pub minimum_per_request: u64,
241}
242
243fn is_zero(value: &u64) -> bool {
244    *value == 0
245}
246
247impl UnitRate {
248    /// `micro_usd` per `per` units of `unit`, every unit billed. A zero `per` is read as 1.
249    pub const fn new(unit: UsageUnit, micro_usd: u64, per: u64) -> Self {
250        Self {
251            unit,
252            micro_usd,
253            per: if per == 0 { 1 } else { per },
254            granularity: 1,
255            minimum_per_request: 0,
256        }
257    }
258
259    /// Bills usage in whole multiples of `granularity` units, rounded down. Zero is read as 1.
260    pub const fn rounded_down_to(mut self, granularity: u64) -> Self {
261        self.granularity = if granularity == 0 { 1 } else { granularity };
262        self
263    }
264
265    /// Bills every request that uses the unit for at least `minimum` units.
266    pub const fn with_minimum_per_request(mut self, minimum: u64) -> Self {
267        self.minimum_per_request = minimum;
268        self
269    }
270
271    /// The cost in micro-USD of one request that used `amount` units, saturating at
272    /// `u64::MAX`.
273    ///
274    /// The amount is rounded down to the billing granularity, then raised to the
275    /// per-request minimum; a request that used none of the unit costs nothing.
276    pub fn cost_micro_usd(&self, amount: u64) -> u64 {
277        if amount == 0 {
278            return 0;
279        }
280        let granularity = self.granularity.max(1);
281        let billed = u128::from((amount / granularity * granularity).max(self.minimum_per_request));
282        let cost = (billed * u128::from(self.micro_usd)).div_ceil(u128::from(self.per.max(1)));
283        u64::try_from(cost).unwrap_or(u64::MAX)
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn every_unit_round_trips_through_its_wire_name() {
293        for unit in UsageUnit::ALL {
294            let json = serde_json::to_value(unit).unwrap();
295            assert_eq!(json, serde_json::Value::String(unit.as_str().to_string()));
296            assert_eq!(serde_json::from_value::<UsageUnit>(json).unwrap(), unit);
297        }
298    }
299
300    #[test]
301    fn zero_amounts_are_absent_and_vectors_compare_by_usage() {
302        let counted = UsageVector::new().with(UsageUnit::Images, 0).with(UsageUnit::Pages, 2);
303        assert_eq!(counted, UsageVector::from_iter([(UsageUnit::Pages, 2)]));
304        assert!(UsageVector::new().with(UsageUnit::Images, 0).is_empty());
305    }
306
307    #[test]
308    fn amounts_saturate() {
309        let mut vector = UsageVector::new().with(UsageUnit::Characters, u64::MAX);
310        vector.add(UsageUnit::Characters, 5);
311        assert_eq!(vector.get(UsageUnit::Characters), u64::MAX);
312    }
313
314    #[test]
315    fn a_vector_deserializes_from_a_wire_map() {
316        let vector: UsageVector =
317            serde_json::from_value(serde_json::json!({ "images": 3, "audioMillis": 1_500 }))
318                .unwrap();
319        assert_eq!(
320            vector,
321            UsageVector::new().with(UsageUnit::Images, 3).with(UsageUnit::AudioMillis, 1_500)
322        );
323    }
324
325    #[test]
326    fn whole_second_billing_rounds_down_before_pricing() {
327        let rate = UnitRate::new(UsageUnit::AudioMillis, 180_000, 3_600_000).rounded_down_to(1_000);
328        assert_eq!(rate.cost_micro_usd(999), 0);
329        assert_eq!(rate.cost_micro_usd(1_000), 50);
330        assert_eq!(rate.cost_micro_usd(30_400), 1_500);
331        assert_eq!(rate.cost_micro_usd(3_600_000), 180_000);
332    }
333
334    #[test]
335    fn a_per_request_minimum_bills_small_requests_at_the_minimum() {
336        let rate = UnitRate::new(UsageUnit::Frames, 200_000, 1_000).with_minimum_per_request(50);
337        assert_eq!(rate.cost_micro_usd(0), 0);
338        assert_eq!(rate.cost_micro_usd(1), 10_000);
339        assert_eq!(rate.cost_micro_usd(50), 10_000);
340        assert_eq!(rate.cost_micro_usd(51), 10_200);
341        assert_eq!(rate.cost_micro_usd(1_800), 360_000);
342        // The minimum lifts what granularity rounds down to nothing.
343        let seconds = UnitRate::new(UsageUnit::AudioMillis, 180_000, 3_600_000)
344            .rounded_down_to(1_000)
345            .with_minimum_per_request(15_000);
346        assert_eq!(seconds.cost_micro_usd(400), 750);
347    }
348
349    #[test]
350    fn a_rate_without_a_minimum_keeps_its_wire_form() {
351        let rate = UnitRate::new(UsageUnit::Images, 2_500_000, 1_000);
352        let json = serde_json::json!({
353            "unit": "images", "microUsd": 2_500_000, "per": 1_000, "granularity": 1
354        });
355        assert_eq!(serde_json::to_value(rate).unwrap(), json);
356        assert_eq!(serde_json::from_value::<UnitRate>(json).unwrap(), rate);
357        let floored = rate.with_minimum_per_request(50);
358        let json = serde_json::to_value(floored).unwrap();
359        assert_eq!(json["minimumPerRequest"], 50);
360        assert_eq!(serde_json::from_value::<UnitRate>(json).unwrap(), floored);
361    }
362
363    #[test]
364    fn subtracting_removes_units_that_reach_zero() {
365        let mut vector = UsageVector::new().with(UsageUnit::Images, 3).with(UsageUnit::Frames, 2);
366        vector.subtract(&UsageVector::new().with(UsageUnit::Images, 1).with(UsageUnit::Frames, 5));
367        assert_eq!(vector, UsageVector::new().with(UsageUnit::Images, 2));
368        vector.subtract(&UsageVector::new().with(UsageUnit::Pages, 4));
369        assert_eq!(vector, UsageVector::new().with(UsageUnit::Images, 2));
370    }
371
372    #[test]
373    fn a_fractional_micro_usd_rounds_up_and_huge_amounts_saturate() {
374        let rate = UnitRate::new(UsageUnit::Characters, 1, 3);
375        assert_eq!(rate.cost_micro_usd(1), 1);
376        assert_eq!(rate.cost_micro_usd(3), 1);
377        assert_eq!(rate.cost_micro_usd(4), 2);
378        assert_eq!(UnitRate::new(UsageUnit::Images, u64::MAX, 1).cost_micro_usd(2), u64::MAX);
379    }
380}