Skip to main content

adk_core/
metering.rs

1//! Metering for every model call made on behalf of a run.
2//!
3//! `LlmAgent` and `CodeActAgent` turns, context compaction summaries, MCP sampling
4//! and LLM routing all go through a [`ModelCallScope`], which applies the run's
5//! [`BudgetTracker`] and spend ledger as two gates:
6//!
7//! | Step | Budget ([`RunConfig::budget_tracker`]) | Spend ledger ([`RunConfig::spend_ledger`]) |
8//! |------|----------------------------------------|--------------------------------------------|
9//! | Before the call | [`BudgetTracker::begin_model_call`] refuses a call over the limit | [`SpendLedger::reserve`] holds the call's upper-bound cost ([`Llm::max_cost_micro_usd`]) or refuses the call |
10//! | After the call | the call's usage and cost are counted once | the reported cost is committed under `LlmResponse::provider` |
11//! | Call failed | — | the hold is released |
12//!
13//! A refused call is never sent to the provider.
14//!
15//! # Hard caps
16//!
17//! The hold is an upper bound on the call's cost, so the committed cost never exceeds it
18//! and a spend cap is never overshot. A call the model cannot bound (an unpriced model)
19//! reserves [`UNBOUNDED_HOLD_MICRO_USD`]: any cap that covers the call refuses it, so it
20//! runs only where no cap applies, and commits its reported cost or the
21//! [`LlmSpendEstimate`] when it reports none.
22//!
23//! # Reaching the scope
24//!
25//! - [`ModelCallScope::generate`] meters one call explicitly.
26//! - [`ModelCallScope::within`] makes the scope current for a future; inside it,
27//!   [`generate_metered`] and [`MeteredLlm`] meter against it. The runner wraps
28//!   its compaction calls this way, the MCP client wraps sampling requests, and
29//!   `LlmAgent`, `CodeActAgent` and the realtime runtimes wrap every tool call in the
30//!   run's scope ([`ModelCallScope::within_tool`]).
31//!
32//! # Calls billed in units
33//!
34//! Image generation, transcription and speech synthesis are billed per image, per second
35//! of audio or per character, not per token. [`ModelCallScope::meter`] (or
36//! [`meter_usage`], against the current scope) applies the same two gates to them:
37//!
38//! | Step | Budget | Spend ledger |
39//! |------|--------|--------------|
40//! | Before the call | refuses when a limit is reached, when the call has no known price under a cost cap, or when [`UsageCall::units`] would take a unit past its cap ([`RunBudget::max_units`](crate::RunBudget::max_units)); otherwise holds those units | reserves [`UsageCall::max_cost_micro_usd`], or [`UNBOUNDED_HOLD_MICRO_USD`] without a price |
41//! | After the call | counts its cost, tokens and [`UsageVector`] in place of the units it held | commits [`MeteredUsage::cost_micro_usd`] |
42//! | Call failed | returns the units it held | the hold is released |
43//!
44//! Units are counted in the budget ([`BudgetTracker::units`]) and never in the ledger,
45//! whose amounts are micro-USD only. A unit call is not a model call.
46//!
47//! # Example
48//!
49//! ```
50//! use std::sync::Arc;
51//! use adk_core::{BudgetTracker, InMemorySpendLedger, ModelCallScope, RunBudget, RunConfig};
52//!
53//! let config = RunConfig::builder()
54//!     .spend_ledger(Arc::new(InMemorySpendLedger::default()))
55//!     .build();
56//! let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(10)));
57//! let scope = ModelCallScope::for_run(&config, "my-app", "assistant").with_budget(tracker);
58//! assert!(!scope.is_unmetered());
59//! assert_eq!(scope.spend_key("gemini-3.8-flash").unwrap().vendor.as_deref(), Some("gemini"));
60//! ```
61
62use std::fmt;
63use std::future::Future;
64use std::sync::Arc;
65
66use async_trait::async_trait;
67use futures::StreamExt;
68
69use crate::{
70    BudgetTracker, GovernanceControl, Llm, LlmRequest, LlmResponse, LlmResponseStream,
71    ReservationId, Result, RunConfig, SpendKey, SpendLedger, ToolContext, UsageVector,
72    budget::meter_stream, schema_adapter::SchemaAdapter, usd_to_micro_usd,
73};
74
75/// Hold reserved for a model call whose cost cannot be bounded.
76///
77/// It exceeds every cap, so a ledger refuses it wherever a limit covers the call, and it
78/// fits the signed 64-bit storage of the SQL ledgers.
79pub const UNBOUNDED_HOLD_MICRO_USD: u64 = i64::MAX as u64;
80
81/// What an unbounded model call commits when its response reports no cost.
82///
83/// Calls with a cost bound ([`Llm::max_cost_micro_usd`]) reserve and, when no cost is
84/// reported, commit that bound. A call without one reserves [`UNBOUNDED_HOLD_MICRO_USD`],
85/// which only an uncapped key accepts, and commits this estimate when its response
86/// reports no cost: `max_output_tokens × price` when the request caps output tokens and an
87/// output price is set, otherwise `per_call_micro_usd`.
88///
89/// # Example
90///
91/// ```rust
92/// use adk_core::{LlmRequest, LlmSpendEstimate};
93///
94/// let estimate = LlmSpendEstimate::per_call(20_000).with_output_price(10_000_000);
95/// let mut request = LlmRequest::new("gemini-3.8-flash", vec![]);
96/// assert_eq!(estimate.estimate(&request), 20_000);
97///
98/// request.config = Some(adk_core::GenerateContentConfig {
99///     max_output_tokens: Some(4_096),
100///     ..Default::default()
101/// });
102/// assert_eq!(estimate.estimate(&request), 40_960);
103/// ```
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct LlmSpendEstimate {
106    /// Reserved when the request has no output cap or no output price is set.
107    pub per_call_micro_usd: u64,
108    /// Output price in micro-USD per million tokens, applied to `max_output_tokens`.
109    pub output_micro_usd_per_million_tokens: Option<u64>,
110}
111
112impl LlmSpendEstimate {
113    /// Default per-call hold: 0.05 USD.
114    pub const DEFAULT_PER_CALL_MICRO_USD: u64 = 50_000;
115
116    /// Reserves a fixed amount before every call.
117    pub fn per_call(micro_usd: u64) -> Self {
118        Self { per_call_micro_usd: micro_usd, output_micro_usd_per_million_tokens: None }
119    }
120
121    /// Sizes the hold from the request's `max_output_tokens` at this output price.
122    pub fn with_output_price(mut self, micro_usd_per_million_tokens: u64) -> Self {
123        self.output_micro_usd_per_million_tokens = Some(micro_usd_per_million_tokens);
124        self
125    }
126
127    /// Returns the amount to reserve for `request`.
128    pub fn estimate(&self, request: &LlmRequest) -> u64 {
129        let max_output_tokens = request
130            .config
131            .as_ref()
132            .and_then(|config| config.max_output_tokens)
133            .and_then(|tokens| u64::try_from(tokens).ok());
134        match (max_output_tokens, self.output_micro_usd_per_million_tokens) {
135            (Some(tokens), Some(price)) => tokens.saturating_mul(price).div_ceil(1_000_000),
136            _ => self.per_call_micro_usd,
137        }
138    }
139}
140
141impl Default for LlmSpendEstimate {
142    fn default() -> Self {
143        Self::per_call(Self::DEFAULT_PER_CALL_MICRO_USD)
144    }
145}
146
147/// Vendor a model call is reserved under, read from the model id's family prefix.
148///
149/// The vendor must be known before the call so a vendor cap can refuse it. Ids routed
150/// through an aggregator name the model's maker, not the aggregator; the committed cost
151/// moves to the provider the response reports.
152///
153/// # Example
154///
155/// ```
156/// use adk_core::vendor_for_model;
157///
158/// assert_eq!(vendor_for_model("models/gemini-3.8-flash"), "gemini");
159/// assert_eq!(vendor_for_model("grok-4.6"), "xai");
160/// assert_eq!(vendor_for_model("muse-spark-1.3"), "muse");
161/// assert_eq!(vendor_for_model("my-fine-tune"), "unknown");
162/// ```
163pub fn vendor_for_model(model: &str) -> &'static str {
164    let name = model.rsplit('/').next().unwrap_or(model).to_ascii_lowercase();
165    let starts = |prefixes: &[&str]| prefixes.iter().any(|prefix| name.starts_with(prefix));
166    if starts(&["gemini"]) {
167        "gemini"
168    } else if starts(&["claude"]) {
169        "anthropic"
170    } else if starts(&["gpt-", "chatgpt", "o1", "o3", "o4", "codex"]) {
171        "openai"
172    } else if starts(&["deepseek"]) {
173        "deepseek"
174    } else if starts(&["grok"]) {
175        "xai"
176    } else if starts(&["mistral", "magistral", "codestral", "devstral", "ministral", "pixtral"]) {
177        "mistral"
178    } else if starts(&["muse-"]) {
179        "muse"
180    } else {
181        "unknown"
182    }
183}
184
185/// A spend-ledger hold for one model call, settled from the responses it observes.
186///
187/// | What the hold observed | Ledger action on [`settle`](Self::settle) |
188/// |------------------------|--------------------------------------------|
189/// | A response reporting `usage_metadata.cost` | Commit that cost |
190/// | Responses, but no cost | Commit the estimate and log a warning |
191/// | No response (the call failed) | Release |
192///
193/// When a response names a provider other than the reserved vendor (for example `bedrock`
194/// serving a Claude model), the cost is committed under that provider. If a limit refuses
195/// even a zero-amount reservation under the reported provider, the cost is committed under
196/// the reserved vendor instead and a warning is logged.
197///
198/// A hold dropped unsettled settles on the current Tokio runtime; outside a runtime it
199/// expires by the ledger's reservation TTL.
200///
201/// # Example
202///
203/// ```
204/// use std::sync::Arc;
205/// use adk_core::{InMemorySpendLedger, LlmResponse, ModelSpendHold, SpendKey, SpendLedger, SpendPeriod, UsageMetadata};
206///
207/// # async fn demo() -> adk_core::Result<()> {
208/// let ledger = Arc::new(InMemorySpendLedger::default());
209/// let key = SpendKey::org("acme").with_vendor("gemini");
210/// let mut hold = ModelSpendHold::reserve(ledger.clone(), key, 50_000).await?;
211///
212/// let mut response = LlmResponse::default();
213/// response.usage_metadata = Some(UsageMetadata { cost: Some(0.002), ..Default::default() });
214/// hold.observe(&response);
215/// hold.settle().await;
216/// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 2_000);
217/// # Ok(())
218/// # }
219/// ```
220pub struct ModelSpendHold {
221    inner: Option<HoldState>,
222}
223
224struct HoldState {
225    ledger: Arc<dyn SpendLedger>,
226    reservation: ReservationId,
227    key: SpendKey,
228    estimate: u64,
229    saw_response: bool,
230    cost_micro_usd: Option<u64>,
231    provider: Option<String>,
232}
233
234impl fmt::Debug for ModelSpendHold {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        let mut debug = f.debug_struct("ModelSpendHold");
237        if let Some(state) = &self.inner {
238            debug
239                .field("reservation", &state.reservation)
240                .field("key", &state.key)
241                .field("estimate", &state.estimate)
242                .field("cost_micro_usd", &state.cost_micro_usd);
243        }
244        debug.finish_non_exhaustive()
245    }
246}
247
248impl ModelSpendHold {
249    /// Reserves `estimate_micro_usd` under `key`.
250    ///
251    /// # Errors
252    ///
253    /// Returns the ledger's error, such as [`SPEND_LIMIT_EXCEEDED_CODE`](crate::SPEND_LIMIT_EXCEEDED_CODE),
254    /// when the reservation is refused.
255    pub async fn reserve(
256        ledger: Arc<dyn SpendLedger>,
257        key: SpendKey,
258        estimate_micro_usd: u64,
259    ) -> Result<Self> {
260        let reservation = ledger.reserve(&key, estimate_micro_usd).await.inspect_err(|error| {
261            tracing::warn!(error = %error, spend.key = %key, "model call refused by spend ledger");
262        })?;
263        Ok(Self {
264            inner: Some(HoldState {
265                ledger,
266                reservation,
267                key,
268                estimate: estimate_micro_usd,
269                saw_response: false,
270                cost_micro_usd: None,
271                provider: None,
272            }),
273        })
274    }
275
276    /// Commits `micro_usd`, instead of the reserved amount, when no response reports a cost.
277    pub fn with_unpriced_commit(mut self, micro_usd: u64) -> Self {
278        if let Some(state) = self.inner.as_mut() {
279            state.estimate = micro_usd;
280        }
281        self
282    }
283
284    /// The key the hold was reserved under.
285    pub fn key(&self) -> Option<&SpendKey> {
286        self.inner.as_ref().map(|state| &state.key)
287    }
288
289    /// Records the cost and provider a response reports.
290    pub fn observe(&mut self, response: &LlmResponse) {
291        let Some(state) = self.inner.as_mut() else {
292            return;
293        };
294        state.saw_response = true;
295        if let Some(cost) = response.usage_metadata.as_ref().and_then(|usage| usage.cost) {
296            state.cost_micro_usd = usd_to_micro_usd(cost);
297        }
298        if let Some(provider) = &response.provider {
299            state.provider = Some(provider.clone());
300        }
301    }
302
303    /// Records that the call completed at `cost_micro_usd`, or at an unknown cost.
304    ///
305    /// For calls that report no [`LlmResponse`], such as the unit-billed calls of
306    /// [`ModelCallScope::meter`].
307    ///
308    /// # Example
309    ///
310    /// ```
311    /// use std::sync::Arc;
312    /// use adk_core::{InMemorySpendLedger, ModelSpendHold, SpendKey, SpendLedger, SpendPeriod};
313    ///
314    /// # async fn demo() -> adk_core::Result<()> {
315    /// let ledger = Arc::new(InMemorySpendLedger::default());
316    /// let mut hold = ModelSpendHold::reserve(ledger.clone(), SpendKey::org("acme"), 20_000).await?;
317    /// hold.observe_cost(Some(10_000));
318    /// hold.settle().await;
319    /// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 10_000);
320    /// # Ok(())
321    /// # }
322    /// ```
323    pub fn observe_cost(&mut self, cost_micro_usd: Option<u64>) {
324        let Some(state) = self.inner.as_mut() else {
325            return;
326        };
327        state.saw_response = true;
328        if cost_micro_usd.is_some() {
329            state.cost_micro_usd = cost_micro_usd;
330        }
331    }
332
333    /// Commits the observed cost, or releases the hold when no response arrived.
334    ///
335    /// Returns the provider the cost was reported under when it differs from the reserved
336    /// vendor, so a caller can reserve later calls of the same model under it.
337    pub async fn settle(mut self) -> Option<String> {
338        let state = self.inner.take()?;
339        state.settle().await
340    }
341}
342
343impl HoldState {
344    async fn settle(self) -> Option<String> {
345        let Self { ledger, reservation, key, estimate, saw_response, cost_micro_usd, provider } =
346            self;
347        if !saw_response {
348            if let Err(error) = ledger.release(reservation).await {
349                tracing::warn!(error = %error, spend.key = %key, "failed to release model spend reservation");
350            }
351            return None;
352        }
353        let amount = match cost_micro_usd {
354            Some(amount) => amount,
355            // A model that bounds its cost at zero, such as local inference, reports none.
356            None if estimate == 0 => {
357                tracing::debug!(
358                    spend.key = %key,
359                    "model response reported no cost; committing its zero bound"
360                );
361                0
362            }
363            None => {
364                tracing::warn!(
365                    spend.key = %key,
366                    spend.estimate_micro_usd = estimate,
367                    "model response reported no cost; committing the reserved bound or estimate"
368                );
369                estimate
370            }
371        };
372        let reported = provider.filter(|provider| key.vendor.as_deref() != Some(provider));
373        if let Some(provider) = &reported {
374            let corrected = key.clone().with_vendor(provider.clone());
375            // A zero hold places the committed cost under the reported provider; the
376            // estimate's hold is released only once the cost is recorded there.
377            match ledger.reserve(&corrected, 0).await {
378                Ok(corrected_reservation) => {
379                    match ledger.commit(corrected_reservation, amount).await {
380                        Ok(()) => {
381                            if let Err(error) = ledger.release(reservation).await {
382                                tracing::warn!(error = %error, spend.key = %key, "failed to release model spend reservation");
383                            }
384                            return reported;
385                        }
386                        Err(error) => tracing::warn!(
387                            error = %error,
388                            spend.key = %corrected,
389                            "failed to commit model spend under the reported provider; committing under the reserved vendor"
390                        ),
391                    }
392                }
393                Err(error) => tracing::warn!(
394                    error = %error,
395                    spend.key = %corrected,
396                    "spend ledger refused the reported provider; committing under the reserved vendor"
397                ),
398            }
399        }
400        if let Err(error) = ledger.commit(reservation, amount).await {
401            tracing::error!(
402                error = %error,
403                spend.key = %key,
404                spend.amount_micro_usd = amount,
405                "failed to commit model spend"
406            );
407        }
408        reported
409    }
410}
411
412impl Drop for ModelSpendHold {
413    fn drop(&mut self) {
414        let Some(state) = self.inner.take() else {
415            return;
416        };
417        match tokio::runtime::Handle::try_current() {
418            Ok(handle) => {
419                handle.spawn(async move {
420                    state.settle().await;
421                });
422            }
423            Err(_) => tracing::warn!(
424                spend.key = %state.key,
425                "model spend hold dropped outside a tokio runtime; it expires by TTL"
426            ),
427        }
428    }
429}
430
431/// Spend attribution for the model calls of a [`ModelCallScope`].
432#[derive(Clone)]
433struct SpendScope {
434    ledger: Arc<dyn SpendLedger>,
435    org: String,
436    agent: Option<String>,
437    estimate: LlmSpendEstimate,
438}
439
440/// The budget and spend ledger that model calls made on behalf of a run count against.
441///
442/// Built from a run's [`RunConfig`] with [`for_run`](Self::for_run), or assembled
443/// explicitly for calls made outside any run. An empty scope meters nothing.
444///
445/// # Example
446///
447/// ```
448/// use std::sync::Arc;
449/// use adk_core::{BudgetTracker, InMemorySpendLedger, ModelCallScope, RunBudget};
450///
451/// let scope = ModelCallScope::new()
452///     .with_budget(Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(1.0))))
453///     .with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme")
454///     .with_agent("mcp-sampling");
455/// assert_eq!(scope.spend_key("claude-haiku-4-5").unwrap().agent.as_deref(), Some("mcp-sampling"));
456/// ```
457#[derive(Clone, Default)]
458pub struct ModelCallScope {
459    budget: Option<Arc<BudgetTracker>>,
460    spend: Option<SpendScope>,
461    governance: Vec<GovernanceControl>,
462}
463
464impl fmt::Debug for ModelCallScope {
465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466        f.debug_struct("ModelCallScope")
467            .field("budget", &self.budget.as_ref().map(|tracker| tracker.budget()))
468            .field("spend_org", &self.spend.as_ref().map(|spend| spend.org.as_str()))
469            .field("spend_agent", &self.spend.as_ref().and_then(|spend| spend.agent.as_deref()))
470            .field("governance", &self.governance.len())
471            .finish()
472    }
473}
474
475tokio::task_local! {
476    static CURRENT_SCOPE: ModelCallScope;
477}
478
479impl ModelCallScope {
480    /// Creates a scope that meters nothing.
481    pub fn new() -> Self {
482        Self::default()
483    }
484
485    /// Creates the scope for calls made on behalf of a run.
486    ///
487    /// Uses the run's [`budget_tracker`](RunConfig::budget_tracker), its
488    /// [`spend_ledger`](RunConfig::spend_ledger),
489    /// [`llm_spend_estimate`](RunConfig::llm_spend_estimate) and kill switches
490    /// ([`governance`](RunConfig::governance)). Spend is attributed to
491    /// `org` (the runner passes its app name) and the [`AgentId`](crate::AgentId) the
492    /// agent named `agent_name` acts as
493    /// ([`ActingConfig::principal_for`](crate::ActingConfig::principal_for): the
494    /// configured principal, or `urn:adk:agent:{org}/{agent_name}`).
495    pub fn for_run(config: &RunConfig, org: &str, agent_name: &str) -> Self {
496        Self {
497            budget: config.budget_tracker.clone(),
498            spend: config.spend_ledger.clone().map(|ledger| SpendScope {
499                ledger,
500                org: org.to_string(),
501                agent: Some(config.acting.principal_for(org, agent_name).id.into()),
502                estimate: config.llm_spend_estimate.unwrap_or_default(),
503            }),
504            governance: config.governance.clone(),
505        }
506    }
507
508    /// Refuses every call while `control` is frozen.
509    ///
510    /// The scope checks its kill switches before each call it meters, so a call that
511    /// makes several provider calls, such as a [fallback chain](Llm::generate_content_metered),
512    /// stops at the next one once a switch is frozen.
513    ///
514    /// # Example
515    ///
516    /// ```
517    /// use adk_core::{GOVERNANCE_FROZEN_CODE, GovernanceControl, ModelCallScope};
518    ///
519    /// let control = GovernanceControl::new();
520    /// let scope = ModelCallScope::new().with_governance(control.clone());
521    /// assert!(scope.check_governance().is_ok());
522    /// control.freeze("incident");
523    /// assert_eq!(scope.check_governance().unwrap_err().code, GOVERNANCE_FROZEN_CODE);
524    /// ```
525    pub fn with_governance(mut self, control: GovernanceControl) -> Self {
526        if !self.governance.iter().any(|existing| existing.same_as(&control)) {
527            self.governance.push(control);
528        }
529        self
530    }
531
532    /// Returns the error of the first frozen kill switch, if any.
533    ///
534    /// # Errors
535    ///
536    /// Returns the frozen control's `governance.frozen` error
537    /// ([`GovernanceControl::check`]).
538    pub fn check_governance(&self) -> Result<()> {
539        self.governance.iter().try_for_each(GovernanceControl::check)
540    }
541
542    /// Counts calls against `tracker`.
543    pub fn with_budget(mut self, tracker: Arc<BudgetTracker>) -> Self {
544        self.budget = Some(tracker);
545        self
546    }
547
548    /// Reserves and commits call spend in `ledger`, attributed to `org`.
549    pub fn with_spend_ledger(
550        mut self,
551        ledger: Arc<dyn SpendLedger>,
552        org: impl Into<String>,
553    ) -> Self {
554        self.spend = Some(SpendScope {
555            ledger,
556            org: org.into(),
557            agent: self.spend.as_ref().and_then(|spend| spend.agent.clone()),
558            estimate: self.spend.as_ref().map(|spend| spend.estimate).unwrap_or_default(),
559        });
560        self
561    }
562
563    /// Attributes spend to `agent`. Has no effect without a spend ledger.
564    pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
565        if let Some(spend) = self.spend.as_mut() {
566            spend.agent = Some(agent.into());
567        }
568        self
569    }
570
571    /// Sets the hold reserved before each call. Has no effect without a spend ledger.
572    pub fn with_spend_estimate(mut self, estimate: LlmSpendEstimate) -> Self {
573        if let Some(spend) = self.spend.as_mut() {
574            spend.estimate = estimate;
575        }
576        self
577    }
578
579    /// The budget tracker calls count against.
580    pub fn budget(&self) -> Option<&Arc<BudgetTracker>> {
581        self.budget.as_ref()
582    }
583
584    /// Returns `true` when the scope has neither a budget nor a spend ledger.
585    pub fn is_unmetered(&self) -> bool {
586        self.budget.is_none() && self.spend.is_none()
587    }
588
589    /// The key a call to `model` reserves under, when the scope has a spend ledger.
590    pub fn spend_key(&self, model: &str) -> Option<SpendKey> {
591        self.vendor_spend_key(vendor_for_model(model))
592    }
593
594    /// The key a call billed by `vendor` reserves under, when the scope has a spend ledger.
595    ///
596    /// # Example
597    ///
598    /// ```
599    /// use std::sync::Arc;
600    /// use adk_core::{InMemorySpendLedger, ModelCallScope};
601    ///
602    /// let scope = ModelCallScope::new().with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme");
603    /// assert_eq!(scope.vendor_spend_key("muse").unwrap().vendor.as_deref(), Some("muse"));
604    /// assert!(ModelCallScope::new().vendor_spend_key("muse").is_none());
605    /// ```
606    pub fn vendor_spend_key(&self, vendor: &str) -> Option<SpendKey> {
607        let spend = self.spend.as_ref()?;
608        let key = SpendKey::org(&spend.org).with_vendor(vendor);
609        Some(match &spend.agent {
610            Some(agent) => key.with_agent(agent.clone()),
611            None => key,
612        })
613    }
614
615    /// The scope of the run a tool call belongs to, when the tool's runtime exposes the
616    /// run's [`RunConfig`] ([`ToolContext::run_config`]).
617    ///
618    /// Spend is attributed to the context's app and the agent making the call, as
619    /// [`for_run`](Self::for_run) attributes it.
620    ///
621    /// # Example
622    ///
623    /// ```rust,ignore
624    /// let scope = adk_core::ModelCallScope::for_tool(ctx.as_ref());
625    /// ```
626    pub fn for_tool(ctx: &dyn ToolContext) -> Option<Self> {
627        ctx.run_config().map(|config| Self::for_run(config, ctx.app_name(), ctx.agent_name()))
628    }
629
630    /// Runs a tool call with the scope of the run it belongs to current
631    /// ([`for_tool`](Self::for_tool)), so the media and model calls the tool makes through
632    /// [`meter_usage`] and [`generate_metered`] count against the run. Without a run
633    /// configuration on `ctx`, `future` runs as is.
634    ///
635    /// Agents call this around every tool execution.
636    ///
637    /// # Example
638    ///
639    /// ```rust,ignore
640    /// let result = ModelCallScope::within_tool(ctx.as_ref(), tool.execute(ctx.clone(), args)).await;
641    /// ```
642    pub fn within_tool<F: Future>(
643        ctx: &dyn ToolContext,
644        future: F,
645    ) -> impl Future<Output = F::Output> + use<F> {
646        let scope = Self::for_tool(ctx);
647        async move {
648            match scope {
649                Some(scope) => scope.within(future).await,
650                None => future.await,
651            }
652        }
653    }
654
655    /// Returns `true` when both scopes count against the same budget and ledger.
656    pub fn same_as(&self, other: &Self) -> bool {
657        let budget = match (&self.budget, &other.budget) {
658            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
659            (None, None) => true,
660            _ => false,
661        };
662        let spend = match (&self.spend, &other.spend) {
663            (Some(a), Some(b)) => {
664                Arc::ptr_eq(&a.ledger, &b.ledger) && a.org == b.org && a.agent == b.agent
665            }
666            (None, None) => true,
667            _ => false,
668        };
669        budget && spend
670    }
671
672    /// The scope made current by an enclosing [`within`](Self::within), if any.
673    pub fn current() -> Option<Self> {
674        CURRENT_SCOPE.try_with(Clone::clone).ok()
675    }
676
677    /// Runs `future` with this scope current, so [`generate_metered`] and [`MeteredLlm`]
678    /// inside it meter against this scope.
679    ///
680    /// The scope does not follow work spawned onto other tasks.
681    pub async fn within<F: Future>(self, future: F) -> F::Output {
682        CURRENT_SCOPE.scope(self, future).await
683    }
684
685    /// Calls `model` under this scope.
686    ///
687    /// Refuses the call while one of the scope's kill switches is frozen
688    /// ([`with_governance`](Self::with_governance)), then hands it to
689    /// [`Llm::generate_content_metered`], which meters it as one model call
690    /// ([`generate_one_call`](Self::generate_one_call)) unless the model sends the request
691    /// to several providers and meters each of their calls itself.
692    ///
693    /// # Errors
694    ///
695    /// Returns the frozen control's `governance.frozen` error, the ledger's error when the
696    /// reservation is refused, a [`ResourceExhausted`](crate::ErrorCategory::ResourceExhausted)
697    /// error when the budget does not allow another call, or the model's own error.
698    pub async fn generate(
699        &self,
700        model: &dyn Llm,
701        request: LlmRequest,
702        stream: bool,
703    ) -> Result<LlmResponseStream> {
704        self.check_governance()?;
705        if self.is_unmetered() && self.governance.is_empty() {
706            return model.generate_content(request, stream).await;
707        }
708        model.generate_content_metered(self, request, stream).await
709    }
710
711    /// Meters one call to `model` as one model call.
712    ///
713    /// Reserves the call's upper-bound cost ([`Llm::max_cost_micro_usd`], or
714    /// [`UNBOUNDED_HOLD_MICRO_USD`] when there is none), then the budget's model call,
715    /// before the request is sent; a refusal from either stops the call. The returned
716    /// stream counts the call's usage once and commits its cost at the turn-complete
717    /// response, or when the stream ends or is dropped. The spend is reserved under the
718    /// vendor of `request.model` ([`vendor_for_model`]) and committed under the provider
719    /// the response reports.
720    ///
721    /// This is what [`Llm::generate_content_metered`] does unless a model overrides it.
722    ///
723    /// # Errors
724    ///
725    /// Returns the ledger's error when the reservation is refused, a
726    /// [`ResourceExhausted`](crate::ErrorCategory::ResourceExhausted) error when the
727    /// budget does not allow another call, or the model's own error.
728    pub async fn generate_one_call<M: Llm + ?Sized>(
729        &self,
730        model: &M,
731        request: LlmRequest,
732        stream: bool,
733    ) -> Result<LlmResponseStream> {
734        if self.is_unmetered() {
735            return model.generate_content(request, stream).await;
736        }
737        let hold = match (&self.spend, self.spend_key(&request.model)) {
738            (Some(spend), Some(key)) => Some(match model.max_cost_micro_usd(&request) {
739                Some(bound) => ModelSpendHold::reserve(spend.ledger.clone(), key, bound).await?,
740                None => {
741                    ModelSpendHold::reserve(spend.ledger.clone(), key, UNBOUNDED_HOLD_MICRO_USD)
742                        .await?
743                        .with_unpriced_commit(spend.estimate.estimate(&request))
744                }
745            }),
746            _ => None,
747        };
748        let meter = match self.budget.as_ref().map(|tracker| tracker.begin_model_call(model.name()))
749        {
750            Some(Ok(meter)) => Some(meter),
751            Some(Err(exceeded)) => {
752                // A hold that saw no response is released.
753                if let Some(hold) = hold {
754                    hold.settle().await;
755                }
756                return Err(exceeded.into());
757            }
758            None => None,
759        };
760        let responses = match model.generate_content(request, stream).await {
761            Ok(responses) => responses,
762            Err(error) => {
763                if let Some(hold) = hold {
764                    hold.settle().await;
765                }
766                return Err(error);
767            }
768        };
769        let responses = match meter {
770            Some(meter) => meter_stream(responses, meter),
771            None => responses,
772        };
773        Ok(match hold {
774            Some(hold) => commit_on_completion(responses, hold),
775            None => responses,
776        })
777    }
778}
779
780impl ModelCallScope {
781    /// Checks the budget and reserves the spend for one call billed in units.
782    ///
783    /// Reserves [`UsageCall::max_cost_micro_usd`] in the spend ledger — or
784    /// [`UNBOUNDED_HOLD_MICRO_USD`] when the call has no known price, which every covering
785    /// cap refuses — then checks the run budget, which refuses a call with no known price
786    /// under a cost cap, and holds [`UsageCall::units`] against its per-unit caps. Settle
787    /// the returned hold with [`UsageHold::commit`] once the call completes; a hold released
788    /// or dropped unsettled records nothing and returns the units it held.
789    ///
790    /// # Errors
791    ///
792    /// Returns the frozen control's `governance.frozen` error while a kill switch is frozen,
793    /// the ledger's error when the reservation is refused, or a
794    /// [`ResourceExhausted`](crate::ErrorCategory::ResourceExhausted) error when the
795    /// budget refuses the call — `budget.units`, naming the unit and its cap, when a
796    /// declared unit does not fit. Nothing has been sent when any of them refuses.
797    pub async fn begin_usage(&self, call: &UsageCall) -> Result<UsageHold> {
798        self.check_governance()?;
799        let spend = match (&self.spend, self.vendor_spend_key(&call.vendor)) {
800            (Some(spend), Some(key)) => Some(match call.max_cost_micro_usd {
801                Some(bound) => ModelSpendHold::reserve(spend.ledger.clone(), key, bound).await?,
802                None => {
803                    ModelSpendHold::reserve(spend.ledger.clone(), key, UNBOUNDED_HOLD_MICRO_USD)
804                        .await?
805                        .with_unpriced_commit(spend.estimate.per_call_micro_usd)
806                }
807            }),
808            _ => None,
809        };
810        if let Some(tracker) = &self.budget
811            && let Err(exceeded) =
812                tracker.begin_usage(&call.model, call.max_cost_micro_usd.is_some(), &call.units)
813        {
814            if let Some(hold) = spend {
815                hold.settle().await;
816            }
817            return Err(exceeded.into());
818        }
819        Ok(UsageHold {
820            spend,
821            budget: self.budget.clone(),
822            model: call.model.clone(),
823            held: call.units.clone(),
824        })
825    }
826
827    /// Runs one call billed in units under this scope.
828    ///
829    /// `future` is the call: it returns its value with the [`MeteredUsage`] it incurred.
830    /// The budget is checked and the spend reserved before `future` is polled
831    /// ([`begin_usage`](Self::begin_usage)), the usage is committed when it succeeds, and
832    /// the hold is released when it fails. An unmetered scope runs `future` as is.
833    ///
834    /// # Errors
835    ///
836    /// A refusal from [`begin_usage`](Self::begin_usage), in which case `future` never
837    /// runs, or the error `future` returns.
838    ///
839    /// # Example
840    ///
841    /// ```
842    /// use std::sync::Arc;
843    /// use adk_core::{
844    ///     InMemorySpendLedger, MeteredUsage, ModelCallScope, SpendKey, SpendLedger, SpendLimits,
845    ///     SpendPeriod, UsageCall, UsageUnit, UsageVector,
846    /// };
847    ///
848    /// # async fn demo() -> adk_core::Result<()> {
849    /// let limits = SpendLimits::new().limit(SpendKey::org("acme").per(SpendPeriod::Day), 1_000_000);
850    /// let ledger = Arc::new(InMemorySpendLedger::new(limits));
851    /// let scope = ModelCallScope::new().with_spend_ledger(ledger.clone(), "acme");
852    ///
853    /// let call = UsageCall::new("muse", "muse-image-1.0").with_max_cost_micro_usd(10_000);
854    /// let image = scope
855    ///     .meter(call, async {
856    ///         let usage = MeteredUsage::new(UsageVector::new().with(UsageUnit::Images, 1))
857    ///             .with_cost_micro_usd(10_000);
858    ///         Ok(("image bytes", usage))
859    ///     })
860    ///     .await?;
861    /// assert_eq!(image, "image bytes");
862    /// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 10_000);
863    /// # Ok(())
864    /// # }
865    /// ```
866    pub async fn meter<T, F>(&self, call: UsageCall, future: F) -> Result<T>
867    where
868        F: Future<Output = Result<(T, MeteredUsage)>>,
869    {
870        if self.is_unmetered() {
871            self.check_governance()?;
872            return future.await.map(|(value, _)| value);
873        }
874        let hold = self.begin_usage(&call).await?;
875        match future.await {
876            Ok((value, usage)) => {
877                hold.commit(usage).await;
878                Ok(value)
879            }
880            Err(error) => {
881                hold.release().await;
882                Err(error)
883            }
884        }
885    }
886}
887
888/// One call billed in units: the vendor and model it is billed under, the most it can
889/// cost, and the most it can use of each unit.
890///
891/// # Example
892///
893/// ```
894/// use adk_core::{UsageCall, UsageUnit, UsageVector};
895///
896/// let call = UsageCall::new("muse", "muse-image-1.0")
897///     .with_max_cost_micro_usd(40_000)
898///     .with_units(UsageVector::new().with(UsageUnit::Images, 4));
899/// assert_eq!(call.max_cost_micro_usd, Some(40_000));
900/// assert_eq!(call.units.get(UsageUnit::Images), 4);
901/// assert_eq!(UsageCall::new("deepgram", "nova-3").max_cost_micro_usd, None);
902/// ```
903#[derive(Debug, Clone, PartialEq, Eq)]
904#[non_exhaustive]
905pub struct UsageCall {
906    /// The spend key vendor the call is reserved and committed under, such as `muse`.
907    pub vendor: String,
908    /// The model or service called, named in budget errors and logs.
909    pub model: String,
910    /// Upper bound on the call's cost, or `None` when no price is known.
911    pub max_cost_micro_usd: Option<u64>,
912    /// The most the call can use of each unit, held against the run budget's per-unit caps
913    /// ([`RunBudget::max_units`](crate::RunBudget::max_units)) before the call starts. Empty
914    /// when the call declares none, in which case no cap holds it back.
915    pub units: UsageVector,
916}
917
918impl UsageCall {
919    /// A call to `model`, billed by `vendor`, with no known price and no declared units.
920    pub fn new(vendor: impl Into<String>, model: impl Into<String>) -> Self {
921        Self {
922            vendor: vendor.into(),
923            model: model.into(),
924            max_cost_micro_usd: None,
925            units: UsageVector::new(),
926        }
927    }
928
929    /// Sets the most the call can cost.
930    pub fn with_max_cost_micro_usd(mut self, max_cost_micro_usd: u64) -> Self {
931        self.max_cost_micro_usd = Some(max_cost_micro_usd);
932        self
933    }
934
935    /// Declares the most the call can use of each unit. The run budget holds these before
936    /// the call starts and refuses the call when a unit would pass its cap.
937    pub fn with_units(mut self, units: UsageVector) -> Self {
938        self.units = units;
939        self
940    }
941}
942
943/// What one call billed in units used, and what it cost when the price is known.
944///
945/// # Example
946///
947/// ```
948/// use adk_core::{MeteredUsage, UsageUnit, UsageVector};
949///
950/// let usage = MeteredUsage::new(UsageVector::new().with(UsageUnit::AudioMillis, 90_000))
951///     .with_cost_micro_usd(4_500);
952/// assert_eq!(usage.units.get(UsageUnit::AudioMillis), 90_000);
953/// assert_eq!(usage.cost_micro_usd, Some(4_500));
954/// ```
955#[derive(Debug, Clone, Default, PartialEq, Eq)]
956#[non_exhaustive]
957pub struct MeteredUsage {
958    /// Usage per unit.
959    pub units: UsageVector,
960    /// Cost in micro-USD, or `None` when no price is known.
961    pub cost_micro_usd: Option<u64>,
962}
963
964impl MeteredUsage {
965    /// Usage of `units` at an unknown cost.
966    pub fn new(units: UsageVector) -> Self {
967        Self { units, cost_micro_usd: None }
968    }
969
970    /// Sets the cost.
971    pub fn with_cost_micro_usd(mut self, cost_micro_usd: u64) -> Self {
972        self.cost_micro_usd = Some(cost_micro_usd);
973        self
974    }
975}
976
977/// The open budget check and spend hold of one call billed in units, from
978/// [`ModelCallScope::begin_usage`].
979///
980/// | Settled with | Spend ledger | Budget |
981/// |--------------|--------------|--------|
982/// | [`commit`](Self::commit) | the reported cost, or the reserved bound (the scope's per-call estimate for an unpriced call) when none is reported | cost, tokens and units counted in place of the units held; an unknown cost under a cost cap stops the run |
983/// | [`release`](Self::release), or dropped | hold released | nothing counted; the units held are returned |
984#[must_use = "an unsettled usage hold records nothing"]
985pub struct UsageHold {
986    spend: Option<ModelSpendHold>,
987    budget: Option<Arc<BudgetTracker>>,
988    model: String,
989    held: UsageVector,
990}
991
992impl fmt::Debug for UsageHold {
993    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
994        f.debug_struct("UsageHold")
995            .field("spend", &self.spend)
996            .field("model", &self.model)
997            .field("held", &self.held)
998            .finish_non_exhaustive()
999    }
1000}
1001
1002impl UsageHold {
1003    /// Records what the call used, in place of the units it held.
1004    pub async fn commit(mut self, usage: MeteredUsage) {
1005        if let Some(tracker) = self.budget.take() {
1006            tracker.record_units(&self.model, &self.held, &usage.units, usage.cost_micro_usd);
1007        }
1008        if let Some(mut hold) = self.spend.take() {
1009            hold.observe_cost(usage.cost_micro_usd);
1010            hold.settle().await;
1011        }
1012    }
1013
1014    /// Releases the hold of a call that failed, recording nothing and returning the units
1015    /// it held.
1016    pub async fn release(mut self) {
1017        if let Some(tracker) = self.budget.take() {
1018            tracker.release_units(&self.held);
1019        }
1020        if let Some(hold) = self.spend.take() {
1021            hold.settle().await;
1022        }
1023    }
1024}
1025
1026impl Drop for UsageHold {
1027    fn drop(&mut self) {
1028        // An abandoned call — its future dropped mid-flight — returns the units it held.
1029        if let Some(tracker) = self.budget.take() {
1030            tracker.release_units(&self.held);
1031        }
1032    }
1033}
1034
1035/// Runs one call billed in units under the [current](ModelCallScope::current) scope, or
1036/// unmetered when there is none. See [`ModelCallScope::meter`].
1037///
1038/// Media clients call this so a call made inside a tool counts against the run the tool
1039/// belongs to.
1040///
1041/// # Errors
1042///
1043/// See [`ModelCallScope::meter`].
1044///
1045/// # Example
1046///
1047/// ```
1048/// use adk_core::{MeteredUsage, UsageCall, UsageUnit, UsageVector, meter_usage};
1049///
1050/// # async fn demo() -> adk_core::Result<()> {
1051/// let call = UsageCall::new("muse", "muse-image-1.0").with_max_cost_micro_usd(10_000);
1052/// let images = meter_usage(call, async {
1053///     Ok((1, MeteredUsage::new(UsageVector::new().with(UsageUnit::Images, 1))))
1054/// })
1055/// .await?;
1056/// assert_eq!(images, 1);
1057/// # Ok(())
1058/// # }
1059/// ```
1060pub async fn meter_usage<T, F>(call: UsageCall, future: F) -> Result<T>
1061where
1062    F: Future<Output = Result<(T, MeteredUsage)>>,
1063{
1064    match ModelCallScope::current() {
1065        Some(scope) => scope.meter(call, future).await,
1066        None => future.await.map(|(value, _)| value),
1067    }
1068}
1069
1070/// Settles `hold` from the responses of `responses` once the stream ends.
1071fn commit_on_completion(responses: LlmResponseStream, hold: ModelSpendHold) -> LlmResponseStream {
1072    // Dropping the stream early drops the hold, which settles it on the runtime.
1073    Box::pin(futures::stream::unfold(Some((responses, Some(hold))), |state| async move {
1074        let (mut responses, mut hold) = state?;
1075        match responses.next().await {
1076            Some(item) => {
1077                if let (Ok(response), Some(open)) = (&item, hold.as_mut()) {
1078                    open.observe(response);
1079                    // Committed before the caller sees the final response, so the next
1080                    // call's reservation already counts this one's cost.
1081                    if response.turn_complete
1082                        && !response.partial
1083                        && let Some(open) = hold.take()
1084                    {
1085                        open.settle().await;
1086                    }
1087                }
1088                Some((item, Some((responses, hold))))
1089            }
1090            None => {
1091                if let Some(open) = hold {
1092                    open.settle().await;
1093                }
1094                None
1095            }
1096        }
1097    }))
1098}
1099
1100/// Calls `model` under the [current](ModelCallScope::current) scope, or unmetered when
1101/// there is none.
1102///
1103/// Built-in compaction summarizers and the MCP sampling handler call models through this
1104/// function; use it in a custom [`BaseEventsSummarizer`](crate::BaseEventsSummarizer) or
1105/// sampling handler so its calls count against the run.
1106///
1107/// # Errors
1108///
1109/// See [`ModelCallScope::generate`].
1110///
1111/// # Example
1112///
1113/// ```rust,ignore
1114/// let stream = adk_core::generate_metered(model.as_ref(), request, false).await?;
1115/// ```
1116pub async fn generate_metered(
1117    model: &dyn Llm,
1118    request: LlmRequest,
1119    stream: bool,
1120) -> Result<LlmResponseStream> {
1121    match ModelCallScope::current() {
1122        Some(scope) => scope.generate(model, request, stream).await,
1123        None => model.generate_content(request, stream).await,
1124    }
1125}
1126
1127/// An [`Llm`] that meters every call against a [`ModelCallScope`].
1128///
1129/// With an explicit scope ([`with_scope`](Self::with_scope)) every call counts against
1130/// it; otherwise calls count against the [current](ModelCallScope::current) scope and run
1131/// unmetered outside one. Wrap the model of a custom summarizer or judge with it; do not
1132/// wrap an agent's own model, whose calls the agent already meters.
1133///
1134/// # Example
1135///
1136/// ```rust,ignore
1137/// use std::sync::Arc;
1138/// use adk_core::{MeteredLlm, ModelCallScope};
1139///
1140/// let judge_model = Arc::new(MeteredLlm::new(model).with_scope(scope));
1141/// ```
1142pub struct MeteredLlm {
1143    inner: Arc<dyn Llm>,
1144    scope: Option<ModelCallScope>,
1145}
1146
1147impl MeteredLlm {
1148    /// Wraps `inner`, metering against the current scope.
1149    pub fn new(inner: Arc<dyn Llm>) -> Self {
1150        Self { inner, scope: None }
1151    }
1152
1153    /// Meters every call against `scope`, whether or not another scope is current.
1154    pub fn with_scope(mut self, scope: ModelCallScope) -> Self {
1155        self.scope = Some(scope);
1156        self
1157    }
1158}
1159
1160#[async_trait]
1161impl Llm for MeteredLlm {
1162    fn name(&self) -> &str {
1163        self.inner.name()
1164    }
1165
1166    async fn generate_content(&self, req: LlmRequest, stream: bool) -> Result<LlmResponseStream> {
1167        match self.scope.clone().or_else(ModelCallScope::current) {
1168            Some(scope) => scope.generate(self.inner.as_ref(), req, stream).await,
1169            None => self.inner.generate_content(req, stream).await,
1170        }
1171    }
1172
1173    fn schema_adapter(&self) -> &dyn SchemaAdapter {
1174        self.inner.schema_adapter()
1175    }
1176
1177    fn uses_interactions_api(&self) -> bool {
1178        self.inner.uses_interactions_api()
1179    }
1180
1181    fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64> {
1182        self.inner.max_cost_micro_usd(request)
1183    }
1184
1185    fn context_window(&self) -> Option<u64> {
1186        self.inner.context_window()
1187    }
1188
1189    fn data_locality(&self) -> crate::DataLocality {
1190        self.inner.data_locality()
1191    }
1192
1193    fn data_destinations(&self) -> Vec<crate::DataDestination> {
1194        self.inner.data_destinations()
1195    }
1196
1197    fn native_web_search(&self) -> Option<crate::NativeWebSearch> {
1198        self.inner.native_web_search()
1199    }
1200
1201    fn native_compaction(&self) -> Option<crate::NativeCompaction> {
1202        self.inner.native_compaction()
1203    }
1204
1205    async fn prewarm(&self) -> Result<()> {
1206        self.inner.prewarm().await
1207    }
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212    use super::*;
1213
1214    use crate::{InMemorySpendLedger, RunBudget, SpendLimits, SpendPeriod, UsageUnit};
1215    use std::sync::atomic::{AtomicBool, Ordering};
1216
1217    fn image_call(images: u64) -> UsageCall {
1218        UsageCall::new("muse", "muse-image-1.0").with_max_cost_micro_usd(images * 10_000)
1219    }
1220
1221    fn images(count: u64) -> MeteredUsage {
1222        MeteredUsage::new(UsageVector::new().with(UsageUnit::Images, count))
1223            .with_cost_micro_usd(count * 10_000)
1224    }
1225
1226    fn capped(micro_usd: u64) -> Arc<InMemorySpendLedger> {
1227        Arc::new(InMemorySpendLedger::new(
1228            SpendLimits::new().limit(SpendKey::org("acme").per(SpendPeriod::Day), micro_usd),
1229        ))
1230    }
1231
1232    #[tokio::test]
1233    async fn a_unit_call_over_the_cap_is_refused_before_it_is_sent() {
1234        let ledger = capped(5_000);
1235        let scope = ModelCallScope::new().with_spend_ledger(ledger.clone(), "acme");
1236        let sent = AtomicBool::new(false);
1237        let refused = scope
1238            .meter(image_call(1), async {
1239                sent.store(true, Ordering::SeqCst);
1240                Ok(((), images(1)))
1241            })
1242            .await
1243            .unwrap_err();
1244        assert_eq!(refused.code, crate::SPEND_LIMIT_EXCEEDED_CODE);
1245        assert!(!sent.load(Ordering::SeqCst));
1246        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 0);
1247    }
1248
1249    #[tokio::test]
1250    async fn a_unit_call_commits_its_cost_to_the_ledger_and_the_budget() {
1251        let ledger = capped(1_000_000);
1252        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(1.0)));
1253        let scope = ModelCallScope::new()
1254            .with_budget(tracker.clone())
1255            .with_spend_ledger(ledger.clone(), "acme");
1256        scope.meter(image_call(2), async { Ok(((), images(2))) }).await.unwrap();
1257
1258        let key = SpendKey::org("acme").with_vendor("muse");
1259        assert_eq!(ledger.spent(&key, SpendPeriod::Day).await.unwrap(), 20_000);
1260        assert_eq!(tracker.usage().cost_micro_usd, 20_000);
1261        assert_eq!(tracker.usage().model_calls, 0);
1262        assert_eq!(tracker.units(), UsageVector::new().with(UsageUnit::Images, 2));
1263    }
1264
1265    #[tokio::test]
1266    async fn a_failed_unit_call_releases_its_hold_and_counts_nothing() {
1267        let ledger = capped(10_000);
1268        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1269        let scope = ModelCallScope::new()
1270            .with_budget(tracker.clone())
1271            .with_spend_ledger(ledger.clone(), "acme");
1272        let failed = scope
1273            .meter(image_call(1), async {
1274                Err::<((), MeteredUsage), _>(crate::AdkError::model("down"))
1275            })
1276            .await
1277            .unwrap_err();
1278        assert_eq!(failed.message, "down");
1279        assert_eq!(tracker.units(), UsageVector::new());
1280        // The released hold leaves the whole cap for the next call.
1281        scope.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap();
1282        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 10_000);
1283    }
1284
1285    #[tokio::test]
1286    async fn an_unpriced_unit_call_is_refused_under_a_ledger_cap() {
1287        let scope = ModelCallScope::new().with_spend_ledger(capped(1_000_000), "acme");
1288        let sent = AtomicBool::new(false);
1289        let refused = scope
1290            .meter(UsageCall::new("deepgram", "nova-3"), async {
1291                sent.store(true, Ordering::SeqCst);
1292                Ok(((), MeteredUsage::default()))
1293            })
1294            .await
1295            .unwrap_err();
1296        assert_eq!(refused.code, crate::SPEND_LIMIT_EXCEEDED_CODE);
1297        assert!(!sent.load(Ordering::SeqCst));
1298    }
1299
1300    #[tokio::test]
1301    async fn an_unpriced_unit_call_is_refused_under_a_budget_cost_cap() {
1302        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(5.0)));
1303        let scope = ModelCallScope::new().with_budget(tracker.clone());
1304        let sent = AtomicBool::new(false);
1305        let refused = scope
1306            .meter(UsageCall::new("deepgram", "nova-3"), async {
1307                sent.store(true, Ordering::SeqCst);
1308                Ok(((), MeteredUsage::default()))
1309            })
1310            .await
1311            .unwrap_err();
1312        assert_eq!(refused.code, "budget.cost_unknown");
1313        assert!(!sent.load(Ordering::SeqCst));
1314        // Nothing ran, so nothing is recorded against later calls.
1315        assert!(tracker.check().is_ok());
1316
1317        let opted_out = Arc::new(BudgetTracker::new(
1318            RunBudget::new().max_cost_usd(5.0).allow_unpriced_models(),
1319        ));
1320        let scope = ModelCallScope::new().with_budget(opted_out.clone());
1321        scope
1322            .meter(UsageCall::new("deepgram", "nova-3"), async {
1323                Ok(((), MeteredUsage::new(UsageVector::new().with(UsageUnit::AudioMillis, 800))))
1324            })
1325            .await
1326            .unwrap();
1327        assert_eq!(opted_out.units(), UsageVector::new().with(UsageUnit::AudioMillis, 800));
1328    }
1329
1330    #[tokio::test]
1331    async fn an_unpriced_unit_call_without_a_cap_commits_the_estimate() {
1332        let ledger = Arc::new(InMemorySpendLedger::default());
1333        let scope = ModelCallScope::new()
1334            .with_spend_ledger(ledger.clone(), "acme")
1335            .with_spend_estimate(LlmSpendEstimate::per_call(7_000));
1336        scope
1337            .meter(UsageCall::new("deepgram", "nova-3"), async {
1338                Ok(((), MeteredUsage::default()))
1339            })
1340            .await
1341            .unwrap();
1342        let key = SpendKey::org("acme").with_vendor("deepgram");
1343        assert_eq!(ledger.spent(&key, SpendPeriod::Day).await.unwrap(), 7_000);
1344    }
1345
1346    /// The messages of the warnings logged while it is the default subscriber.
1347    #[derive(Clone, Default)]
1348    struct Warnings(Arc<std::sync::Mutex<Vec<String>>>);
1349
1350    impl tracing::Subscriber for Warnings {
1351        fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
1352            true
1353        }
1354        fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
1355            tracing::span::Id::from_u64(1)
1356        }
1357        fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
1358        fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
1359        fn event(&self, event: &tracing::Event<'_>) {
1360            struct Message(String);
1361            impl tracing::field::Visit for Message {
1362                fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
1363                    if field.name() == "message" {
1364                        self.0 = format!("{value:?}");
1365                    }
1366                }
1367            }
1368            if *event.metadata().level() == tracing::Level::WARN {
1369                let mut message = Message(String::new());
1370                event.record(&mut message);
1371                self.0.lock().unwrap().push(message.0);
1372            }
1373        }
1374        fn enter(&self, _: &tracing::span::Id) {}
1375        fn exit(&self, _: &tracing::span::Id) {}
1376    }
1377
1378    #[tokio::test]
1379    async fn a_response_without_a_cost_warns_only_when_its_bound_is_positive() {
1380        let warnings = Warnings::default();
1381        let _default = tracing::subscriber::set_default(warnings.clone());
1382        let ledger = Arc::new(InMemorySpendLedger::default());
1383        // A local model bounds its cost at zero; a cloud model at a positive amount.
1384        for bound in [0, 7_000] {
1385            let mut hold = ModelSpendHold::reserve(ledger.clone(), SpendKey::org("acme"), bound)
1386                .await
1387                .unwrap();
1388            hold.observe_cost(None);
1389            hold.settle().await;
1390        }
1391        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 7_000);
1392        assert_eq!(
1393            *warnings.0.lock().unwrap(),
1394            ["model response reported no cost; committing the reserved bound or estimate"]
1395        );
1396    }
1397
1398    #[tokio::test]
1399    async fn a_unit_call_is_refused_once_the_budget_is_spent() {
1400        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_micro_usd(10_000)));
1401        let scope = ModelCallScope::new().with_budget(tracker.clone());
1402        scope.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap();
1403        let refused = scope.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap_err();
1404        assert_eq!(refused.code, "budget.cost");
1405    }
1406
1407    #[tokio::test]
1408    async fn the_free_function_meters_against_the_current_scope() {
1409        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1410        let scope = ModelCallScope::new().with_budget(tracker.clone());
1411        scope.within(meter_usage(image_call(1), async { Ok(((), images(1))) })).await.unwrap();
1412        assert_eq!(tracker.usage().cost_micro_usd, 10_000);
1413        // Outside any scope the call runs unmetered.
1414        meter_usage(image_call(1), async { Ok(((), images(1))) }).await.unwrap();
1415        assert_eq!(tracker.usage().cost_micro_usd, 10_000);
1416    }
1417
1418    #[test]
1419    fn vendor_is_read_from_the_model_family() {
1420        assert_eq!(vendor_for_model("gemini-3.7-flash"), "gemini");
1421        assert_eq!(vendor_for_model("models/gemini-3.1-pro-preview"), "gemini");
1422        assert_eq!(vendor_for_model("claude-opus-4-8"), "anthropic");
1423        assert_eq!(vendor_for_model("gpt-5.2"), "openai");
1424        assert_eq!(vendor_for_model("o3-mini"), "openai");
1425        assert_eq!(vendor_for_model("deepseek-v4"), "deepseek");
1426        assert_eq!(vendor_for_model("muse-image-1.0"), "muse");
1427        assert_eq!(vendor_for_model("llama-4-scout"), "unknown");
1428    }
1429
1430    #[test]
1431    fn the_estimate_without_an_output_price_is_the_per_call_amount() {
1432        let mut request = LlmRequest::new("gemini-3.7-flash", vec![]);
1433        request.config = Some(crate::GenerateContentConfig {
1434            max_output_tokens: Some(1_000),
1435            ..Default::default()
1436        });
1437        assert_eq!(LlmSpendEstimate::per_call(7).estimate(&request), 7);
1438        assert_eq!(LlmSpendEstimate::default().estimate(&request), 50_000);
1439    }
1440
1441    struct Searching;
1442
1443    #[async_trait]
1444    impl Llm for Searching {
1445        fn name(&self) -> &str {
1446            "searching"
1447        }
1448
1449        async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
1450            Ok(Box::pin(futures::stream::empty()))
1451        }
1452
1453        fn native_web_search(&self) -> Option<crate::NativeWebSearch> {
1454            Some(crate::NativeWebSearch::new(
1455                "gemini",
1456                crate::NativeWebSearchTool::GoogleSearch,
1457                false,
1458            ))
1459        }
1460    }
1461
1462    #[test]
1463    fn the_metered_wrapper_reports_the_native_search_of_the_model_it_wraps() {
1464        let metered = MeteredLlm::new(Arc::new(Searching));
1465        assert_eq!(
1466            metered.native_web_search(),
1467            Some(crate::NativeWebSearch::new(
1468                "gemini",
1469                crate::NativeWebSearchTool::GoogleSearch,
1470                false
1471            ))
1472        );
1473    }
1474
1475    /// Answers every call with one complete response reporting `cost`, served by `provider`.
1476    struct Priced {
1477        name: &'static str,
1478        provider: &'static str,
1479        cost: f64,
1480        sent: std::sync::atomic::AtomicUsize,
1481    }
1482
1483    impl Priced {
1484        fn new(name: &'static str, provider: &'static str, cost: f64) -> Self {
1485            Self { name, provider, cost, sent: std::sync::atomic::AtomicUsize::new(0) }
1486        }
1487    }
1488
1489    #[async_trait]
1490    impl Llm for Priced {
1491        fn name(&self) -> &str {
1492            self.name
1493        }
1494
1495        async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
1496            self.sent.fetch_add(1, Ordering::SeqCst);
1497            let mut response = LlmResponse::new(crate::Content::new("model").with_text("ok"));
1498            response.provider = Some(self.provider.to_string());
1499            response.model = Some(self.name.to_string());
1500            response.usage_metadata = Some(crate::UsageMetadata {
1501                prompt_token_count: 10,
1502                candidates_token_count: 5,
1503                total_token_count: 15,
1504                cost: Some(self.cost),
1505                ..Default::default()
1506            });
1507            Ok(Box::pin(futures::stream::iter([Ok(response)])))
1508        }
1509
1510        fn max_cost_micro_usd(&self, _: &LlmRequest) -> Option<u64> {
1511            Some(50_000)
1512        }
1513    }
1514
1515    /// Sends every request to both of its models and answers with the second one's stream.
1516    struct BothModels {
1517        first: Arc<Priced>,
1518        second: Arc<Priced>,
1519    }
1520
1521    #[async_trait]
1522    impl Llm for BothModels {
1523        fn name(&self) -> &str {
1524            "both"
1525        }
1526
1527        async fn generate_content(
1528            &self,
1529            req: LlmRequest,
1530            stream: bool,
1531        ) -> Result<LlmResponseStream> {
1532            self.second.generate_content(req, stream).await
1533        }
1534
1535        async fn generate_content_metered(
1536            &self,
1537            scope: &ModelCallScope,
1538            req: LlmRequest,
1539            stream: bool,
1540        ) -> Result<LlmResponseStream> {
1541            let mut first = req.clone();
1542            first.model = self.first.name.to_string();
1543            let mut drained = scope.generate(self.first.as_ref(), first, stream).await?;
1544            while drained.next().await.is_some() {}
1545            let mut second = req;
1546            second.model = self.second.name.to_string();
1547            scope.generate(self.second.as_ref(), second, stream).await
1548        }
1549    }
1550
1551    #[tokio::test]
1552    async fn a_model_that_meters_its_own_calls_records_each_under_its_provider() {
1553        let ledger = capped(1_000_000);
1554        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1555        let scope = ModelCallScope::new()
1556            .with_budget(tracker.clone())
1557            .with_spend_ledger(ledger.clone(), "acme");
1558        let model = BothModels {
1559            first: Arc::new(Priced::new("gpt-6.1-sol", "openai", 0.001)),
1560            second: Arc::new(Priced::new("claude-haiku-5-5", "anthropic", 0.002)),
1561        };
1562
1563        let mut responses =
1564            scope.generate(&model, LlmRequest::new("both", vec![]), false).await.unwrap();
1565        while responses.next().await.is_some() {}
1566
1567        let spent = |vendor: &'static str| {
1568            let ledger = ledger.clone();
1569            async move {
1570                ledger
1571                    .spent(&SpendKey::org("acme").with_vendor(vendor), SpendPeriod::Day)
1572                    .await
1573                    .unwrap()
1574            }
1575        };
1576        assert_eq!(spent("openai").await, 1_000);
1577        assert_eq!(spent("anthropic").await, 2_000);
1578        assert_eq!(tracker.usage().model_calls, 2);
1579        assert_eq!(tracker.usage().total_tokens, 30);
1580        assert_eq!(tracker.usage().cost_micro_usd, 3_000);
1581    }
1582
1583    #[tokio::test]
1584    async fn a_model_with_the_default_is_metered_as_one_call() {
1585        let ledger = capped(1_000_000);
1586        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1587        let scope = ModelCallScope::new()
1588            .with_budget(tracker.clone())
1589            .with_spend_ledger(ledger.clone(), "acme");
1590        let model = Priced::new("claude-haiku-5-5", "anthropic", 0.002);
1591
1592        let mut responses = scope
1593            .generate(&model, LlmRequest::new("claude-haiku-5-5", vec![]), false)
1594            .await
1595            .unwrap();
1596        while responses.next().await.is_some() {}
1597
1598        let key = SpendKey::org("acme").with_vendor("anthropic");
1599        assert_eq!(ledger.spent(&key, SpendPeriod::Day).await.unwrap(), 2_000);
1600        assert_eq!(tracker.usage().model_calls, 1);
1601    }
1602
1603    #[tokio::test]
1604    async fn a_frozen_scope_refuses_a_call_before_it_is_reserved_or_sent() {
1605        let ledger = capped(1_000_000);
1606        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1607        let control = crate::GovernanceControl::new();
1608        let scope = ModelCallScope::new()
1609            .with_budget(tracker.clone())
1610            .with_spend_ledger(ledger.clone(), "acme")
1611            .with_governance(control.clone());
1612        let model = Priced::new("claude-haiku-5-5", "anthropic", 0.002);
1613        control.freeze("incident");
1614
1615        let refused = scope
1616            .generate(&model, LlmRequest::new("claude-haiku-5-5", vec![]), false)
1617            .await
1618            .err()
1619            .unwrap();
1620        assert_eq!(refused.code, crate::GOVERNANCE_FROZEN_CODE);
1621        assert_eq!(model.sent.load(Ordering::SeqCst), 0);
1622        assert_eq!(tracker.usage().model_calls, 0);
1623
1624        let unmetered = ModelCallScope::new().with_governance(control.clone());
1625        let refused = unmetered
1626            .generate(&model, LlmRequest::new("claude-haiku-5-5", vec![]), false)
1627            .await
1628            .err()
1629            .unwrap();
1630        assert_eq!(refused.code, crate::GOVERNANCE_FROZEN_CODE);
1631        let refused =
1632            unmetered.meter(image_call(1), async { Ok(((), images(1))) }).await.unwrap_err();
1633        assert_eq!(refused.code, crate::GOVERNANCE_FROZEN_CODE);
1634        assert_eq!(model.sent.load(Ordering::SeqCst), 0);
1635    }
1636
1637    #[test]
1638    fn a_run_scope_carries_the_run_kill_switches() {
1639        let control = crate::GovernanceControl::new();
1640        let config = RunConfig::builder().governance(control.clone()).build();
1641        let scope = ModelCallScope::for_run(&config, "acme", "assistant");
1642        assert!(scope.check_governance().is_ok());
1643        control.freeze("incident");
1644        assert_eq!(scope.check_governance().unwrap_err().code, crate::GOVERNANCE_FROZEN_CODE);
1645    }
1646}