1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use thiserror::Error;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct ModelPricing {
7 pub model_name: String,
8 pub provider: String,
9 pub input_cost_per_1k_tokens: f64, pub output_cost_per_1k_tokens: f64, pub context_window: usize,
12 pub max_output_tokens: Option<usize>,
13}
14
15impl ModelPricing {
16 fn from_mtok(
19 model_name: &str,
20 provider: &str,
21 input_per_mtok: f64,
22 output_per_mtok: f64,
23 context_window: usize,
24 max_output_tokens: Option<usize>,
25 ) -> Self {
26 ModelPricing {
27 model_name: model_name.to_string(),
28 provider: provider.to_string(),
29 input_cost_per_1k_tokens: input_per_mtok / 1000.0,
30 output_cost_per_1k_tokens: output_per_mtok / 1000.0,
31 context_window,
32 max_output_tokens,
33 }
34 }
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct CostEstimate {
39 pub model_name: String,
40 pub input_tokens: usize,
41 pub output_tokens: usize,
42 pub input_cost: f64,
43 pub output_cost: f64,
44 #[serde(default)]
46 pub cache_cost: f64,
47 pub total_cost: f64,
48 pub currency: String,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct BudgetStatus {
53 pub budget_usd: f64,
54 pub spent_usd: f64,
55 pub remaining_usd: f64,
56 pub percent_used: f64,
57 pub status: BudgetAlert,
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
61pub enum BudgetAlert {
62 Ok, Warning, Critical, Exceeded, }
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
72pub enum Platform {
73 #[default]
75 FirstParty,
76 Bedrock,
78 Vertex,
80 Azure,
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
86pub enum PricingTier {
87 #[default]
89 Standard,
90 Batch,
92 Cached,
94 Priority,
96 Flex,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
102pub enum DataResidency {
103 #[default]
105 Global,
106 Us,
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
113pub struct RateCard {
114 pub platform: Platform,
115 pub tier: PricingTier,
116 pub data_residency: DataResidency,
117 pub regional_endpoint: bool,
119 pub fast_mode: bool,
121}
122
123impl RateCard {
124 pub fn parse(s: &str) -> Result<RateCard, CostError> {
129 let mut card = RateCard::default();
130 for raw in
131 s.split(|c: char| c == '/' || c == ':' || c == ',' || c == '+' || c.is_whitespace())
132 {
133 let token = raw.trim().to_ascii_lowercase();
134 if token.is_empty() {
135 continue;
136 }
137 match token.as_str() {
138 "first_party" | "firstparty" | "first-party" | "direct" | "anthropic"
139 | "openai" | "google" => card.platform = Platform::FirstParty,
140 "bedrock" | "aws" => card.platform = Platform::Bedrock,
141 "vertex" | "vertexai" | "gcp" => card.platform = Platform::Vertex,
142 "azure" => card.platform = Platform::Azure,
143 "standard" | "ondemand" | "on-demand" => card.tier = PricingTier::Standard,
144 "batch" => card.tier = PricingTier::Batch,
145 "cached" | "cache" => card.tier = PricingTier::Cached,
146 "priority" => card.tier = PricingTier::Priority,
147 "flex" => card.tier = PricingTier::Flex,
148 "regional" | "region" | "multiregion" | "multi-region" => {
149 card.regional_endpoint = true
150 }
151 "us" | "residency" | "data-residency" | "us-only" => {
152 card.data_residency = DataResidency::Us
153 }
154 "global" => card.data_residency = DataResidency::Global,
155 "fast" | "fast-mode" | "fastmode" => card.fast_mode = true,
156 other => return Err(CostError::UnknownRateCard(other.to_string())),
157 }
158 }
159 Ok(card)
160 }
161}
162
163#[derive(Debug, Clone, Copy, Default)]
166pub struct TokenUsage {
167 pub input_tokens: usize,
168 pub output_tokens: usize,
169 pub cache_read_tokens: usize,
170 pub cache_write_5m_tokens: usize,
171 pub cache_write_1h_tokens: usize,
172}
173
174#[derive(Debug, Clone, Copy)]
177struct CacheRates {
178 read_per_1k: f64,
179 write_5m_per_1k: Option<f64>,
180 write_1h_per_1k: Option<f64>,
181}
182
183impl CacheRates {
184 fn from_mtok(read: f64, write_5m: f64, write_1h: f64) -> Self {
186 Self {
187 read_per_1k: read / 1000.0,
188 write_5m_per_1k: Some(write_5m / 1000.0),
189 write_1h_per_1k: Some(write_1h / 1000.0),
190 }
191 }
192 fn read_only_mtok(read: f64) -> Self {
194 Self {
195 read_per_1k: read / 1000.0,
196 write_5m_per_1k: None,
197 write_1h_per_1k: None,
198 }
199 }
200}
201
202#[derive(Debug, Clone, Copy)]
204struct TokenRates {
205 input_per_1k: f64,
206 output_per_1k: f64,
207}
208
209impl TokenRates {
210 fn from_mtok(input: f64, output: f64) -> Self {
211 Self {
212 input_per_1k: input / 1000.0,
213 output_per_1k: output / 1000.0,
214 }
215 }
216}
217
218#[derive(Debug, Clone, Copy)]
221struct ContextTier {
222 threshold_tokens: usize,
223 input_per_1k: f64,
224 output_per_1k: f64,
225}
226
227impl ContextTier {
228 fn from_mtok(threshold_tokens: usize, input: f64, output: f64) -> Self {
229 Self {
230 threshold_tokens,
231 input_per_1k: input / 1000.0,
232 output_per_1k: output / 1000.0,
233 }
234 }
235}
236
237#[derive(Debug, Clone, Copy, Default)]
239struct ModifierFlags {
240 supports_data_residency: bool,
242 supports_regional_premium: bool,
244}
245
246#[derive(Debug, Clone, Default)]
249struct PricingExtras {
250 cache_rates: Option<CacheRates>,
251 fast_mode_rates: Option<TokenRates>,
252 long_context_tiers: Vec<ContextTier>,
253 priority_multiplier: Option<f64>,
254 cache_storage_per_mtok_hour: Option<f64>,
257 flags: ModifierFlags,
258}
259
260pub struct CostCalculator {
261 pricing_table: HashMap<String, ModelPricing>,
262 extras: HashMap<String, PricingExtras>,
264}
265
266impl CostCalculator {
267 pub fn new() -> Self {
269 let mut pricing_table = HashMap::new();
270
271 pricing_table.insert(
273 "gpt-4".to_string(),
274 ModelPricing {
275 model_name: "gpt-4".to_string(),
276 provider: "openai".to_string(),
277 input_cost_per_1k_tokens: 0.03,
278 output_cost_per_1k_tokens: 0.06,
279 context_window: 8192,
280 max_output_tokens: Some(4096),
281 },
282 );
283
284 pricing_table.insert(
285 "gpt-4-turbo".to_string(),
286 ModelPricing {
287 model_name: "gpt-4-turbo".to_string(),
288 provider: "openai".to_string(),
289 input_cost_per_1k_tokens: 0.01,
290 output_cost_per_1k_tokens: 0.03,
291 context_window: 128000,
292 max_output_tokens: Some(4096),
293 },
294 );
295
296 pricing_table.insert(
297 "gpt-3.5-turbo".to_string(),
298 ModelPricing {
299 model_name: "gpt-3.5-turbo".to_string(),
300 provider: "openai".to_string(),
301 input_cost_per_1k_tokens: 0.0005,
302 output_cost_per_1k_tokens: 0.0015,
303 context_window: 16385,
304 max_output_tokens: Some(4096),
305 },
306 );
307
308 pricing_table.insert(
309 "gpt-4o".to_string(),
310 ModelPricing {
311 model_name: "gpt-4o".to_string(),
312 provider: "openai".to_string(),
313 input_cost_per_1k_tokens: 0.005,
314 output_cost_per_1k_tokens: 0.015,
315 context_window: 128000,
316 max_output_tokens: Some(4096),
317 },
318 );
319
320 pricing_table.insert(
321 "gpt-4o-mini".to_string(),
322 ModelPricing {
323 model_name: "gpt-4o-mini".to_string(),
324 provider: "openai".to_string(),
325 input_cost_per_1k_tokens: 0.00015,
326 output_cost_per_1k_tokens: 0.0006,
327 context_window: 128000,
328 max_output_tokens: Some(16384),
329 },
330 );
331
332 pricing_table.insert(
334 "claude-3-opus".to_string(),
335 ModelPricing {
336 model_name: "claude-3-opus".to_string(),
337 provider: "anthropic".to_string(),
338 input_cost_per_1k_tokens: 0.015,
339 output_cost_per_1k_tokens: 0.075,
340 context_window: 200000,
341 max_output_tokens: Some(4096),
342 },
343 );
344
345 pricing_table.insert(
346 "claude-3-sonnet".to_string(),
347 ModelPricing {
348 model_name: "claude-3-sonnet".to_string(),
349 provider: "anthropic".to_string(),
350 input_cost_per_1k_tokens: 0.003,
351 output_cost_per_1k_tokens: 0.015,
352 context_window: 200000,
353 max_output_tokens: Some(4096),
354 },
355 );
356
357 pricing_table.insert(
358 "claude-3-haiku".to_string(),
359 ModelPricing {
360 model_name: "claude-3-haiku".to_string(),
361 provider: "anthropic".to_string(),
362 input_cost_per_1k_tokens: 0.00025,
363 output_cost_per_1k_tokens: 0.00125,
364 context_window: 200000,
365 max_output_tokens: Some(4096),
366 },
367 );
368
369 pricing_table.insert(
370 "claude-3-5-sonnet".to_string(),
371 ModelPricing {
372 model_name: "claude-3-5-sonnet".to_string(),
373 provider: "anthropic".to_string(),
374 input_cost_per_1k_tokens: 0.003,
375 output_cost_per_1k_tokens: 0.015,
376 context_window: 200000,
377 max_output_tokens: Some(8192),
378 },
379 );
380
381 pricing_table.insert(
383 "gemini-pro".to_string(),
384 ModelPricing {
385 model_name: "gemini-pro".to_string(),
386 provider: "google".to_string(),
387 input_cost_per_1k_tokens: 0.0005,
388 output_cost_per_1k_tokens: 0.0015,
389 context_window: 30720,
390 max_output_tokens: Some(2048),
391 },
392 );
393
394 pricing_table.insert(
395 "gemini-ultra".to_string(),
396 ModelPricing {
397 model_name: "gemini-ultra".to_string(),
398 provider: "google".to_string(),
399 input_cost_per_1k_tokens: 0.0125,
400 output_cost_per_1k_tokens: 0.0375,
401 context_window: 30720,
402 max_output_tokens: Some(2048),
403 },
404 );
405
406 let mut calculator = Self {
407 pricing_table,
408 extras: HashMap::new(),
409 };
410 calculator.install_modern_models();
411 calculator
412 }
413
414 pub fn normalize_model_id(model_id: &str) -> String {
420 let mut id = model_id;
421 for region in ["us.", "eu.", "apac.", "global."] {
422 if let Some(rest) = id.strip_prefix(region) {
423 id = rest;
424 break;
425 }
426 }
427 for vendor in ["anthropic.", "amazon.", "cohere.", "mistral.", "meta."] {
428 if let Some(rest) = id.strip_prefix(vendor) {
429 id = rest;
430 break;
431 }
432 }
433 let mut out = id.to_string();
434 if let Some(pos) = out.rfind("-v") {
436 let tail = &out[pos + 2..];
437 if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit() || c == ':') {
438 out.truncate(pos);
439 }
440 }
441 if let Some(pos) = out.rfind(':') {
443 if out[pos + 1..].chars().all(|c| c.is_ascii_digit()) && !out[pos + 1..].is_empty() {
444 out.truncate(pos);
445 }
446 }
447 if out.len() > 9 {
449 let (head, tail) = out.split_at(out.len() - 9);
450 if tail.starts_with('-') && tail[1..].chars().all(|c| c.is_ascii_digit()) {
451 out = head.to_string();
452 }
453 }
454 out
455 }
456
457 fn resolve_model_key(&self, model_name: &str) -> Option<String> {
460 if self.pricing_table.contains_key(model_name) {
461 return Some(model_name.to_string());
462 }
463 let normalized = Self::normalize_model_id(model_name);
464 if self.pricing_table.contains_key(&normalized) {
465 return Some(normalized);
466 }
467 None
468 }
469
470 fn insert_model(&mut self, pricing: ModelPricing, extras: PricingExtras) {
472 let name = pricing.model_name.clone();
473 self.extras.insert(name.clone(), extras);
474 self.pricing_table.insert(name, pricing);
475 }
476
477 fn install_modern_models(&mut self) {
480 self.insert_model(
483 ModelPricing::from_mtok(
484 "claude-opus-4-8",
485 "anthropic",
486 5.0,
487 25.0,
488 1_000_000,
489 Some(64_000),
490 ),
491 PricingExtras {
492 cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
493 fast_mode_rates: Some(TokenRates::from_mtok(10.0, 50.0)),
494 flags: ModifierFlags {
495 supports_data_residency: true,
496 supports_regional_premium: true,
497 },
498 ..Default::default()
499 },
500 );
501 self.insert_model(
502 ModelPricing::from_mtok(
503 "claude-opus-4-7",
504 "anthropic",
505 5.0,
506 25.0,
507 1_000_000,
508 Some(64_000),
509 ),
510 PricingExtras {
511 cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
512 fast_mode_rates: Some(TokenRates::from_mtok(30.0, 150.0)),
513 flags: ModifierFlags {
514 supports_data_residency: true,
515 supports_regional_premium: true,
516 },
517 ..Default::default()
518 },
519 );
520 self.insert_model(
521 ModelPricing::from_mtok(
522 "claude-opus-4-6",
523 "anthropic",
524 5.0,
525 25.0,
526 1_000_000,
527 Some(64_000),
528 ),
529 PricingExtras {
530 cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
531 fast_mode_rates: Some(TokenRates::from_mtok(30.0, 150.0)),
532 flags: ModifierFlags {
533 supports_data_residency: true,
534 supports_regional_premium: true,
535 },
536 ..Default::default()
537 },
538 );
539 self.insert_model(
540 ModelPricing::from_mtok(
541 "claude-opus-4-5",
542 "anthropic",
543 5.0,
544 25.0,
545 200_000,
546 Some(64_000),
547 ),
548 PricingExtras {
549 cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
550 flags: ModifierFlags {
551 supports_data_residency: false,
552 supports_regional_premium: true,
553 },
554 ..Default::default()
555 },
556 );
557 self.insert_model(
558 ModelPricing::from_mtok(
559 "claude-opus-4-1",
560 "anthropic",
561 15.0,
562 75.0,
563 200_000,
564 Some(32_000),
565 ),
566 PricingExtras {
567 cache_rates: Some(CacheRates::from_mtok(1.5, 18.75, 30.0)),
568 ..Default::default()
569 },
570 );
571 self.insert_model(
572 ModelPricing::from_mtok(
573 "claude-sonnet-4-6",
574 "anthropic",
575 3.0,
576 15.0,
577 1_000_000,
578 Some(64_000),
579 ),
580 PricingExtras {
581 cache_rates: Some(CacheRates::from_mtok(0.3, 3.75, 6.0)),
582 flags: ModifierFlags {
583 supports_data_residency: true,
584 supports_regional_premium: true,
585 },
586 ..Default::default()
587 },
588 );
589 self.insert_model(
590 ModelPricing::from_mtok(
591 "claude-sonnet-4-5",
592 "anthropic",
593 3.0,
594 15.0,
595 200_000,
596 Some(64_000),
597 ),
598 PricingExtras {
599 cache_rates: Some(CacheRates::from_mtok(0.3, 3.75, 6.0)),
600 flags: ModifierFlags {
601 supports_data_residency: false,
602 supports_regional_premium: true,
603 },
604 ..Default::default()
605 },
606 );
607 self.insert_model(
608 ModelPricing::from_mtok(
609 "claude-haiku-4-5",
610 "anthropic",
611 1.0,
612 5.0,
613 200_000,
614 Some(64_000),
615 ),
616 PricingExtras {
617 cache_rates: Some(CacheRates::from_mtok(0.1, 1.25, 2.0)),
618 flags: ModifierFlags {
619 supports_data_residency: false,
620 supports_regional_premium: true,
621 },
622 ..Default::default()
623 },
624 );
625 self.insert_model(
626 ModelPricing::from_mtok(
627 "claude-haiku-3-5",
628 "anthropic",
629 0.8,
630 4.0,
631 200_000,
632 Some(8_192),
633 ),
634 PricingExtras {
635 cache_rates: Some(CacheRates::from_mtok(0.08, 1.0, 1.6)),
636 ..Default::default()
637 },
638 );
639
640 self.insert_model(
643 ModelPricing::from_mtok("gpt-5.5", "openai", 5.0, 30.0, 1_050_000, Some(128_000)),
644 PricingExtras {
645 cache_rates: Some(CacheRates::read_only_mtok(0.5)),
646 priority_multiplier: Some(2.5),
647 flags: ModifierFlags {
648 supports_data_residency: false,
649 supports_regional_premium: true,
650 },
651 ..Default::default()
652 },
653 );
654 self.insert_model(
655 ModelPricing::from_mtok("gpt-5.5-pro", "openai", 30.0, 180.0, 400_000, Some(128_000)),
656 PricingExtras {
657 flags: ModifierFlags {
658 supports_data_residency: false,
659 supports_regional_premium: true,
660 },
661 ..Default::default()
662 },
663 );
664 self.insert_model(
665 ModelPricing::from_mtok("gpt-5.4", "openai", 2.5, 15.0, 400_000, Some(128_000)),
666 PricingExtras {
667 cache_rates: Some(CacheRates::read_only_mtok(0.25)),
668 flags: ModifierFlags {
669 supports_data_residency: false,
670 supports_regional_premium: true,
671 },
672 ..Default::default()
673 },
674 );
675 self.insert_model(
676 ModelPricing::from_mtok("gpt-5.4-mini", "openai", 0.75, 4.5, 400_000, Some(128_000)),
677 PricingExtras {
678 cache_rates: Some(CacheRates::read_only_mtok(0.075)),
679 flags: ModifierFlags {
680 supports_data_residency: false,
681 supports_regional_premium: true,
682 },
683 ..Default::default()
684 },
685 );
686 self.insert_model(
687 ModelPricing::from_mtok("gpt-5.4-nano", "openai", 0.2, 1.25, 400_000, Some(128_000)),
688 PricingExtras {
689 cache_rates: Some(CacheRates::read_only_mtok(0.02)),
690 flags: ModifierFlags {
691 supports_data_residency: false,
692 supports_regional_premium: true,
693 },
694 ..Default::default()
695 },
696 );
697 self.insert_model(
698 ModelPricing::from_mtok("gpt-5.4-pro", "openai", 30.0, 180.0, 400_000, Some(128_000)),
699 PricingExtras {
700 flags: ModifierFlags {
701 supports_data_residency: false,
702 supports_regional_premium: true,
703 },
704 ..Default::default()
705 },
706 );
707
708 self.insert_model(
711 ModelPricing::from_mtok(
712 "gemini-3.5-flash",
713 "google",
714 1.5,
715 9.0,
716 1_048_576,
717 Some(65_536),
718 ),
719 PricingExtras {
720 cache_rates: Some(CacheRates::read_only_mtok(0.15)),
721 priority_multiplier: Some(1.8),
722 cache_storage_per_mtok_hour: Some(1.0),
723 ..Default::default()
724 },
725 );
726 self.insert_model(
727 ModelPricing::from_mtok(
728 "gemini-3.1-pro",
729 "google",
730 2.0,
731 12.0,
732 1_048_576,
733 Some(65_536),
734 ),
735 PricingExtras {
736 long_context_tiers: vec![ContextTier::from_mtok(200_000, 4.0, 18.0)],
737 ..Default::default()
738 },
739 );
740 self.insert_model(
741 ModelPricing::from_mtok(
742 "gemini-3.1-flash-lite",
743 "google",
744 0.25,
745 1.5,
746 1_048_576,
747 Some(65_536),
748 ),
749 PricingExtras::default(),
750 );
751 self.insert_model(
752 ModelPricing::from_mtok(
753 "gemini-3-flash",
754 "google",
755 0.5,
756 3.0,
757 1_048_576,
758 Some(65_536),
759 ),
760 PricingExtras::default(),
761 );
762 self.insert_model(
763 ModelPricing::from_mtok(
764 "gemini-2.5-pro",
765 "google",
766 1.25,
767 10.0,
768 1_048_576,
769 Some(65_536),
770 ),
771 PricingExtras {
772 cache_rates: Some(CacheRates::read_only_mtok(0.125)),
773 cache_storage_per_mtok_hour: Some(4.5),
774 long_context_tiers: vec![ContextTier::from_mtok(200_000, 2.5, 15.0)],
775 ..Default::default()
776 },
777 );
778 self.insert_model(
779 ModelPricing::from_mtok(
780 "gemini-2.5-flash",
781 "google",
782 0.3,
783 2.5,
784 1_048_576,
785 Some(65_536),
786 ),
787 PricingExtras::default(),
788 );
789 self.insert_model(
790 ModelPricing::from_mtok(
791 "gemini-2.5-flash-lite",
792 "google",
793 0.1,
794 0.4,
795 1_048_576,
796 Some(65_536),
797 ),
798 PricingExtras::default(),
799 );
800
801 self.insert_model(
805 ModelPricing::from_mtok("nova-premier", "amazon", 2.5, 12.5, 1_000_000, Some(10_000)),
806 PricingExtras::default(),
807 );
808 self.insert_model(
809 ModelPricing::from_mtok("nova-pro", "amazon", 0.8, 3.2, 300_000, Some(5_120)),
810 PricingExtras::default(),
811 );
812 self.insert_model(
813 ModelPricing::from_mtok("nova-lite", "amazon", 0.06, 0.24, 300_000, Some(5_120)),
814 PricingExtras::default(),
815 );
816 self.insert_model(
817 ModelPricing::from_mtok("nova-micro", "amazon", 0.035, 0.14, 128_000, Some(5_120)),
818 PricingExtras::default(),
819 );
820 self.insert_model(
821 ModelPricing::from_mtok("titan-embed-text", "amazon", 0.1, 0.0, 8_192, None),
822 PricingExtras::default(),
823 );
824 self.insert_model(
825 ModelPricing::from_mtok("cohere-embed", "cohere", 0.1, 0.0, 8_192, None),
826 PricingExtras::default(),
827 );
828 }
829
830 pub fn estimate_cost(
834 &self,
835 model_name: &str,
836 input_tokens: usize,
837 output_tokens: usize,
838 ) -> Result<CostEstimate, CostError> {
839 self.estimate_cost_with_card(
840 model_name,
841 TokenUsage {
842 input_tokens,
843 output_tokens,
844 ..Default::default()
845 },
846 RateCard::default(),
847 )
848 }
849
850 pub fn estimate_cost_with_card(
854 &self,
855 model_name: &str,
856 usage: TokenUsage,
857 card: RateCard,
858 ) -> Result<CostEstimate, CostError> {
859 let key = self
860 .resolve_model_key(model_name)
861 .ok_or_else(|| CostError::UnknownModel(model_name.to_string()))?;
862 let pricing = self
863 .pricing_table
864 .get(&key)
865 .ok_or_else(|| CostError::UnknownModel(model_name.to_string()))?;
866 let extras = self.extras.get(&key);
867
868 let billable = usage.input_tokens
869 + usage.output_tokens
870 + usage.cache_read_tokens
871 + usage.cache_write_5m_tokens
872 + usage.cache_write_1h_tokens;
873 if billable == 0 {
874 return Err(CostError::InvalidTokenCount);
875 }
876
877 if usage.input_tokens + usage.output_tokens > pricing.context_window {
880 return Err(CostError::InvalidTokenCount);
881 }
882 if let Some(max_output) = pricing.max_output_tokens {
883 if usage.output_tokens > max_output {
884 return Err(CostError::InvalidTokenCount);
885 }
886 }
887
888 let mut base_in = pricing.input_cost_per_1k_tokens;
890 let mut base_out = pricing.output_cost_per_1k_tokens;
891
892 if let Some(ex) = extras {
895 if let Some(tier) = ex
896 .long_context_tiers
897 .iter()
898 .filter(|t| usage.input_tokens > t.threshold_tokens)
899 .max_by_key(|t| t.threshold_tokens)
900 {
901 base_in = tier.input_per_1k;
902 base_out = tier.output_per_1k;
903 }
904 }
905
906 if card.fast_mode {
908 if let Some(fm) = extras.and_then(|e| e.fast_mode_rates) {
909 base_in = fm.input_per_1k;
910 base_out = fm.output_per_1k;
911 }
912 }
913
914 let tier_mult = match card.tier {
916 PricingTier::Standard | PricingTier::Cached => 1.0,
917 PricingTier::Batch | PricingTier::Flex => 0.5,
918 PricingTier::Priority => match extras.and_then(|e| e.priority_multiplier) {
919 Some(m) => m,
920 None => {
921 return Err(CostError::TierUnavailable {
922 model: model_name.to_string(),
923 tier: "priority".to_string(),
924 })
925 }
926 },
927 };
928
929 let mut platform_mult = 1.0;
931 if card.regional_endpoint
932 && extras
933 .map(|e| e.flags.supports_regional_premium)
934 .unwrap_or(false)
935 {
936 platform_mult *= 1.10;
937 }
938
939 let mut residency_mult = 1.0;
941 if card.data_residency == DataResidency::Us
942 && extras
943 .map(|e| e.flags.supports_data_residency)
944 .unwrap_or(false)
945 {
946 residency_mult *= 1.10;
947 }
948
949 let mult = tier_mult * platform_mult * residency_mult;
950
951 let eff_in = if card.tier == PricingTier::Cached {
955 extras
956 .and_then(|e| e.cache_rates)
957 .map(|c| c.read_per_1k)
958 .unwrap_or(base_in)
959 * mult
960 } else {
961 base_in * mult
962 };
963 let eff_out = base_out * mult;
964
965 let cache_leg_mult = if card.tier == PricingTier::Batch {
967 0.5
968 } else {
969 1.0
970 };
971 let mut cache_cost = 0.0;
972 if let Some(cr) = extras.and_then(|e| e.cache_rates) {
973 cache_cost +=
974 (usage.cache_read_tokens as f64 / 1000.0) * cr.read_per_1k * cache_leg_mult;
975 if let Some(w5) = cr.write_5m_per_1k {
976 cache_cost += (usage.cache_write_5m_tokens as f64 / 1000.0) * w5 * cache_leg_mult;
977 }
978 if let Some(w1) = cr.write_1h_per_1k {
979 cache_cost += (usage.cache_write_1h_tokens as f64 / 1000.0) * w1 * cache_leg_mult;
980 }
981 }
982
983 let input_cost = (usage.input_tokens as f64 / 1000.0) * eff_in;
984 let output_cost = (usage.output_tokens as f64 / 1000.0) * eff_out;
985 let total_cost = input_cost + output_cost + cache_cost;
986
987 Ok(CostEstimate {
988 model_name: model_name.to_string(),
989 input_tokens: usage.input_tokens,
990 output_tokens: usage.output_tokens,
991 input_cost,
992 output_cost,
993 cache_cost,
994 total_cost,
995 currency: "USD".to_string(),
996 })
997 }
998
999 pub fn estimate_cost_on(
1002 &self,
1003 model_name: &str,
1004 input_tokens: usize,
1005 output_tokens: usize,
1006 card: RateCard,
1007 ) -> Result<CostEstimate, CostError> {
1008 self.estimate_cost_with_card(
1009 model_name,
1010 TokenUsage {
1011 input_tokens,
1012 output_tokens,
1013 ..Default::default()
1014 },
1015 card,
1016 )
1017 }
1018
1019 pub fn available_rate_cards(&self) -> Vec<String> {
1022 [
1023 "standard",
1024 "batch",
1025 "cached",
1026 "priority",
1027 "flex",
1028 "first_party:fast",
1029 "first_party:standard,us",
1030 "bedrock:standard",
1031 "bedrock:batch",
1032 "bedrock:standard,regional",
1033 "vertex:standard",
1034 "vertex:batch",
1035 "vertex:standard,regional",
1036 "azure:standard",
1037 "azure:standard,regional",
1038 ]
1039 .into_iter()
1040 .map(String::from)
1041 .collect()
1042 }
1043
1044 pub fn estimate_cache_storage_cost(
1048 &self,
1049 model_name: &str,
1050 cached_tokens: usize,
1051 hours: f64,
1052 ) -> Result<f64, CostError> {
1053 self.pricing_table
1054 .get(model_name)
1055 .ok_or_else(|| CostError::UnknownModel(model_name.to_string()))?;
1056 let rate = self
1057 .extras
1058 .get(model_name)
1059 .and_then(|e| e.cache_storage_per_mtok_hour)
1060 .unwrap_or(0.0);
1061 Ok((cached_tokens as f64 / 1_000_000.0) * rate * hours)
1062 }
1063
1064 pub fn estimate_cost_from_text(
1066 &self,
1067 model_name: &str,
1068 input_text: &str,
1069 estimated_output_tokens: usize,
1070 ) -> Result<CostEstimate, CostError> {
1071 self.estimate_cost_from_text_with_card(
1072 model_name,
1073 input_text,
1074 estimated_output_tokens,
1075 RateCard::default(),
1076 )
1077 }
1078
1079 pub fn estimate_cost_from_text_with_card(
1081 &self,
1082 model_name: &str,
1083 input_text: &str,
1084 estimated_output_tokens: usize,
1085 card: RateCard,
1086 ) -> Result<CostEstimate, CostError> {
1087 let input_tokens = self.estimate_tokens(input_text);
1088 self.estimate_cost_on(model_name, input_tokens, estimated_output_tokens, card)
1089 }
1090
1091 pub fn check_budget(&self, spent: f64, budget: f64) -> BudgetStatus {
1093 if budget <= 0.0 {
1094 return BudgetStatus {
1095 budget_usd: budget,
1096 spent_usd: spent,
1097 remaining_usd: budget - spent,
1098 percent_used: 100.0,
1099 status: BudgetAlert::Exceeded,
1100 };
1101 }
1102
1103 let percent_used = (spent / budget) * 100.0;
1104 let remaining = budget - spent;
1105
1106 let status = match percent_used {
1107 p if p >= 100.0 => BudgetAlert::Exceeded,
1108 p if p >= 95.0 => BudgetAlert::Critical,
1109 p if p >= 80.0 => BudgetAlert::Warning,
1110 _ => BudgetAlert::Ok,
1111 };
1112
1113 BudgetStatus {
1114 budget_usd: budget,
1115 spent_usd: spent,
1116 remaining_usd: remaining,
1117 percent_used: percent_used.min(100.0),
1118 status,
1119 }
1120 }
1121
1122 pub fn get_cheapest_model(&self, min_context_window: usize) -> Option<&ModelPricing> {
1124 self.pricing_table
1125 .values()
1126 .filter(|pricing| pricing.context_window >= min_context_window)
1127 .min_by(|a, b| {
1128 let avg_cost_a = (a.input_cost_per_1k_tokens + a.output_cost_per_1k_tokens) / 2.0;
1129 let avg_cost_b = (b.input_cost_per_1k_tokens + b.output_cost_per_1k_tokens) / 2.0;
1130 avg_cost_a
1131 .partial_cmp(&avg_cost_b)
1132 .unwrap_or(std::cmp::Ordering::Equal)
1133 })
1134 }
1135
1136 pub fn get_models_under_cost(&self, max_cost_per_1k: f64) -> Vec<&ModelPricing> {
1138 self.pricing_table
1139 .values()
1140 .filter(|pricing| {
1141 let avg_cost =
1142 (pricing.input_cost_per_1k_tokens + pricing.output_cost_per_1k_tokens) / 2.0;
1143 avg_cost <= max_cost_per_1k
1144 })
1145 .collect()
1146 }
1147
1148 pub fn get_models_by_provider(&self, provider: &str) -> Vec<&ModelPricing> {
1150 self.pricing_table
1151 .values()
1152 .filter(|pricing| pricing.provider.eq_ignore_ascii_case(provider))
1153 .collect()
1154 }
1155
1156 pub fn compare_models(
1158 &self,
1159 model_a: &str,
1160 model_b: &str,
1161 input_tokens: usize,
1162 output_tokens: usize,
1163 ) -> Result<ModelComparison, CostError> {
1164 let cost_a = self.estimate_cost(model_a, input_tokens, output_tokens)?;
1165 let cost_b = self.estimate_cost(model_b, input_tokens, output_tokens)?;
1166
1167 let savings = cost_a.total_cost - cost_b.total_cost;
1168 let percent_difference = if cost_a.total_cost > 0.0 {
1169 (savings / cost_a.total_cost) * 100.0
1170 } else {
1171 0.0
1172 };
1173
1174 Ok(ModelComparison {
1175 model_a: cost_a,
1176 model_b: cost_b,
1177 cheaper_model: if savings > 0.0 { model_b } else { model_a }.to_string(),
1178 savings: savings.abs(),
1179 percent_difference: percent_difference.abs(),
1180 })
1181 }
1182
1183 pub fn add_model(&mut self, pricing: ModelPricing) {
1185 self.pricing_table
1186 .insert(pricing.model_name.clone(), pricing);
1187 }
1188
1189 pub fn remove_model(&mut self, model_name: &str) -> Option<ModelPricing> {
1191 self.pricing_table.remove(model_name)
1192 }
1193
1194 pub fn get_all_models(&self) -> Vec<&ModelPricing> {
1196 self.pricing_table.values().collect()
1197 }
1198
1199 fn estimate_tokens(&self, text: &str) -> usize {
1201 let char_count = text.len();
1204
1205 let token_estimate = if text.is_ascii() {
1207 (char_count as f64 / 4.0).ceil() as usize
1209 } else {
1210 (char_count as f64 / 3.0).ceil() as usize
1212 };
1213
1214 token_estimate + (token_estimate / 20) }
1217
1218 pub fn project_monthly_cost(
1220 &self,
1221 model_name: &str,
1222 daily_input_tokens: usize,
1223 daily_output_tokens: usize,
1224 days_per_month: f64,
1225 ) -> Result<CostProjection, CostError> {
1226 self.project_monthly_cost_with_card(
1227 model_name,
1228 daily_input_tokens,
1229 daily_output_tokens,
1230 days_per_month,
1231 RateCard::default(),
1232 )
1233 }
1234
1235 pub fn project_monthly_cost_with_card(
1237 &self,
1238 model_name: &str,
1239 daily_input_tokens: usize,
1240 daily_output_tokens: usize,
1241 days_per_month: f64,
1242 card: RateCard,
1243 ) -> Result<CostProjection, CostError> {
1244 let daily_cost =
1245 self.estimate_cost_on(model_name, daily_input_tokens, daily_output_tokens, card)?;
1246 let monthly_cost = daily_cost.total_cost * days_per_month;
1247
1248 Ok(CostProjection {
1249 model_name: model_name.to_string(),
1250 daily_cost: daily_cost.total_cost,
1251 monthly_cost,
1252 annual_cost: monthly_cost * 12.0,
1253 currency: "USD".to_string(),
1254 })
1255 }
1256}
1257
1258impl Default for CostCalculator {
1259 fn default() -> Self {
1260 Self::new()
1261 }
1262}
1263
1264#[derive(Debug, Clone)]
1265pub struct ModelComparison {
1266 pub model_a: CostEstimate,
1267 pub model_b: CostEstimate,
1268 pub cheaper_model: String,
1269 pub savings: f64,
1270 pub percent_difference: f64,
1271}
1272
1273#[derive(Debug, Clone, Serialize, Deserialize)]
1274pub struct CostProjection {
1275 pub model_name: String,
1276 pub daily_cost: f64,
1277 pub monthly_cost: f64,
1278 pub annual_cost: f64,
1279 pub currency: String,
1280}
1281
1282#[derive(Error, Debug, Clone, PartialEq)]
1283pub enum CostError {
1284 #[error("Unknown model: {0}")]
1285 UnknownModel(String),
1286 #[error("Invalid token count")]
1287 InvalidTokenCount,
1288 #[error("Unknown rate card: {0}")]
1289 UnknownRateCard(String),
1290 #[error("Pricing tier '{tier}' is not available for model '{model}'")]
1291 TierUnavailable { model: String, tier: String },
1292}
1293
1294#[cfg(test)]
1295mod tests {
1296 use super::*;
1297
1298 #[test]
1299 fn normalize_model_id_strips_platform_qualifiers() {
1300 for (raw, expected) in [
1301 ("us.amazon.nova-pro-v1:0", "nova-pro"),
1302 ("us.amazon.nova-micro-v1:0", "nova-micro"),
1303 ("eu.anthropic.claude-sonnet-4-6", "claude-sonnet-4-6"),
1304 (
1305 "us.anthropic.claude-haiku-4-5-20251001-v1:0",
1306 "claude-haiku-4-5",
1307 ),
1308 ("amazon.titan-embed-text-v2:0", "titan-embed-text"),
1309 ("cohere.cohere-embed-v3:0", "cohere-embed"),
1310 ("gpt-4o", "gpt-4o"),
1311 ] {
1312 assert_eq!(CostCalculator::normalize_model_id(raw), expected, "{raw}");
1313 }
1314 }
1315
1316 #[test]
1317 fn platform_qualified_bedrock_ids_price_via_normalization() {
1318 let calc = CostCalculator::new();
1319 let direct = calc.estimate_cost("nova-pro", 100_000, 1_000).unwrap();
1320 let qualified = calc
1321 .estimate_cost("us.amazon.nova-pro-v1:0", 100_000, 1_000)
1322 .unwrap();
1323 assert_eq!(direct.total_cost, qualified.total_cost);
1324 assert!((direct.total_cost - (0.08 + 0.0032)).abs() < 1e-9);
1326 }
1327
1328 #[test]
1329 fn nova_and_embedding_models_price_at_bedrock_list_rates() {
1330 let calc = CostCalculator::new();
1331 for (model, input_rate, output_rate, input_tokens, output_tokens) in [
1332 ("nova-premier", 2.5, 12.5, 100_000, 1_000),
1333 ("nova-pro", 0.8, 3.2, 100_000, 1_000),
1334 ("nova-lite", 0.06, 0.24, 100_000, 1_000),
1335 ("nova-micro", 0.035, 0.14, 100_000, 1_000),
1336 ("titan-embed-text", 0.1, 0.0, 8_000, 0),
1337 ("cohere-embed", 0.1, 0.0, 8_000, 0),
1338 ] {
1339 let est = calc
1340 .estimate_cost(model, input_tokens, output_tokens)
1341 .unwrap();
1342 let expected = (input_tokens as f64) * input_rate / 1_000_000.0
1343 + (output_tokens as f64) * output_rate / 1_000_000.0;
1344 assert!(
1345 (est.total_cost - expected).abs() < 1e-9,
1346 "{model}: {} vs {expected}",
1347 est.total_cost
1348 );
1349 }
1350 }
1351
1352 use super::*;
1353
1354 #[test]
1355 fn test_cost_estimation() {
1356 let calculator = CostCalculator::new();
1357
1358 let estimate = calculator.estimate_cost("gpt-4", 1000, 500).unwrap();
1359
1360 assert_eq!(estimate.model_name, "gpt-4");
1361 assert_eq!(estimate.input_tokens, 1000);
1362 assert_eq!(estimate.output_tokens, 500);
1363 assert_eq!(estimate.input_cost, 0.03); assert_eq!(estimate.output_cost, 0.03); assert_eq!(estimate.total_cost, 0.06);
1366 assert_eq!(estimate.currency, "USD");
1367 }
1368
1369 #[test]
1370 fn test_unknown_model() {
1371 let calculator = CostCalculator::new();
1372 let result = calculator.estimate_cost("unknown-model", 1000, 500);
1373
1374 assert!(matches!(result, Err(CostError::UnknownModel(_))));
1375 }
1376
1377 #[test]
1378 fn test_invalid_token_count() {
1379 let calculator = CostCalculator::new();
1380
1381 let result = calculator.estimate_cost("gpt-4", 0, 0);
1383 assert!(matches!(result, Err(CostError::InvalidTokenCount)));
1384
1385 let result = calculator.estimate_cost("gpt-4", 10000, 0);
1387 assert!(matches!(result, Err(CostError::InvalidTokenCount)));
1388
1389 let result = calculator.estimate_cost("gpt-4", 1000, 5000);
1391 assert!(matches!(result, Err(CostError::InvalidTokenCount)));
1392 }
1393
1394 #[test]
1395 fn test_budget_status() {
1396 let calculator = CostCalculator::new();
1397
1398 let status = calculator.check_budget(50.0, 100.0);
1400 assert_eq!(status.status, BudgetAlert::Ok);
1401 assert_eq!(status.percent_used, 50.0);
1402 assert_eq!(status.remaining_usd, 50.0);
1403
1404 let status = calculator.check_budget(85.0, 100.0);
1406 assert_eq!(status.status, BudgetAlert::Warning);
1407
1408 let status = calculator.check_budget(96.0, 100.0);
1410 assert_eq!(status.status, BudgetAlert::Critical);
1411
1412 let status = calculator.check_budget(110.0, 100.0);
1414 assert_eq!(status.status, BudgetAlert::Exceeded);
1415 assert_eq!(status.remaining_usd, -10.0);
1416 }
1417
1418 #[test]
1419 fn test_cheapest_model() {
1420 let calculator = CostCalculator::new();
1421
1422 let cheapest = calculator.get_cheapest_model(8000);
1423 assert!(cheapest.is_some());
1424 let model = cheapest.unwrap();
1425
1426 assert!(model.context_window >= 8000);
1428 }
1429
1430 #[test]
1431 fn test_models_under_cost() {
1432 let calculator = CostCalculator::new();
1433
1434 let cheap_models = calculator.get_models_under_cost(0.01);
1435 assert!(!cheap_models.is_empty());
1436
1437 for model in &cheap_models {
1439 let avg_cost = (model.input_cost_per_1k_tokens + model.output_cost_per_1k_tokens) / 2.0;
1440 assert!(avg_cost <= 0.01);
1441 }
1442 }
1443
1444 #[test]
1445 fn test_models_by_provider() {
1446 let calculator = CostCalculator::new();
1447
1448 let openai_models = calculator.get_models_by_provider("openai");
1449 assert!(!openai_models.is_empty());
1450 for model in &openai_models {
1451 assert_eq!(model.provider, "openai");
1452 }
1453
1454 let anthropic_models = calculator.get_models_by_provider("anthropic");
1455 assert!(!anthropic_models.is_empty());
1456 for model in &anthropic_models {
1457 assert_eq!(model.provider, "anthropic");
1458 }
1459 }
1460
1461 #[test]
1462 fn test_model_comparison() {
1463 let calculator = CostCalculator::new();
1464
1465 let comparison = calculator
1466 .compare_models("gpt-4", "gpt-3.5-turbo", 1000, 500)
1467 .unwrap();
1468
1469 assert_eq!(comparison.cheaper_model, "gpt-3.5-turbo");
1471 assert!(comparison.savings > 0.0);
1472 assert!(comparison.percent_difference > 0.0);
1473 }
1474
1475 #[test]
1476 fn test_cost_from_text() {
1477 let calculator = CostCalculator::new();
1478
1479 let text = "Hello, world!";
1480 let estimate = calculator
1481 .estimate_cost_from_text("gpt-3.5-turbo", text, 100)
1482 .unwrap();
1483
1484 assert!(estimate.input_tokens > 0);
1485 assert_eq!(estimate.output_tokens, 100);
1486 assert!(estimate.total_cost > 0.0);
1487 }
1488
1489 #[test]
1490 fn test_token_estimation() {
1491 let calculator = CostCalculator::new();
1492
1493 let english_text = "Hello, world! This is a test.";
1495 let tokens = calculator.estimate_tokens(english_text);
1496
1497 let expected = ((english_text.len() as f64 / 4.0).ceil() as usize * 105) / 100; assert!(tokens >= expected - 2 && tokens <= expected + 2);
1500
1501 assert_eq!(calculator.estimate_tokens(""), 0);
1503 }
1504
1505 #[test]
1506 fn test_custom_model() {
1507 let mut calculator = CostCalculator::new();
1508
1509 let custom_model = ModelPricing {
1510 model_name: "custom-model".to_string(),
1511 provider: "custom".to_string(),
1512 input_cost_per_1k_tokens: 0.001,
1513 output_cost_per_1k_tokens: 0.002,
1514 context_window: 4096,
1515 max_output_tokens: Some(2048),
1516 };
1517
1518 calculator.add_model(custom_model.clone());
1519
1520 let estimate = calculator.estimate_cost("custom-model", 1000, 500).unwrap();
1521 assert_eq!(estimate.input_cost, 0.001);
1522 assert_eq!(estimate.output_cost, 0.001);
1523 assert_eq!(estimate.total_cost, 0.002);
1524
1525 let removed = calculator.remove_model("custom-model");
1527 assert!(removed.is_some());
1528 assert_eq!(removed.unwrap().model_name, "custom-model");
1529
1530 let result = calculator.estimate_cost("custom-model", 1000, 500);
1532 assert!(matches!(result, Err(CostError::UnknownModel(_))));
1533 }
1534
1535 #[test]
1536 fn test_cost_projection() {
1537 let calculator = CostCalculator::new();
1538
1539 let projection = calculator
1540 .project_monthly_cost("gpt-4", 4000, 2000, 30.0)
1541 .unwrap();
1542
1543 assert_eq!(projection.model_name, "gpt-4");
1544 assert!(projection.daily_cost > 0.0);
1545 assert_eq!(projection.monthly_cost, projection.daily_cost * 30.0);
1546 assert_eq!(projection.annual_cost, projection.monthly_cost * 12.0);
1547 }
1548
1549 #[test]
1550 fn test_all_default_models_available() {
1551 let calculator = CostCalculator::new();
1552
1553 let test_models = [
1555 "gpt-4",
1557 "gpt-4-turbo",
1558 "gpt-3.5-turbo",
1559 "gpt-4o",
1560 "gpt-4o-mini",
1561 "claude-3-opus",
1562 "claude-3-sonnet",
1563 "claude-3-haiku",
1564 "claude-3-5-sonnet",
1565 "gemini-pro",
1566 "gemini-ultra",
1567 "claude-opus-4-8",
1569 "claude-opus-4-7",
1570 "claude-opus-4-6",
1571 "claude-opus-4-5",
1572 "claude-opus-4-1",
1573 "claude-sonnet-4-6",
1574 "claude-sonnet-4-5",
1575 "claude-haiku-4-5",
1576 "claude-haiku-3-5",
1577 "gpt-5.5",
1578 "gpt-5.5-pro",
1579 "gpt-5.4",
1580 "gpt-5.4-mini",
1581 "gpt-5.4-nano",
1582 "gpt-5.4-pro",
1583 "gemini-3.5-flash",
1584 "gemini-3.1-pro",
1585 "gemini-3.1-flash-lite",
1586 "gemini-3-flash",
1587 "gemini-2.5-pro",
1588 "gemini-2.5-flash",
1589 "gemini-2.5-flash-lite",
1590 ];
1591
1592 for model in &test_models {
1593 let result = calculator.estimate_cost(model, 1000, 500);
1594 assert!(result.is_ok(), "Model {} should be available", model);
1595 }
1596 }
1597
1598 #[test]
1599 fn test_rate_card_default_equals_standard() {
1600 let calc = CostCalculator::new();
1601 let plain = calc.estimate_cost("claude-opus-4-8", 1000, 500).unwrap();
1602 let standard = calc
1603 .estimate_cost_on(
1604 "claude-opus-4-8",
1605 1000,
1606 500,
1607 RateCard::parse("standard").unwrap(),
1608 )
1609 .unwrap();
1610 let default = calc
1611 .estimate_cost_on("claude-opus-4-8", 1000, 500, RateCard::default())
1612 .unwrap();
1613 assert_eq!(plain.total_cost, standard.total_cost);
1614 assert_eq!(plain.total_cost, default.total_cost);
1615 assert_eq!(plain.cache_cost, 0.0);
1616 }
1617
1618 #[test]
1619 fn test_rate_card_batch_is_half() {
1620 let calc = CostCalculator::new();
1621 let standard = calc
1623 .estimate_cost("claude-opus-4-8", 500_000, 50_000)
1624 .unwrap();
1625 let batch = calc
1626 .estimate_cost_on(
1627 "claude-opus-4-8",
1628 500_000,
1629 50_000,
1630 RateCard::parse("batch").unwrap(),
1631 )
1632 .unwrap();
1633 assert!((batch.total_cost - 0.5 * standard.total_cost).abs() < 1e-9);
1634 }
1635
1636 #[test]
1637 fn test_rate_card_cache_read_is_tenth_of_input() {
1638 let calc = CostCalculator::new();
1639 let usage = TokenUsage {
1640 input_tokens: 0,
1641 output_tokens: 1000,
1642 cache_read_tokens: 100_000,
1643 ..Default::default()
1644 };
1645 let est = calc
1646 .estimate_cost_with_card("claude-opus-4-8", usage, RateCard::default())
1647 .unwrap();
1648 let base_input_for_100k = (100_000.0 / 1000.0) * 0.005;
1650 assert!((est.cache_cost - 0.1 * base_input_for_100k).abs() < 1e-9);
1651 }
1652
1653 #[test]
1654 fn test_rate_card_bedrock_regional_premium() {
1655 let calc = CostCalculator::new();
1656 let standard = calc.estimate_cost("claude-opus-4-8", 1000, 500).unwrap();
1657 let regional = calc
1658 .estimate_cost_on(
1659 "claude-opus-4-8",
1660 1000,
1661 500,
1662 RateCard::parse("bedrock:regional").unwrap(),
1663 )
1664 .unwrap();
1665 assert!((regional.total_cost - 1.10 * standard.total_cost).abs() < 1e-9);
1666 }
1667
1668 #[test]
1669 fn test_rate_card_data_residency_premium() {
1670 let calc = CostCalculator::new();
1671 let standard = calc.estimate_cost("claude-sonnet-4-6", 1000, 500).unwrap();
1672 let us = calc
1673 .estimate_cost_on(
1674 "claude-sonnet-4-6",
1675 1000,
1676 500,
1677 RateCard::parse("first_party:standard,us").unwrap(),
1678 )
1679 .unwrap();
1680 assert!((us.total_cost - 1.10 * standard.total_cost).abs() < 1e-9);
1681 }
1682
1683 #[test]
1684 fn test_rate_card_fast_mode_override() {
1685 let calc = CostCalculator::new();
1686 let fast = calc
1688 .estimate_cost_on(
1689 "claude-opus-4-8",
1690 1000,
1691 1000,
1692 RateCard::parse("fast").unwrap(),
1693 )
1694 .unwrap();
1695 let expected = (1000.0 / 1000.0) * 0.010 + (1000.0 / 1000.0) * 0.050;
1696 assert!((fast.total_cost - expected).abs() < 1e-9);
1697 let standard = calc.estimate_cost("claude-opus-4-8", 1000, 1000).unwrap();
1698 assert!(fast.total_cost > standard.total_cost);
1699 }
1700
1701 #[test]
1702 fn test_rate_card_long_context_tier() {
1703 let calc = CostCalculator::new();
1704 let below = calc.estimate_cost("gemini-2.5-pro", 150_000, 1000).unwrap();
1706 let above = calc.estimate_cost("gemini-2.5-pro", 250_000, 1000).unwrap();
1707 assert!((below.input_cost - (150_000.0 / 1000.0) * 0.00125).abs() < 1e-9);
1708 assert!((above.input_cost - (250_000.0 / 1000.0) * 0.0025).abs() < 1e-9);
1709 }
1710
1711 #[test]
1712 fn test_rate_card_priority_and_errors() {
1713 assert!(matches!(
1715 RateCard::parse("totally-bogus"),
1716 Err(CostError::UnknownRateCard(_))
1717 ));
1718
1719 let calc = CostCalculator::new();
1720 let standard = calc.estimate_cost("gpt-5.5", 1000, 500).unwrap();
1722 let priority = calc
1723 .estimate_cost_on("gpt-5.5", 1000, 500, RateCard::parse("priority").unwrap())
1724 .unwrap();
1725 assert!((priority.total_cost - 2.5 * standard.total_cost).abs() < 1e-9);
1726
1727 let unavailable = calc.estimate_cost_on(
1728 "gpt-5.4-pro",
1729 1000,
1730 500,
1731 RateCard::parse("priority").unwrap(),
1732 );
1733 assert!(matches!(
1734 unavailable,
1735 Err(CostError::TierUnavailable { .. })
1736 ));
1737 }
1738
1739 #[test]
1740 fn test_cache_storage_cost() {
1741 let calc = CostCalculator::new();
1742 let cost = calc
1744 .estimate_cache_storage_cost("gemini-2.5-pro", 1_000_000, 2.0)
1745 .unwrap();
1746 assert!((cost - 9.0).abs() < 1e-9);
1747 let none = calc
1749 .estimate_cache_storage_cost("gpt-4", 1_000_000, 2.0)
1750 .unwrap();
1751 assert_eq!(none, 0.0);
1752 }
1753}