Skip to main content

agent_metering/
usage.rs

1//! Normalized, provider-independent usage records and attribution.
2
3use std::collections::BTreeMap;
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8use uuid::Uuid;
9
10/// A resource quantity together with the provenance of that quantity.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(tag = "source", content = "value", rename_all = "snake_case")]
13pub enum MeteredValue {
14    /// Explicitly reported by the provider.
15    Reported(u64),
16    /// Calculated by the platform or estimated from available information.
17    Estimated(u64),
18    /// The provider did not report this dimension, or it could not be derived.
19    Unavailable,
20}
21
22impl MeteredValue {
23    pub fn value(self) -> Option<u64> {
24        match self {
25            Self::Reported(value) | Self::Estimated(value) => Some(value),
26            Self::Unavailable => None,
27        }
28    }
29
30    pub fn is_estimated(self) -> bool {
31        matches!(self, Self::Estimated(_))
32    }
33}
34
35/// Named resource dimensions for one provider invocation.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct UsageDimensions {
38    dimensions: BTreeMap<String, MeteredValue>,
39}
40
41impl Default for UsageDimensions {
42    /// Standard dimensions start as unavailable, never as implicit zeroes.
43    fn default() -> Self {
44        Self {
45            dimensions: BTreeMap::from([
46                (Self::INPUT_TOKENS.into(), MeteredValue::Unavailable),
47                (Self::OUTPUT_TOKENS.into(), MeteredValue::Unavailable),
48                (Self::CACHED_INPUT_TOKENS.into(), MeteredValue::Unavailable),
49                (Self::REASONING_TOKENS.into(), MeteredValue::Unavailable),
50            ]),
51        }
52    }
53}
54
55impl UsageDimensions {
56    pub const INPUT_TOKENS: &'static str = "input_tokens";
57    pub const OUTPUT_TOKENS: &'static str = "output_tokens";
58    pub const CACHED_INPUT_TOKENS: &'static str = "cached_input_tokens";
59    pub const REASONING_TOKENS: &'static str = "reasoning_tokens";
60
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    pub fn with(mut self, name: impl Into<String>, value: MeteredValue) -> Self {
66        self.dimensions.insert(name.into(), value);
67        self
68    }
69
70    pub fn get(&self, name: &str) -> MeteredValue {
71        self.dimensions
72            .get(name)
73            .copied()
74            .unwrap_or(MeteredValue::Unavailable)
75    }
76
77    pub fn iter(&self) -> impl Iterator<Item = (&str, MeteredValue)> {
78        self.dimensions
79            .iter()
80            .map(|(name, value)| (name.as_str(), *value))
81    }
82
83    pub fn is_empty(&self) -> bool {
84        self.dimensions
85            .values()
86            .all(|value| *value == MeteredValue::Unavailable)
87    }
88}
89
90/// Provider-reported monetary cost, retained separately from calculated cost.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct ReportedCost {
93    /// Currency in integer micro-units (1 USD = 1,000,000 micros).
94    pub amount_micros: u64,
95    pub currency: String,
96}
97
98impl ReportedCost {
99    pub fn new(amount_micros: u64, currency: impl Into<String>) -> Result<Self, UsageRecordError> {
100        let currency = currency.into();
101        if currency.len() != 3 || !currency.bytes().all(|byte| byte.is_ascii_uppercase()) {
102            return Err(UsageRecordError::InvalidCurrency);
103        }
104        Ok(Self {
105            amount_micros,
106            currency,
107        })
108    }
109}
110
111/// Whether the provider invocation completed from the platform's perspective.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "snake_case")]
114pub enum InvocationOutcome {
115    Succeeded,
116    Failed,
117    TimedOut,
118    Cancelled,
119}
120
121/// Immutable accounting input for one model invocation.
122///
123/// Every retry/fallback attempt has its own invocation ID. This makes usage
124/// aggregation additive and prevents a successful retry from hiding a billable
125/// failed attempt.
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct UsageRecord {
128    pub invocation_id: Uuid,
129    pub run_id: Uuid,
130    pub iteration: u32,
131    pub agent: String,
132    pub principal_id: Option<String>,
133    pub provider: String,
134    pub model: String,
135    pub outcome: InvocationOutcome,
136    pub usage: UsageDimensions,
137    #[serde(default)]
138    pub reported_cost: Option<ReportedCost>,
139    pub occurred_at: DateTime<Utc>,
140}
141
142impl UsageRecord {
143    #[allow(clippy::too_many_arguments)]
144    pub fn new(
145        invocation_id: Uuid,
146        run_id: Uuid,
147        iteration: u32,
148        agent: impl Into<String>,
149        principal_id: Option<String>,
150        provider: impl Into<String>,
151        model: impl Into<String>,
152        outcome: InvocationOutcome,
153        usage: UsageDimensions,
154        occurred_at: DateTime<Utc>,
155    ) -> Result<Self, UsageRecordError> {
156        let agent = agent.into();
157        let provider = provider.into();
158        let model = model.into();
159        if agent.trim().is_empty() {
160            return Err(UsageRecordError::EmptyAttribution("agent"));
161        }
162        if provider.trim().is_empty() {
163            return Err(UsageRecordError::EmptyAttribution("provider"));
164        }
165        if model.trim().is_empty() {
166            return Err(UsageRecordError::EmptyAttribution("model"));
167        }
168        Ok(Self {
169            invocation_id,
170            run_id,
171            iteration,
172            agent,
173            principal_id,
174            provider,
175            model,
176            outcome,
177            usage,
178            reported_cost: None,
179            occurred_at,
180        })
181    }
182
183    pub fn with_reported_cost(mut self, cost: ReportedCost) -> Self {
184        self.reported_cost = Some(cost);
185        self
186    }
187}
188
189#[derive(Debug, Error, PartialEq, Eq)]
190pub enum UsageRecordError {
191    #[error("{0} attribution must not be empty")]
192    EmptyAttribution(&'static str),
193    #[error("currency must be a three-letter uppercase code")]
194    InvalidCurrency,
195}