1use crate::{
76 AdkError, ErrorCategory, ErrorComponent, ErrorDetails, Event, Llm, LlmRequest, LlmResponse,
77 LlmResponseStream, Result, UsageMetadata, UsageUnit, UsageVector,
78};
79use futures::Stream;
80use std::collections::BTreeMap;
81use std::fmt;
82use std::pin::Pin;
83use std::sync::atomic::{AtomicU64, Ordering};
84use std::sync::{Arc, Mutex};
85use std::task::{Context, Poll};
86use std::time::{Duration, Instant};
87
88pub const BUDGET_RECORDED_KEY: &str = "adk.budget.recorded";
94
95pub const BUDGET_LIMIT_KEY: &str = "adk.budget.limit";
98
99#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
126#[serde(rename_all = "camelCase", default)]
127#[non_exhaustive]
128pub struct RunBudget {
129 #[serde(skip_serializing_if = "Option::is_none")]
131 pub max_model_calls: Option<u64>,
132 #[serde(skip_serializing_if = "Option::is_none")]
134 pub max_total_tokens: Option<u64>,
135 #[serde(skip_serializing_if = "Option::is_none")]
137 pub max_cost_micro_usd: Option<u64>,
138 #[serde(
140 rename = "maxWallTimeMs",
141 with = "optional_millis",
142 skip_serializing_if = "Option::is_none"
143 )]
144 pub max_wall_time: Option<Duration>,
145 #[serde(skip_serializing_if = "Option::is_none")]
147 pub max_tool_calls: Option<u64>,
148 #[serde(skip_serializing_if = "std::ops::Not::not")]
154 pub allow_unpriced_models: bool,
155 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
159 pub max_units: BTreeMap<UsageUnit, u64>,
160}
161
162mod optional_millis {
164 use std::time::Duration;
165
166 use serde::{Deserialize, Deserializer, Serializer};
167
168 pub(super) fn serialize<S: Serializer>(
169 value: &Option<Duration>,
170 serializer: S,
171 ) -> Result<S::Ok, S::Error> {
172 match value {
173 Some(duration) => {
174 serializer.serialize_u64(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
175 }
176 None => serializer.serialize_none(),
177 }
178 }
179
180 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
181 deserializer: D,
182 ) -> Result<Option<Duration>, D::Error> {
183 Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_millis))
184 }
185}
186
187impl RunBudget {
188 pub fn new() -> Self {
190 Self::default()
191 }
192
193 pub fn max_model_calls(mut self, max: u64) -> Self {
195 self.max_model_calls = Some(max);
196 self
197 }
198
199 pub fn max_total_tokens(mut self, max: u64) -> Self {
201 self.max_total_tokens = Some(max);
202 self
203 }
204
205 pub fn max_cost_micro_usd(mut self, max: u64) -> Self {
207 self.max_cost_micro_usd = Some(max);
208 self
209 }
210
211 pub fn max_cost_usd(self, max: f64) -> Self {
215 self.max_cost_micro_usd(usd_to_micro(max))
216 }
217
218 pub fn max_wall_time(mut self, max: Duration) -> Self {
220 self.max_wall_time = Some(max);
221 self
222 }
223
224 pub fn max_tool_calls(mut self, max: u64) -> Self {
226 self.max_tool_calls = Some(max);
227 self
228 }
229
230 pub fn allow_unpriced_models(mut self) -> Self {
234 self.allow_unpriced_models = true;
235 self
236 }
237
238 pub fn max_units(mut self, unit: UsageUnit, max: u64) -> Self {
256 self.max_units.insert(unit, max);
257 self
258 }
259
260 pub fn is_unlimited(&self) -> bool {
262 self.max_model_calls.is_none()
263 && self.max_total_tokens.is_none()
264 && self.max_cost_micro_usd.is_none()
265 && self.max_wall_time.is_none()
266 && self.max_tool_calls.is_none()
267 && self.max_units.is_empty()
268 }
269
270 #[must_use]
289 pub fn narrowed(&self, other: &RunBudget) -> RunBudget {
290 fn min<T: Ord + Copy>(a: Option<T>, b: Option<T>) -> Option<T> {
291 match (a, b) {
292 (Some(a), Some(b)) => Some(a.min(b)),
293 (a, b) => a.or(b),
294 }
295 }
296 RunBudget {
297 max_model_calls: min(self.max_model_calls, other.max_model_calls),
298 max_total_tokens: min(self.max_total_tokens, other.max_total_tokens),
299 max_cost_micro_usd: min(self.max_cost_micro_usd, other.max_cost_micro_usd),
300 max_wall_time: min(self.max_wall_time, other.max_wall_time),
301 max_tool_calls: min(self.max_tool_calls, other.max_tool_calls),
302 max_units: UsageUnit::ALL
303 .into_iter()
304 .filter_map(|unit| {
305 min(self.max_units.get(&unit).copied(), other.max_units.get(&unit).copied())
306 .map(|max| (unit, max))
307 })
308 .collect(),
309 allow_unpriced_models: match (
311 self.max_cost_micro_usd.is_some(),
312 other.max_cost_micro_usd.is_some(),
313 ) {
314 (true, false) => self.allow_unpriced_models,
315 (false, true) => other.allow_unpriced_models,
316 (true, true) | (false, false) => {
317 self.allow_unpriced_models && other.allow_unpriced_models
318 }
319 },
320 }
321 }
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
326#[non_exhaustive]
327pub enum BudgetLimit {
328 ModelCalls,
330 TotalTokens,
332 Cost,
334 WallTime,
336 ToolCalls,
338 Units(UsageUnit),
340}
341
342impl BudgetLimit {
343 pub const fn as_str(self) -> &'static str {
345 match self {
346 Self::ModelCalls => "model_calls",
347 Self::TotalTokens => "total_tokens",
348 Self::Cost => "cost_micro_usd",
349 Self::WallTime => "wall_time_ms",
350 Self::ToolCalls => "tool_calls",
351 Self::Units(unit) => match unit {
352 UsageUnit::InputTokens => "units.inputTokens",
353 UsageUnit::OutputTokens => "units.outputTokens",
354 UsageUnit::Images => "units.images",
355 UsageUnit::AudioMillis => "units.audioMillis",
356 UsageUnit::VideoMillis => "units.videoMillis",
357 UsageUnit::Characters => "units.characters",
358 UsageUnit::Pages => "units.pages",
359 UsageUnit::Requests => "units.requests",
360 UsageUnit::Frames => "units.frames",
361 },
362 }
363 }
364}
365
366impl fmt::Display for BudgetLimit {
367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 f.write_str(self.as_str())
369 }
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct BudgetExceeded {
378 limit: BudgetLimit,
379 used: u64,
380 max: u64,
381 code: &'static str,
382 message: String,
383}
384
385impl BudgetExceeded {
386 fn reached(limit: BudgetLimit, used: u64, max: u64) -> Self {
387 let (code, message) = match limit {
388 BudgetLimit::ModelCalls => (
389 "budget.model_calls",
390 format!("budget exhausted: {used} of {max} model calls used"),
391 ),
392 BudgetLimit::TotalTokens => {
393 ("budget.total_tokens", format!("budget exhausted: {used} of {max} tokens used"))
394 }
395 BudgetLimit::Cost => (
396 "budget.cost",
397 format!(
398 "budget exhausted: {} of {} spent",
399 format_micro_usd(used),
400 format_micro_usd(max)
401 ),
402 ),
403 BudgetLimit::WallTime => (
404 "budget.wall_time",
405 format!("budget exhausted: {used}ms of {max}ms wall time elapsed"),
406 ),
407 BudgetLimit::ToolCalls => {
408 ("budget.tool_calls", format!("budget exhausted: {used} of {max} tool calls used"))
409 }
410 BudgetLimit::Units(unit) => {
411 ("budget.units", format!("budget exhausted: {used} of {max} {unit} used"))
412 }
413 };
414 Self { limit, used, max, code, message }
415 }
416
417 fn units(unit: UsageUnit, used: u64, requested: u64, max: u64) -> Self {
418 Self {
419 limit: BudgetLimit::Units(unit),
420 used,
421 max,
422 code: "budget.units",
423 message: format!(
424 "budget exhausted: the call would bring {unit} to {}, past the run's cap of \
425 {max} {unit}, so it was not sent; raise RunBudget::max_units for {unit} or \
426 start a new run",
427 used.saturating_add(requested)
428 ),
429 }
430 }
431
432 fn tool_batch(used: u64, requested: u64, max: u64) -> Self {
433 Self {
434 limit: BudgetLimit::ToolCalls,
435 used,
436 max,
437 code: "budget.tool_calls",
438 message: format!(
439 "budget exhausted: {requested} tool calls requested with {used} of {max} already used"
440 ),
441 }
442 }
443
444 fn unpriced(model: &str, used: u64, max: u64) -> Self {
445 Self {
446 limit: BudgetLimit::Cost,
447 used,
448 max,
449 code: "budget.cost_unknown",
450 message: format!(
451 "cost unknown for model '{model}': the budget has a cost cap of {} and no price is known for this model; set UsageMetadata::cost in the provider or opt out with RunBudget::allow_unpriced_models()",
452 format_micro_usd(max)
453 ),
454 }
455 }
456
457 fn unpriced_units(model: &str, used: u64, max: u64) -> Self {
458 Self {
459 limit: BudgetLimit::Cost,
460 used,
461 max,
462 code: "budget.cost_unknown",
463 message: format!(
464 "cost unknown for '{model}': the budget has a cost cap of {} and no per-unit price is known for this call, so it was not sent; add the price to the pricing catalog or opt out with RunBudget::allow_unpriced_models()",
465 format_micro_usd(max)
466 ),
467 }
468 }
469
470 fn untokened(model: &str, used: u64, max: u64) -> Self {
471 Self {
472 limit: BudgetLimit::TotalTokens,
473 used,
474 max,
475 code: "budget.tokens_unknown",
476 message: format!(
477 "token usage unknown for model '{model}': the provider reported no usage and the budget has a token cap of {max}"
478 ),
479 }
480 }
481
482 pub fn limit(&self) -> BudgetLimit {
484 self.limit
485 }
486
487 pub fn used(&self) -> u64 {
489 self.used
490 }
491
492 pub fn max(&self) -> u64 {
494 self.max
495 }
496
497 pub fn code(&self) -> &'static str {
499 self.code
500 }
501
502 pub fn message(&self) -> &str {
504 &self.message
505 }
506}
507
508impl fmt::Display for BudgetExceeded {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510 f.write_str(&self.message)
511 }
512}
513
514impl std::error::Error for BudgetExceeded {}
515
516impl From<BudgetExceeded> for AdkError {
517 fn from(exceeded: BudgetExceeded) -> Self {
518 let mut details = ErrorDetails::default();
519 details.metadata.insert("limit".to_string(), exceeded.limit.as_str().into());
520 details.metadata.insert("used".to_string(), exceeded.used.into());
521 details.metadata.insert("max".to_string(), exceeded.max.into());
522 if let BudgetLimit::Units(unit) = exceeded.limit {
523 details.metadata.insert("unit".to_string(), unit.as_str().into());
524 }
525 AdkError::new(
526 ErrorComponent::Agent,
527 ErrorCategory::ResourceExhausted,
528 exceeded.code,
529 exceeded.message,
530 )
531 .with_details(details)
532 }
533}
534
535#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
537pub struct BudgetUsage {
538 pub model_calls: u64,
540 pub total_tokens: u64,
542 pub cost_micro_usd: u64,
544 pub tool_calls: u64,
546 pub elapsed: Duration,
548}
549
550#[derive(Debug)]
572pub struct BudgetTracker {
573 budget: RunBudget,
574 started_at: Instant,
575 model_calls: AtomicU64,
576 total_tokens: AtomicU64,
577 cost_micro_usd: AtomicU64,
578 tool_calls: AtomicU64,
579 units: Mutex<UnitCounts>,
580 exceeded: Mutex<Option<BudgetExceeded>>,
581 parent: Option<Arc<BudgetTracker>>,
582}
583
584#[derive(Debug, Default)]
587struct UnitCounts {
588 used: UsageVector,
589 held: UsageVector,
590}
591
592impl BudgetTracker {
593 pub fn new(budget: RunBudget) -> Self {
595 Self::resume(budget, BudgetUsage::default(), None)
596 }
597
598 pub fn with_parent(budget: RunBudget, parent: Arc<BudgetTracker>) -> Self {
600 Self::resume(budget, BudgetUsage::default(), Some(parent))
601 }
602
603 pub fn resume(
608 budget: RunBudget,
609 usage: BudgetUsage,
610 parent: Option<Arc<BudgetTracker>>,
611 ) -> Self {
612 let now = Instant::now();
613 Self {
614 budget,
615 started_at: now.checked_sub(usage.elapsed).unwrap_or(now),
616 model_calls: AtomicU64::new(usage.model_calls),
617 total_tokens: AtomicU64::new(usage.total_tokens),
618 cost_micro_usd: AtomicU64::new(usage.cost_micro_usd),
619 tool_calls: AtomicU64::new(usage.tool_calls),
620 units: Mutex::new(UnitCounts::default()),
621 exceeded: Mutex::new(None),
622 parent,
623 }
624 }
625
626 pub fn budget(&self) -> &RunBudget {
628 &self.budget
629 }
630
631 pub fn parent(&self) -> Option<&Arc<BudgetTracker>> {
633 self.parent.as_ref()
634 }
635
636 pub fn usage(&self) -> BudgetUsage {
638 BudgetUsage {
639 model_calls: self.model_calls.load(Ordering::SeqCst),
640 total_tokens: self.total_tokens.load(Ordering::SeqCst),
641 cost_micro_usd: self.cost_micro_usd.load(Ordering::SeqCst),
642 tool_calls: self.tool_calls.load(Ordering::SeqCst),
643 elapsed: self.started_at.elapsed(),
644 }
645 }
646
647 pub fn units(&self) -> UsageVector {
678 self.units.lock().unwrap_or_else(|e| e.into_inner()).used.clone()
679 }
680
681 pub fn exceeded(&self) -> Option<BudgetExceeded> {
688 let own = self.exceeded.lock().unwrap_or_else(|e| e.into_inner()).clone();
689 own.or_else(|| self.parent.as_ref().and_then(|parent| parent.exceeded()))
690 }
691
692 pub fn check(&self) -> std::result::Result<(), BudgetExceeded> {
699 self.check_chain(Strictness::Reached)
700 }
701
702 pub fn begin_model_call(
712 self: &Arc<Self>,
713 model: impl Into<String>,
714 ) -> std::result::Result<ModelCallMeter, BudgetExceeded> {
715 self.check()?;
716 self.check_chain(Strictness::Exceeded)?;
719 self.reserve(Counter::ModelCalls, 1)?;
720 Ok(ModelCallMeter {
721 tracker: Arc::clone(self),
722 model: model.into(),
723 fallback: None,
724 responses_seen: false,
725 settled: false,
726 })
727 }
728
729 pub(crate) fn begin_usage(
738 &self,
739 model: &str,
740 priced: bool,
741 units: &UsageVector,
742 ) -> std::result::Result<(), BudgetExceeded> {
743 self.check()?;
744 self.check_chain(Strictness::Exceeded)?;
745 if !priced {
746 self.refuse_unpriced(model)?;
747 }
748 self.hold_units(units)
749 }
750
751 fn hold_units(&self, units: &UsageVector) -> std::result::Result<(), BudgetExceeded> {
754 if units.is_empty() {
755 return Ok(());
756 }
757 {
758 let mut counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
759 for (unit, amount) in units.iter() {
760 if let Some(&max) = self.budget.max_units.get(&unit) {
761 let used = counts.used.get(unit).saturating_add(counts.held.get(unit));
762 if used.saturating_add(amount) > max {
763 return Err(BudgetExceeded::units(unit, used, amount, max));
764 }
765 }
766 }
767 counts.held.merge(units);
768 }
769 if let Some(parent) = &self.parent
770 && let Err(violation) = parent.hold_units(units)
771 {
772 self.units.lock().unwrap_or_else(|e| e.into_inner()).held.subtract(units);
773 return Err(violation);
774 }
775 Ok(())
776 }
777
778 pub(crate) fn release_units(&self, held: &UsageVector) {
781 if held.is_empty() {
782 return;
783 }
784 self.units.lock().unwrap_or_else(|e| e.into_inner()).held.subtract(held);
785 if let Some(parent) = &self.parent {
786 parent.release_units(held);
787 }
788 }
789
790 fn refuse_unpriced(&self, model: &str) -> std::result::Result<(), BudgetExceeded> {
791 if let Some(max) = self.budget.max_cost_micro_usd
792 && !self.budget.allow_unpriced_models
793 {
794 let used = self.cost_micro_usd.load(Ordering::SeqCst);
795 return Err(BudgetExceeded::unpriced_units(model, used, max));
796 }
797 match &self.parent {
798 Some(parent) => parent.refuse_unpriced(model),
799 None => Ok(()),
800 }
801 }
802
803 pub(crate) fn record_units(
806 &self,
807 model: &str,
808 held: &UsageVector,
809 units: &UsageVector,
810 cost: Option<u64>,
811 ) {
812 self.add(Counter::TotalTokens, units.tokens());
813 match cost {
814 Some(cost) => self.add(Counter::Cost, cost),
815 None => self.flag_unpriced(model),
816 }
817 self.settle_units(held, units);
818 }
819
820 fn settle_units(&self, held: &UsageVector, used: &UsageVector) {
823 if held.is_empty() && used.is_empty() {
824 return;
825 }
826 {
827 let mut counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
828 counts.held.subtract(held);
829 counts.used.merge(used);
830 }
831 if let Some(parent) = &self.parent {
832 parent.settle_units(held, used);
833 }
834 }
835
836 pub fn begin_tool_calls(&self, count: u64) -> std::result::Result<(), BudgetExceeded> {
846 self.check()?;
847 if count == 0 {
848 return Ok(());
849 }
850 self.reserve(Counter::ToolCalls, count)
851 }
852
853 pub fn release_tool_calls(&self, count: u64) {
871 if count == 0 {
872 return;
873 }
874 let _ = self.tool_calls.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
875 Some(used.saturating_sub(count))
876 });
877 if let Some(parent) = &self.parent {
878 parent.release_tool_calls(count);
879 }
880 }
881
882 pub fn tool_calls_remaining(&self) -> Option<u64> {
896 let own = self
897 .budget
898 .max_tool_calls
899 .map(|max| max.saturating_sub(self.tool_calls.load(Ordering::SeqCst)));
900 let parent = self.parent.as_ref().and_then(|parent| parent.tool_calls_remaining());
901 match (own, parent) {
902 (Some(own), Some(parent)) => Some(own.min(parent)),
903 (own, parent) => own.or(parent),
904 }
905 }
906
907 pub fn remaining(&self) -> RunBudget {
926 let usage = self.usage();
927 let left = |max: Option<u64>, used: u64| max.map(|max| max.saturating_sub(used));
928 let own = RunBudget {
929 max_model_calls: left(self.budget.max_model_calls, usage.model_calls),
930 max_total_tokens: left(self.budget.max_total_tokens, usage.total_tokens),
931 max_cost_micro_usd: left(self.budget.max_cost_micro_usd, usage.cost_micro_usd),
932 max_wall_time: self.budget.max_wall_time.map(|max| max.saturating_sub(usage.elapsed)),
933 max_tool_calls: left(self.budget.max_tool_calls, usage.tool_calls),
934 allow_unpriced_models: self.budget.allow_unpriced_models,
935 max_units: {
936 let counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
937 self.budget
938 .max_units
939 .iter()
940 .map(|(&unit, &max)| {
941 let used = counts.used.get(unit).saturating_add(counts.held.get(unit));
942 (unit, max.saturating_sub(used))
943 })
944 .collect()
945 },
946 };
947 match &self.parent {
948 Some(parent) => {
949 let mut chain = own.narrowed(&parent.remaining());
950 chain.allow_unpriced_models = self.budget.allow_unpriced_models;
951 chain
952 }
953 None => own,
954 }
955 }
956
957 pub fn carve(&self, ask: &RunBudget) -> std::result::Result<RunBudget, BudgetExceeded> {
992 self.check()?;
993 let left = self.remaining();
994 let pick = |ask: Option<u64>, left: Option<u64>| match (ask, left) {
995 (Some(ask), Some(left)) => Some(ask.min(left)),
996 (Some(ask), None) => Some(ask),
997 (None, Some(left)) => Some(left.div_ceil(2)),
998 (None, None) => None,
999 };
1000 let capped = left.max_cost_micro_usd.is_some();
1001 let slice = RunBudget {
1002 max_model_calls: pick(ask.max_model_calls, left.max_model_calls),
1003 max_total_tokens: pick(ask.max_total_tokens, left.max_total_tokens),
1004 max_cost_micro_usd: pick(ask.max_cost_micro_usd, left.max_cost_micro_usd),
1005 max_wall_time: match (ask.max_wall_time, left.max_wall_time) {
1006 (Some(ask), Some(left)) => Some(ask.min(left)),
1007 (ask, left) => ask.or(left),
1008 },
1009 max_tool_calls: pick(ask.max_tool_calls, left.max_tool_calls),
1010 allow_unpriced_models: if capped {
1011 self.unpriced_allowed_in_chain()
1012 } else {
1013 ask.allow_unpriced_models
1014 },
1015 max_units: UsageUnit::ALL
1016 .into_iter()
1017 .filter_map(|unit| {
1018 pick(ask.max_units.get(&unit).copied(), left.max_units.get(&unit).copied())
1019 .map(|max| (unit, max))
1020 })
1021 .collect(),
1022 };
1023 let usage = self.usage();
1024 let exhausted = |limit: BudgetLimit, slice: Option<u64>, used: u64| {
1025 (slice == Some(0)).then(|| BudgetExceeded::reached(limit, used, used))
1026 };
1027 if let Some(violation) = exhausted(
1028 BudgetLimit::ModelCalls,
1029 slice.max_model_calls.filter(|_| left.max_model_calls.is_some()),
1030 usage.model_calls,
1031 )
1032 .or_else(|| {
1033 exhausted(
1034 BudgetLimit::TotalTokens,
1035 slice.max_total_tokens.filter(|_| left.max_total_tokens.is_some()),
1036 usage.total_tokens,
1037 )
1038 })
1039 .or_else(|| {
1040 exhausted(
1041 BudgetLimit::Cost,
1042 slice.max_cost_micro_usd.filter(|_| left.max_cost_micro_usd.is_some()),
1043 usage.cost_micro_usd,
1044 )
1045 })
1046 .or_else(|| {
1047 exhausted(
1048 BudgetLimit::ToolCalls,
1049 slice.max_tool_calls.filter(|_| left.max_tool_calls.is_some()),
1050 usage.tool_calls,
1051 )
1052 })
1053 .or_else(|| {
1054 (slice.max_wall_time == Some(Duration::ZERO)).then(|| {
1055 let elapsed = duration_ms(usage.elapsed);
1056 BudgetExceeded::reached(BudgetLimit::WallTime, elapsed, elapsed)
1057 })
1058 })
1059 .or_else(|| {
1060 left.max_units.keys().find(|unit| slice.max_units.get(unit) == Some(&0)).map(|&unit| {
1061 let used = self.units().get(unit);
1062 BudgetExceeded::reached(BudgetLimit::Units(unit), used, used)
1063 })
1064 }) {
1065 return Err(violation);
1066 }
1067 self.hold_units(
1069 &slice
1070 .max_units
1071 .iter()
1072 .filter(|(unit, _)| left.max_units.contains_key(unit))
1073 .map(|(&unit, &max)| (unit, max))
1074 .collect(),
1075 )?;
1076 let reserve = |counter: Counter, slice: Option<u64>, limited: Option<u64>| {
1077 if let (Some(amount), Some(_)) = (slice, limited) {
1078 self.add(counter, amount);
1079 }
1080 };
1081 reserve(Counter::ModelCalls, slice.max_model_calls, left.max_model_calls);
1082 reserve(Counter::TotalTokens, slice.max_total_tokens, left.max_total_tokens);
1083 reserve(Counter::Cost, slice.max_cost_micro_usd, left.max_cost_micro_usd);
1084 reserve(Counter::ToolCalls, slice.max_tool_calls, left.max_tool_calls);
1085 Ok(slice)
1086 }
1087
1088 fn unpriced_allowed_in_chain(&self) -> bool {
1090 let own = self.budget.max_cost_micro_usd.is_none() || self.budget.allow_unpriced_models;
1091 own && self.parent.as_ref().is_none_or(|parent| parent.unpriced_allowed_in_chain())
1092 }
1093
1094 pub fn record_event(&self, event: &mut Event) -> std::result::Result<(), BudgetExceeded> {
1107 if event.llm_response.partial || event.provider_metadata.contains_key(BUDGET_RECORDED_KEY) {
1108 return self.check_chain(Strictness::Exceeded);
1109 }
1110 let usage = event.llm_response.usage_metadata.clone();
1111 let tool_calls = event.tool_calls().len() as u64;
1112 if usage.is_none() && tool_calls == 0 {
1113 return self.check_chain(Strictness::Exceeded);
1114 }
1115 if let Some(usage) = usage {
1116 self.add(Counter::ModelCalls, 1);
1117 let model =
1118 event.llm_response.model.clone().unwrap_or_else(|| "unattributed".to_string());
1119 self.record_usage(&model, Some(&usage));
1120 }
1121 self.add(Counter::ToolCalls, tool_calls);
1122 event.provider_metadata.insert(BUDGET_RECORDED_KEY.to_string(), "true".to_string());
1123 self.check_chain(Strictness::Exceeded)
1124 }
1125
1126 fn check_chain(&self, strictness: Strictness) -> std::result::Result<(), BudgetExceeded> {
1127 if let Some(exceeded) = self.exceeded.lock().unwrap_or_else(|e| e.into_inner()).clone() {
1128 return Err(exceeded);
1129 }
1130 if let Some(violation) = self.limit_violation(strictness) {
1131 return Err(violation);
1132 }
1133 match &self.parent {
1134 Some(parent) => parent.check_chain(strictness),
1135 None => Ok(()),
1136 }
1137 }
1138
1139 fn limit_violation(&self, strictness: Strictness) -> Option<BudgetExceeded> {
1140 let usage = self.usage();
1141 let over = |used: u64, max: u64| match strictness {
1142 Strictness::Reached => used >= max,
1143 Strictness::Exceeded => used > max,
1144 };
1145 if let Some(max) = self.budget.max_total_tokens
1146 && over(usage.total_tokens, max)
1147 {
1148 return Some(BudgetExceeded::reached(
1149 BudgetLimit::TotalTokens,
1150 usage.total_tokens,
1151 max,
1152 ));
1153 }
1154 if let Some(max) = self.budget.max_cost_micro_usd
1155 && over(usage.cost_micro_usd, max)
1156 {
1157 return Some(BudgetExceeded::reached(BudgetLimit::Cost, usage.cost_micro_usd, max));
1158 }
1159 if let Some(max) = self.budget.max_wall_time {
1160 let elapsed = duration_ms(usage.elapsed);
1161 let max = duration_ms(max);
1162 if over(elapsed, max) {
1163 return Some(BudgetExceeded::reached(BudgetLimit::WallTime, elapsed, max));
1164 }
1165 }
1166 if strictness == Strictness::Exceeded {
1167 if let Some(max) = self.budget.max_model_calls
1168 && usage.model_calls > max
1169 {
1170 return Some(BudgetExceeded::reached(
1171 BudgetLimit::ModelCalls,
1172 usage.model_calls,
1173 max,
1174 ));
1175 }
1176 if let Some(max) = self.budget.max_tool_calls
1177 && usage.tool_calls > max
1178 {
1179 return Some(BudgetExceeded::reached(
1180 BudgetLimit::ToolCalls,
1181 usage.tool_calls,
1182 max,
1183 ));
1184 }
1185 }
1186 None
1187 }
1188
1189 fn remember(&self, violation: BudgetExceeded) -> BudgetExceeded {
1190 let mut slot = self.exceeded.lock().unwrap_or_else(|e| e.into_inner());
1191 slot.get_or_insert(violation).clone()
1192 }
1193
1194 fn counter(&self, counter: Counter) -> &AtomicU64 {
1195 match counter {
1196 Counter::ModelCalls => &self.model_calls,
1197 Counter::ToolCalls => &self.tool_calls,
1198 Counter::TotalTokens => &self.total_tokens,
1199 Counter::Cost => &self.cost_micro_usd,
1200 }
1201 }
1202
1203 fn reserve(&self, counter: Counter, count: u64) -> std::result::Result<(), BudgetExceeded> {
1204 let max = match counter {
1205 Counter::ModelCalls => self.budget.max_model_calls,
1206 Counter::ToolCalls => self.budget.max_tool_calls,
1207 Counter::TotalTokens | Counter::Cost => None,
1208 };
1209 let atomic = self.counter(counter);
1210 let reserved = atomic.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
1211 let next = used.saturating_add(count);
1212 match max {
1213 Some(max) if next > max => None,
1214 _ => Some(next),
1215 }
1216 });
1217 if let Err(used) = reserved {
1218 let max = max.unwrap_or_default();
1219 let violation = match counter {
1220 Counter::ToolCalls if count > 1 => BudgetExceeded::tool_batch(used, count, max),
1221 Counter::ToolCalls => BudgetExceeded::reached(BudgetLimit::ToolCalls, used, max),
1222 Counter::ModelCalls | Counter::TotalTokens | Counter::Cost => {
1223 BudgetExceeded::reached(BudgetLimit::ModelCalls, used, max)
1224 }
1225 };
1226 return Err(violation);
1227 }
1228 if let Some(parent) = &self.parent
1229 && let Err(violation) = parent.reserve(counter, count)
1230 {
1231 atomic.fetch_sub(count, Ordering::SeqCst);
1232 return Err(violation);
1233 }
1234 Ok(())
1235 }
1236
1237 fn add(&self, counter: Counter, amount: u64) {
1238 if amount == 0 {
1239 return;
1240 }
1241 let atomic = self.counter(counter);
1242 let _ = atomic.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
1243 Some(used.saturating_add(amount))
1244 });
1245 if let Some(parent) = &self.parent {
1246 parent.add(counter, amount);
1247 }
1248 }
1249
1250 fn record_usage(&self, model: &str, usage: Option<&UsageMetadata>) {
1252 match usage {
1253 Some(usage) => {
1254 self.add(Counter::TotalTokens, u64::try_from(usage.total_token_count).unwrap_or(0));
1255 self.add(Counter::ToolCalls, usage.builtin_tool_use_count());
1256 let count = |tokens: i32| u64::try_from(tokens).unwrap_or(0);
1257 self.settle_units(
1258 &UsageVector::new(),
1259 &UsageVector::new()
1260 .with(UsageUnit::InputTokens, count(usage.prompt_token_count))
1261 .with(UsageUnit::OutputTokens, count(usage.candidates_token_count)),
1262 );
1263 match usage.cost {
1264 Some(cost) => self.add(Counter::Cost, usd_to_micro(cost)),
1265 None => self.flag_unpriced(model),
1266 }
1267 }
1268 None => {
1269 self.flag_unpriced(model);
1270 self.flag_untokened(model);
1271 }
1272 }
1273 }
1274
1275 fn flag_unpriced(&self, model: &str) {
1276 if let Some(max) = self.budget.max_cost_micro_usd
1277 && !self.budget.allow_unpriced_models
1278 {
1279 let used = self.cost_micro_usd.load(Ordering::SeqCst);
1280 self.remember(BudgetExceeded::unpriced(model, used, max));
1281 }
1282 if let Some(parent) = &self.parent {
1283 parent.flag_unpriced(model);
1284 }
1285 }
1286
1287 fn flag_untokened(&self, model: &str) {
1288 if let Some(max) = self.budget.max_total_tokens {
1289 let used = self.total_tokens.load(Ordering::SeqCst);
1290 self.remember(BudgetExceeded::untokened(model, used, max));
1291 }
1292 if let Some(parent) = &self.parent {
1293 parent.flag_untokened(model);
1294 }
1295 }
1296}
1297
1298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1299enum Strictness {
1300 Reached,
1302 Exceeded,
1304}
1305
1306#[derive(Debug, Clone, Copy)]
1307enum Counter {
1308 ModelCalls,
1309 ToolCalls,
1310 TotalTokens,
1311 Cost,
1312}
1313
1314#[derive(Debug)]
1322pub struct ModelCallMeter {
1323 tracker: Arc<BudgetTracker>,
1324 model: String,
1325 fallback: Option<(String, UsageMetadata)>,
1326 responses_seen: bool,
1327 settled: bool,
1328}
1329
1330impl ModelCallMeter {
1331 pub fn observe(&mut self, response: &LlmResponse) {
1333 if self.settled {
1334 return;
1335 }
1336 self.responses_seen = true;
1337 let Some(usage) = &response.usage_metadata else {
1338 return;
1339 };
1340 let model = response.model.clone().unwrap_or_else(|| self.model.clone());
1341 if response.partial {
1342 self.fallback = Some((model, usage.clone()));
1343 return;
1344 }
1345 self.settled = true;
1346 self.tracker.record_usage(&model, Some(usage));
1347 }
1348
1349 pub fn is_settled(&self) -> bool {
1351 self.settled
1352 }
1353
1354 pub fn finish(mut self) {
1356 self.settle();
1357 }
1358
1359 fn settle(&mut self) {
1360 if self.settled {
1361 return;
1362 }
1363 self.settled = true;
1364 if !self.responses_seen {
1365 return;
1366 }
1367 match self.fallback.take() {
1368 Some((model, usage)) => self.tracker.record_usage(&model, Some(&usage)),
1369 None => self.tracker.record_usage(&self.model, None),
1370 }
1371 }
1372}
1373
1374impl Drop for ModelCallMeter {
1375 fn drop(&mut self) {
1376 self.settle();
1377 }
1378}
1379
1380pub fn meter_stream(stream: LlmResponseStream, meter: ModelCallMeter) -> LlmResponseStream {
1383 Box::pin(MeteredStream { inner: stream, meter: Some(meter) })
1384}
1385
1386struct MeteredStream {
1387 inner: LlmResponseStream,
1388 meter: Option<ModelCallMeter>,
1389}
1390
1391impl Stream for MeteredStream {
1392 type Item = Result<LlmResponse>;
1393
1394 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1395 let item = self.inner.as_mut().poll_next(cx);
1396 match &item {
1397 Poll::Ready(Some(Ok(response))) => {
1398 if let Some(meter) = self.meter.as_mut() {
1399 meter.observe(response);
1400 }
1401 }
1402 Poll::Ready(None) => {
1403 self.meter.take();
1404 }
1405 Poll::Ready(Some(Err(_))) | Poll::Pending => {}
1406 }
1407 item
1408 }
1409}
1410
1411pub async fn generate_with_budget(
1429 model: &dyn Llm,
1430 request: LlmRequest,
1431 stream: bool,
1432 tracker: Option<&Arc<BudgetTracker>>,
1433) -> Result<LlmResponseStream> {
1434 let Some(tracker) = tracker else {
1435 return model.generate_content(request, stream).await;
1436 };
1437 let meter = tracker.begin_model_call(model.name())?;
1438 let responses = model.generate_content(request, stream).await?;
1439 Ok(meter_stream(responses, meter))
1440}
1441
1442pub fn budget_exceeded_event(invocation_id: &str, author: &str, error: &AdkError) -> Option<Event> {
1462 if error.category != ErrorCategory::ResourceExhausted {
1463 return None;
1464 }
1465 let mut event = Event::new(invocation_id);
1466 event.author = author.to_string();
1467 event.llm_response.partial = false;
1468 event.llm_response.turn_complete = true;
1469 event.llm_response.finish_reason = Some(crate::FinishReason::Other);
1470 event.llm_response.error_code = Some(error.code.to_string());
1471 event.llm_response.error_message = Some(error.message.clone());
1472 if let Some(limit) = error.details.metadata.get("limit").and_then(|value| value.as_str()) {
1473 event.provider_metadata.insert(BUDGET_LIMIT_KEY.to_string(), limit.to_string());
1474 }
1475 Some(event)
1476}
1477
1478fn usd_to_micro(usd: f64) -> u64 {
1479 if !usd.is_finite() || usd <= 0.0 {
1480 return 0;
1481 }
1482 let micro = (usd * 1_000_000.0).round();
1483 if micro >= u64::MAX as f64 { u64::MAX } else { micro as u64 }
1484}
1485
1486fn duration_ms(duration: Duration) -> u64 {
1487 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
1488}
1489
1490fn format_micro_usd(micro: u64) -> String {
1491 format!("${}.{:06}", micro / 1_000_000, micro % 1_000_000)
1492}
1493
1494#[cfg(test)]
1495mod tests {
1496 use super::*;
1497 use crate::{Content, Part};
1498
1499 fn usage(total: i32, cost: Option<f64>) -> UsageMetadata {
1500 UsageMetadata {
1501 prompt_token_count: total / 2,
1502 candidates_token_count: total - total / 2,
1503 total_token_count: total,
1504 cost,
1505 ..Default::default()
1506 }
1507 }
1508
1509 fn response(partial: bool, usage: Option<UsageMetadata>) -> LlmResponse {
1510 LlmResponse {
1511 partial,
1512 usage_metadata: usage,
1513 model: Some("gemini-3.7-flash".to_string()),
1514 ..Default::default()
1515 }
1516 }
1517
1518 #[test]
1519 fn builtin_tool_uses_count_as_tool_calls_and_refuse_the_next_turn_once_over() {
1520 let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(2)));
1521 let mut searched = usage(10, Some(0.0));
1522 searched.builtin_tool_uses = vec![crate::BuiltinToolUse::new("web_search", 2)];
1523 let mut meter = tracker.begin_model_call("m").unwrap();
1524 meter.observe(&response(false, Some(searched.clone())));
1525 drop(meter);
1526 assert_eq!(tracker.usage().tool_calls, 2);
1527 assert_eq!(tracker.tool_calls_remaining(), Some(0));
1528 let mut meter = tracker.begin_model_call("m").unwrap();
1530 meter.observe(&response(false, Some(searched)));
1531 drop(meter);
1532 assert_eq!(tracker.usage().tool_calls, 4);
1533 let error = tracker.begin_model_call("m").unwrap_err();
1534 assert_eq!(error.limit(), BudgetLimit::ToolCalls);
1535 }
1536
1537 #[test]
1538 fn tool_calls_remaining_takes_the_tightest_ancestor() {
1539 let parent = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(1)));
1540 let child = BudgetTracker::with_parent(RunBudget::new().max_tool_calls(5), parent);
1541 assert_eq!(child.tool_calls_remaining(), Some(1));
1542 child.begin_tool_calls(1).unwrap();
1543 assert_eq!(child.tool_calls_remaining(), Some(0));
1544 }
1545
1546 #[test]
1547 fn model_call_limit_blocks_the_next_call() {
1548 let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(2)));
1549 tracker.begin_model_call("m").unwrap().finish();
1550 tracker.begin_model_call("m").unwrap().finish();
1551 let error = tracker.begin_model_call("m").unwrap_err();
1552 assert_eq!(error.limit(), BudgetLimit::ModelCalls);
1553 assert_eq!(tracker.usage().model_calls, 2);
1554 }
1555
1556 #[test]
1557 fn partial_chunks_do_not_add_usage() {
1558 let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1559 let mut meter = tracker.begin_model_call("gemini-3.7-flash").unwrap();
1560 meter.observe(&response(true, Some(usage(100, Some(0.001)))));
1562 meter.observe(&response(true, Some(usage(150, Some(0.0015)))));
1563 meter.observe(&response(false, Some(usage(200, Some(0.002)))));
1564 meter.observe(&response(false, Some(usage(200, Some(0.002)))));
1565 drop(meter);
1566 let usage = tracker.usage();
1567 assert_eq!((usage.model_calls, usage.total_tokens, usage.cost_micro_usd), (1, 200, 2_000));
1568 }
1569
1570 #[test]
1571 fn a_cut_stream_records_its_last_partial_usage() {
1572 let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1573 let mut meter = tracker.begin_model_call("m").unwrap();
1574 meter.observe(&response(true, Some(usage(100, Some(0.001)))));
1575 meter.observe(&response(true, Some(usage(150, Some(0.0015)))));
1576 drop(meter);
1577 assert_eq!(tracker.usage().total_tokens, 150);
1578 assert_eq!(tracker.usage().cost_micro_usd, 1_500);
1579 }
1580
1581 #[test]
1582 fn cost_cap_stops_once_reached() {
1583 let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(0.003)));
1584 for _ in 0..3 {
1585 let mut meter = tracker.begin_model_call("m").unwrap();
1586 meter.observe(&response(false, Some(usage(10, Some(0.001)))));
1587 }
1588 let error = tracker.begin_model_call("m").unwrap_err();
1589 assert_eq!(error.limit(), BudgetLimit::Cost);
1590 assert_eq!(error.code(), "budget.cost");
1591 assert_eq!(error.used(), 3_000);
1592 assert!(tracker.begin_tool_calls(1).is_err());
1593 }
1594
1595 #[test]
1596 fn unknown_cost_under_a_cap_fails_closed() {
1597 let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(10.0)));
1598 let mut meter = tracker.begin_model_call("mystery-model").unwrap();
1599 meter.observe(&response(false, Some(usage(10, None))));
1600 let error = tracker.begin_model_call("mystery-model").unwrap_err();
1601 assert_eq!(error.code(), "budget.cost_unknown");
1602 assert!(error.message().contains("cost unknown for model 'gemini-3.7-flash'"));
1603
1604 let allowed = Arc::new(BudgetTracker::new(
1605 RunBudget::new().max_cost_usd(10.0).allow_unpriced_models(),
1606 ));
1607 let mut meter = allowed.begin_model_call("mystery-model").unwrap();
1608 meter.observe(&response(false, Some(usage(10, None))));
1609 drop(meter);
1610 assert!(allowed.begin_model_call("mystery-model").is_ok());
1611 }
1612
1613 #[test]
1614 fn missing_usage_under_a_token_cap_fails_closed() {
1615 let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_total_tokens(100)));
1616 let mut meter = tracker.begin_model_call("silent").unwrap();
1617 meter.observe(&response(false, None));
1618 drop(meter);
1619 assert_eq!(tracker.check().unwrap_err().code(), "budget.tokens_unknown");
1620 }
1621
1622 #[test]
1623 fn tool_batches_are_all_or_nothing() {
1624 let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(3));
1625 tracker.begin_tool_calls(2).unwrap();
1626 let error = tracker.begin_tool_calls(2).unwrap_err();
1627 assert_eq!(error.limit(), BudgetLimit::ToolCalls);
1628 assert_eq!(tracker.usage().tool_calls, 2);
1629 tracker.begin_tool_calls(1).unwrap();
1630 assert!(tracker.begin_tool_calls(1).is_err());
1631 }
1632
1633 #[test]
1634 fn wall_time_is_checked_at_every_checkpoint() {
1635 let tracker = Arc::new(BudgetTracker::resume(
1636 RunBudget::new().max_wall_time(Duration::from_millis(50)),
1637 BudgetUsage { elapsed: Duration::from_millis(60), ..Default::default() },
1638 None,
1639 ));
1640 assert_eq!(tracker.begin_model_call("m").unwrap_err().limit(), BudgetLimit::WallTime);
1641 assert_eq!(tracker.begin_tool_calls(1).unwrap_err().limit(), BudgetLimit::WallTime);
1642 }
1643
1644 #[test]
1645 fn child_trackers_count_against_their_parent() {
1646 let parent = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(2)));
1647 let child = Arc::new(BudgetTracker::with_parent(
1648 RunBudget::new().max_model_calls(5),
1649 parent.clone(),
1650 ));
1651 child.begin_model_call("m").unwrap().finish();
1652 parent.begin_model_call("m").unwrap().finish();
1653 let error = child.begin_model_call("m").unwrap_err();
1654 assert_eq!(error.limit(), BudgetLimit::ModelCalls);
1655 assert_eq!(child.usage().model_calls, 1);
1657 assert_eq!(parent.usage().model_calls, 2);
1658 }
1659
1660 #[test]
1661 fn record_event_counts_unmetered_events_once() {
1662 let tracker = BudgetTracker::new(RunBudget::new());
1663 let mut event = Event::new("inv");
1664 event.llm_response.usage_metadata = Some(usage(40, Some(0.004)));
1665 event.llm_response.content = Some(Content {
1666 role: "model".to_string(),
1667 parts: vec![Part::FunctionCall {
1668 name: "lookup".to_string(),
1669 args: serde_json::json!({}),
1670 id: None,
1671 thought_signature: None,
1672 }],
1673 });
1674 tracker.record_event(&mut event).unwrap();
1675 tracker.record_event(&mut event).unwrap();
1676 let mut partial = Event::new("inv");
1677 partial.llm_response.partial = true;
1678 partial.llm_response.usage_metadata = Some(usage(999, Some(9.0)));
1679 tracker.record_event(&mut partial).unwrap();
1680 let usage = tracker.usage();
1681 assert_eq!(
1682 (usage.model_calls, usage.total_tokens, usage.cost_micro_usd, usage.tool_calls),
1683 (1, 40, 4_000, 1)
1684 );
1685 assert_eq!(event.provider_metadata[BUDGET_RECORDED_KEY], "true");
1686 }
1687
1688 #[test]
1689 fn violations_convert_to_resource_exhausted_errors() {
1690 let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(0));
1691 let error: AdkError = tracker.begin_tool_calls(1).unwrap_err().into();
1692 assert_eq!(error.category, ErrorCategory::ResourceExhausted);
1693 assert_eq!(error.code, "budget.tool_calls");
1694 assert!(!error.is_retryable());
1695 assert_eq!(error.details.metadata["limit"], "tool_calls");
1696 let event = budget_exceeded_event("inv", "agent", &error).unwrap();
1697 assert!(!event.llm_response.partial);
1698 assert_eq!(event.llm_response.error_message.as_deref(), Some(error.message.as_str()));
1699 assert!(budget_exceeded_event("inv", "agent", &AdkError::agent("other")).is_none());
1700 }
1701
1702 #[tokio::test]
1703 async fn metered_streams_record_on_completion() {
1704 let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1705 let meter = tracker.begin_model_call("m").unwrap();
1706 let responses: Vec<Result<LlmResponse>> = vec![
1707 Ok(response(true, Some(usage(5, Some(0.0005))))),
1708 Ok(response(false, Some(usage(10, Some(0.001))))),
1709 ];
1710 let stream = meter_stream(Box::pin(futures::stream::iter(responses)), meter);
1711 let collected: Vec<_> = futures::StreamExt::collect(stream).await;
1712 assert_eq!(collected.len(), 2);
1713 assert_eq!(tracker.usage().total_tokens, 10);
1714 assert_eq!(tracker.usage().cost_micro_usd, 1_000);
1715 }
1716
1717 #[test]
1718 fn a_carved_slice_never_takes_the_chain_past_its_limits() {
1719 let run = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(10)));
1720 let team = BudgetTracker::with_parent(RunBudget::new().max_tool_calls(6), Arc::clone(&run));
1721 let slice = team.carve(&RunBudget::new().max_model_calls(4).max_tool_calls(100)).unwrap();
1722 assert_eq!(slice.max_model_calls, Some(4));
1723 assert_eq!(slice.max_tool_calls, Some(6), "the team's tool limit caps the ask");
1724 assert_eq!(run.usage().model_calls, 4);
1726 assert_eq!(team.remaining().max_tool_calls, Some(0));
1727 assert_eq!(team.remaining().max_model_calls, Some(6));
1728 let refused = team.carve(&RunBudget::new()).unwrap_err();
1730 assert_eq!(refused.limit(), BudgetLimit::ToolCalls);
1731 assert_eq!(run.usage().model_calls, 4);
1732 }
1733
1734 #[test]
1735 fn a_slice_counts_unpriced_models_as_free_only_where_the_chain_does() {
1736 let capped = BudgetTracker::new(RunBudget::new().max_cost_micro_usd(1_000));
1737 let ask = RunBudget::new().allow_unpriced_models();
1738 assert!(!capped.carve(&ask).unwrap().allow_unpriced_models);
1739 let lenient =
1740 BudgetTracker::new(RunBudget::new().max_cost_micro_usd(1_000).allow_unpriced_models());
1741 assert!(lenient.carve(&RunBudget::new()).unwrap().allow_unpriced_models);
1742 let open = BudgetTracker::new(RunBudget::new());
1743 assert!(open.carve(&ask).unwrap().allow_unpriced_models);
1744 assert_eq!(open.carve(&RunBudget::new()).unwrap(), RunBudget::new());
1745 }
1746
1747 #[test]
1748 fn a_budget_round_trips_with_its_wall_time_in_milliseconds() {
1749 let budget =
1750 RunBudget::new().max_model_calls(3).max_wall_time(Duration::from_millis(1_500));
1751 let json = serde_json::to_value(&budget).unwrap();
1752 assert_eq!(json, serde_json::json!({ "maxModelCalls": 3, "maxWallTimeMs": 1500 }));
1753 assert_eq!(serde_json::from_value::<RunBudget>(json).unwrap(), budget);
1754 assert_eq!(
1755 serde_json::from_value::<RunBudget>(serde_json::json!({})).unwrap(),
1756 RunBudget::new()
1757 );
1758 }
1759
1760 fn images(count: u64) -> UsageVector {
1761 UsageVector::new().with(UsageUnit::Images, count)
1762 }
1763
1764 #[test]
1765 fn a_unit_hold_past_its_cap_is_refused_naming_the_unit_and_the_cap() {
1766 let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 2));
1767 tracker.begin_usage("sam-3.1", true, &images(1)).unwrap();
1768 tracker.record_units("sam-3.1", &images(1), &images(1), Some(2_500));
1769 tracker.begin_usage("sam-3.1", true, &images(1)).unwrap();
1770 let refused = tracker.begin_usage("sam-3.1", true, &images(1)).unwrap_err();
1771 assert_eq!(refused.limit(), BudgetLimit::Units(UsageUnit::Images));
1772 assert_eq!((refused.used(), refused.max()), (2, 2));
1773 assert_eq!(refused.code(), "budget.units");
1774 assert!(refused.message().contains("cap of 2 images"), "{}", refused.message());
1775 let error = AdkError::from(refused);
1776 assert_eq!(error.details.metadata["limit"], "units.images");
1777 assert_eq!(error.details.metadata["unit"], "images");
1778 tracker.release_units(&images(1));
1780 assert!(tracker.begin_usage("sam-3.1", true, &images(1)).is_ok());
1781 assert_eq!(tracker.units(), images(1), "only committed units are usage");
1782 }
1783
1784 #[test]
1785 fn a_commit_replaces_the_hold_with_what_the_call_used() {
1786 let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Frames, 100));
1787 let frames = |count| UsageVector::new().with(UsageUnit::Frames, count);
1788 tracker.begin_usage("sam-3.1", true, &frames(80)).unwrap();
1789 assert_eq!(tracker.remaining().max_units[&UsageUnit::Frames], 20);
1790 tracker.record_units("sam-3.1", &frames(80), &frames(30), Some(6_000));
1791 assert_eq!(tracker.remaining().max_units[&UsageUnit::Frames], 70);
1792 assert_eq!(tracker.units(), frames(30));
1793 }
1794
1795 #[test]
1796 fn uncapped_units_and_undeclared_calls_are_never_held_back() {
1797 let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 1));
1798 tracker
1799 .begin_usage("tts", true, &UsageVector::new().with(UsageUnit::Characters, 9_000))
1800 .unwrap();
1801 tracker.record_units("sam-3.1", &UsageVector::new(), &images(3), Some(0));
1802 assert!(tracker.begin_usage("sam-3.1", true, &UsageVector::new()).is_ok());
1804 assert_eq!(
1805 tracker.begin_usage("sam-3.1", true, &images(1)).unwrap_err().limit(),
1806 BudgetLimit::Units(UsageUnit::Images)
1807 );
1808 }
1809
1810 #[test]
1811 fn a_child_hold_is_refused_by_its_parents_cap_and_holds_nothing() {
1812 let run = Arc::new(BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Pages, 5)));
1813 let team = BudgetTracker::with_parent(
1814 RunBudget::new().max_units(UsageUnit::Pages, 10),
1815 Arc::clone(&run),
1816 );
1817 let pages = |count| UsageVector::new().with(UsageUnit::Pages, count);
1818 team.begin_usage("ocr", true, &pages(4)).unwrap();
1819 let refused = team.begin_usage("ocr", true, &pages(2)).unwrap_err();
1820 assert_eq!((refused.limit(), refused.max()), (BudgetLimit::Units(UsageUnit::Pages), 5));
1821 assert_eq!(team.remaining().max_units[&UsageUnit::Pages], 1);
1822 team.record_units("ocr", &pages(4), &pages(4), Some(0));
1823 assert_eq!((team.units(), run.units()), (pages(4), pages(4)));
1824 }
1825
1826 #[test]
1827 fn unit_caps_narrow_carve_and_round_trip() {
1828 let runner = RunBudget::new().max_units(UsageUnit::Images, 50);
1829 let run =
1830 RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600);
1831 let narrowed = runner.narrowed(&run);
1832 assert_eq!(
1833 narrowed,
1834 RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600)
1835 );
1836 assert!(!narrowed.is_unlimited());
1837
1838 let parent = BudgetTracker::new(narrowed.clone());
1839 let slice = parent.carve(&RunBudget::new().max_units(UsageUnit::Images, 8)).unwrap();
1840 assert_eq!(slice.max_units[&UsageUnit::Images], 8);
1841 assert_eq!(slice.max_units[&UsageUnit::Frames], 300, "half of what is left");
1842 assert_eq!(parent.remaining().max_units[&UsageUnit::Images], 12);
1843 assert_eq!(parent.units(), UsageVector::new(), "a carved slice is held, not used");
1844 let exhausted = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 0));
1845 assert_eq!(
1846 exhausted.carve(&RunBudget::new()).unwrap_err().limit(),
1847 BudgetLimit::Units(UsageUnit::Images)
1848 );
1849
1850 let json = serde_json::to_value(&narrowed).unwrap();
1851 assert_eq!(json, serde_json::json!({ "maxUnits": { "images": 20, "frames": 600 } }));
1852 assert_eq!(serde_json::from_value::<RunBudget>(json).unwrap(), narrowed);
1853 }
1854}