Skip to main content

adk_model/
pricing.rs

1//! Token prices for every provider and cost calculation from [`UsageMetadata`],
2//! plus per-unit prices for models billed per image, per second of audio or per character.
3//!
4//! [`PricingCatalog`] is the single table `adk-model` uses to fill
5//! [`UsageMetadata::cost`](adk_core::UsageMetadata::cost) on provider responses that do not report a cost
6//! themselves. It consolidates the vendor tables in `adk_gemini::pricing`,
7//! `adk_model::openai::pricing` and `adk_anthropic::pricing` (tests keep the
8//! rates in step) and adds DeepSeek, Groq, xAI and Mistral list prices. Every
9//! rate is USD per one million tokens.
10//!
11//! # Usage normalization
12//!
13//! `adk-model` providers report `prompt_token_count` *including* cache reads
14//! and cache writes, and `candidates_token_count` including thinking tokens.
15//! The catalog bills each prompt token once:
16//!
17//! | Tokens | Rate |
18//! |--------|------|
19//! | `prompt − cache reads − cache writes` | `input` |
20//! | `cache_read_input_token_count` | `cache_read` |
21//! | 5-minute cache writes | `cache_write_5m` |
22//! | 1-hour cache writes (Anthropic `cache_creation_input_tokens_1h`) | `cache_write_1h` |
23//! | `candidates_token_count` | `output` |
24//!
25//! # Model resolution
26//!
27//! Lookup strips resource prefixes (`models/`, `publishers/…/models/`,
28//! `vendor/`), Bedrock region and vendor prefixes (`us.anthropic.`) and
29//! version suffixes (`-v1:0`), then matches the identifier exactly or as a
30//! dated alias of a listed model: `claude-sonnet-4-5-20250929`,
31//! `gpt-4.1-2025-04-14` and `claude-sonnet-4-5@20250929` resolve, while an
32//! unlisted point release such as `claude-opus-4-9` does not.
33//!
34//! A vendor's list price applies only to providers that bill it: Google rates
35//! to `gemini` and `openrouter`; OpenAI rates to `openai`, `openai-responses`,
36//! `azure-openai`, `azure-ai` and `openrouter`; Anthropic rates to `anthropic`,
37//! `bedrock`, `azure-ai` and `openrouter`; DeepSeek rates to `deepseek`; Groq
38//! rates to `groq`; xAI rates to `xai` and `openrouter`; Mistral rates to
39//! `mistral` and `openrouter`. `ollama` runs locally and costs zero, except
40//! `*cloud*` models.
41//!
42//! # Limitations
43//!
44//! - Standard tier only: batch, flex, priority, fast mode, data-residency and
45//!   regional uplifts are not applied.
46//! - Image, audio and realtime output rates are not modelled; models whose
47//!   output is billed by modality are left out, so they resolve to `None`.
48//! - Cache storage (Gemini per-hour storage) is not a per-request cost.
49//! - Built-in tool fees ([`BuiltinToolFee`])
50//!   apply on the vendor's own API only, ignore free allowances, and leave
51//!   container-billed tools unpriced.
52//! - DeepSeek's off-peak discount ([`OffPeak`]) applies outside the published
53//!   UTC peak hours on weekdays; Chinese public holidays, which are off-peak in
54//!   full, are billed at the peak rate, which over-estimates.
55//! - Models a vendor prices only on request ("Contact Sales") are left out:
56//!   Groq's Llama models.
57//!
58//! `None` from [`PricingCatalog::cost_usd`] means the cost is unknown, never
59//! that the request was free.
60//!
61//! # Per-unit prices
62//!
63//! Models billed in units rather than tokens carry a [`UnitPrice`]: an
64//! [`adk_core::UnitRate`] per [`adk_core::UsageUnit`]. [`PricingCatalog::unit_cost_micro_usd`]
65//! prices a [`UsageVector`], both the most a call can use (its
66//! spend hold) and what it used.
67//!
68//! | Model | Unit | Price |
69//! |-------|------|-------|
70//! | `muse-image-1.0` | images returned | $0.01 per image |
71//! | `muse-voice-transcribe-1.0` | audio milliseconds, billed in whole seconds rounded down | $0.18 per hour |
72//! | `sam-3.1` | images segmented | $2.50 per 1,000 images |
73//! | `sam-3.1` | video frames segmented | $0.20 per 1,000 frames, at least 50 frames per request |
74//!
75//! # Example
76//!
77//! ```
78//! use adk_core::UsageMetadata;
79//! use adk_model::pricing::PricingCatalog;
80//!
81//! let usage = UsageMetadata {
82//!     prompt_token_count: 1_000_000,
83//!     candidates_token_count: 100_000,
84//!     total_token_count: 1_100_000,
85//!     cache_read_input_token_count: Some(400_000),
86//!     ..Default::default()
87//! };
88//! // 600K uncached at $2.00 + 400K cached at $0.50 + 100K output at $8.00.
89//! let cost = PricingCatalog::standard().cost_usd(Some("openai"), "gpt-4.1", &usage).unwrap();
90//! assert!((cost - 2.20).abs() < 1e-9);
91//! assert!(PricingCatalog::standard().cost_usd(Some("openai"), "my-fine-tune", &usage).is_none());
92//! ```
93
94use adk_core::{LlmRequest, Part, UnitRate, UsageMetadata, UsageUnit, UsageVector};
95use chrono::NaiveDate;
96use std::sync::LazyLock;
97
98/// Date the standard catalog's rates were last verified against the vendors'
99/// published price lists.
100pub const PRICING_EFFECTIVE_DATE: &str = "2026-11-17";
101
102/// The vendor whose published list price a [`ModelPrice`] carries.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104#[non_exhaustive]
105pub enum PriceVendor {
106    /// Google Gemini.
107    Google,
108    /// OpenAI.
109    OpenAI,
110    /// Anthropic Claude.
111    Anthropic,
112    /// DeepSeek.
113    DeepSeek,
114    /// Groq, which hosts open-weight models at its own prices.
115    Groq,
116    /// Meta Muse Spark models served by the Meta Model API.
117    Meta,
118    /// xAI Grok.
119    XAi,
120    /// Mistral AI.
121    Mistral,
122}
123
124impl PriceVendor {
125    /// Returns `true` when `provider` bills this vendor's models at list price.
126    pub fn billed_by(self, provider: &str) -> bool {
127        match self {
128            Self::Google => matches!(provider, "gemini" | "openrouter"),
129            Self::OpenAI => matches!(
130                provider,
131                "openai" | "openai-responses" | "azure-openai" | "azure-ai" | "openrouter"
132            ),
133            Self::Anthropic => {
134                matches!(provider, "anthropic" | "bedrock" | "azure-ai" | "openrouter")
135            }
136            Self::DeepSeek => provider == "deepseek",
137            Self::Groq => provider == "groq",
138            Self::Meta => provider == "muse",
139            Self::XAi => matches!(provider, "xai" | "openrouter"),
140            Self::Mistral => matches!(provider, "mistral" | "openrouter"),
141        }
142    }
143}
144
145impl PriceVendor {
146    /// Returns `true` when `provider` is the vendor's own API, the only place its
147    /// published built-in tool fees apply.
148    pub fn first_party(self, provider: &str) -> bool {
149        match self {
150            Self::Google => provider == "gemini",
151            Self::OpenAI => matches!(provider, "openai" | "openai-responses"),
152            Self::Anthropic => provider == "anthropic",
153            Self::DeepSeek => provider == "deepseek",
154            Self::Groq => provider == "groq",
155            Self::Meta => provider == "muse",
156            Self::XAi => provider == "xai",
157            Self::Mistral => provider == "mistral",
158        }
159    }
160}
161
162/// How a [`BuiltinToolFee`] is charged.
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum FeeUnit {
165    /// Once per reported use, such as one search query.
166    PerUse,
167    /// Once per response that used the tool at all, such as one grounded prompt.
168    PerResponse,
169}
170
171/// A vendor's fee for a provider-executed built-in tool, on top of token costs.
172///
173/// `kind` is a [`BuiltinToolUse::kind`](adk_core::BuiltinToolUse::kind). The fee
174/// applies to every model of the vendor unless restricted with
175/// [`for_models`](Self::for_models).
176///
177/// # Example
178///
179/// ```
180/// use adk_model::pricing::{BuiltinToolFee, PriceVendor};
181///
182/// let fee = BuiltinToolFee::per_use(PriceVendor::Google, "google_search", 0.014)
183///     .for_models(["gemini-3*"]);
184/// assert!(fee.applies_to("gemini-3.8-flash"));
185/// assert!(!fee.applies_to("gemma-4-31b-it"));
186/// assert!((fee.cost_usd(3) - 0.042).abs() < 1e-12);
187/// ```
188#[derive(Debug, Clone, PartialEq)]
189pub struct BuiltinToolFee {
190    /// Vendor whose published fee this is.
191    pub vendor: PriceVendor,
192    /// Built-in tool kind the fee applies to.
193    pub kind: String,
194    /// Model identifiers the fee applies to; empty means every model. An entry
195    /// ending in `*` is a prefix; any other entry matches exactly or as a dated alias.
196    pub models: Vec<String>,
197    /// Fee in USD per [`unit`](Self::unit).
198    pub usd: f64,
199    /// What one fee is charged for.
200    pub unit: FeeUnit,
201}
202
203impl BuiltinToolFee {
204    /// A fee of `usd` per use of `kind`.
205    pub fn per_use(vendor: PriceVendor, kind: impl Into<String>, usd: f64) -> Self {
206        Self { vendor, kind: kind.into(), models: Vec::new(), usd, unit: FeeUnit::PerUse }
207    }
208
209    /// A fee of `usd` per response that used `kind` at least once.
210    pub fn per_response(vendor: PriceVendor, kind: impl Into<String>, usd: f64) -> Self {
211        Self { unit: FeeUnit::PerResponse, ..Self::per_use(vendor, kind, usd) }
212    }
213
214    /// Restricts the fee to `models`.
215    pub fn for_models(mut self, models: impl IntoIterator<Item = impl Into<String>>) -> Self {
216        self.models = models.into_iter().map(Into::into).collect();
217        self
218    }
219
220    /// Whether the fee applies to `model`.
221    pub fn applies_to(&self, model: &str) -> bool {
222        if self.models.is_empty() {
223            return true;
224        }
225        let canonical = canonical_model_id(model);
226        self.models.iter().any(|pattern| match pattern.strip_suffix('*') {
227            Some(prefix) => canonical.starts_with(prefix),
228            None => {
229                canonical == *pattern
230                    || canonical.strip_prefix(pattern.as_str()).is_some_and(is_version_suffix)
231            }
232        })
233    }
234
235    /// Fee in USD for `count` uses in one response.
236    pub fn cost_usd(&self, count: u32) -> f64 {
237        match self.unit {
238            FeeUnit::PerUse => f64::from(count) * self.usd,
239            FeeUnit::PerResponse if count > 0 => self.usd,
240            FeeUnit::PerResponse => 0.0,
241        }
242    }
243}
244
245/// Per-million-token prices for one rate card.
246#[derive(Debug, Clone, Copy, PartialEq)]
247pub struct ModelRates {
248    /// Uncached input tokens.
249    pub input: f64,
250    /// Output tokens, including thinking tokens.
251    pub output: f64,
252    /// Input tokens read from a cache.
253    pub cache_read: f64,
254    /// Input tokens written to a 5-minute (or untyped) cache entry.
255    pub cache_write_5m: f64,
256    /// Input tokens written to a 1-hour cache entry.
257    pub cache_write_1h: f64,
258}
259
260impl ModelRates {
261    /// Rates with cache reads and writes billed at the input rate.
262    ///
263    /// # Example
264    ///
265    /// ```
266    /// use adk_model::pricing::ModelRates;
267    ///
268    /// let rates = ModelRates::new(2.0, 8.0).with_cache_read(0.5);
269    /// assert_eq!(rates.cache_read, 0.5);
270    /// assert_eq!(rates.cache_write_5m, 2.0);
271    /// ```
272    pub const fn new(input: f64, output: f64) -> Self {
273        Self { input, output, cache_read: input, cache_write_5m: input, cache_write_1h: input }
274    }
275
276    /// Sets the cache-read rate.
277    pub const fn with_cache_read(mut self, rate: f64) -> Self {
278        self.cache_read = rate;
279        self
280    }
281
282    /// Sets the 5-minute and 1-hour cache-write rates.
283    pub const fn with_cache_writes(mut self, five_minute: f64, one_hour: f64) -> Self {
284        self.cache_write_5m = five_minute;
285        self.cache_write_1h = one_hour;
286        self
287    }
288}
289
290/// A rate card that replaces the base rates once a prompt reaches a size.
291#[derive(Debug, Clone, Copy, PartialEq)]
292pub struct LongContextTier {
293    /// Smallest prompt, cache reads and writes included, billed at `rates`.
294    pub min_prompt_tokens: u64,
295    /// Rates for the whole request once the threshold is reached.
296    pub rates: ModelRates,
297}
298
299/// A scheduled change to a model's rates.
300#[derive(Debug, Clone, Copy, PartialEq)]
301pub struct RateChange {
302    /// First day (UTC) the new rates apply.
303    pub effective: NaiveDate,
304    /// Rates from `effective` onward.
305    pub rates: ModelRates,
306}
307
308/// The price of one model.
309#[derive(Debug, Clone, PartialEq)]
310pub struct ModelPrice {
311    /// Vendor whose list price this is.
312    pub vendor: PriceVendor,
313    /// Canonical model identifier.
314    pub model: String,
315    /// Base rate card.
316    pub rates: ModelRates,
317    /// Long-context rate card, when the vendor publishes one.
318    pub long_context: Option<LongContextTier>,
319    /// Scheduled change to the base rates, such as the end of an introductory price.
320    pub change: Option<RateChange>,
321    /// Largest output, reasoning included, the model produces for one request; used to
322    /// bound a request that sets no output cap.
323    pub max_output_tokens: Option<u64>,
324    /// The most tokens a request may carry, as the vendor publishes it: the stated maximum
325    /// input where the vendor gives one, else the context window. Auto-compaction compacts
326    /// an agent's history before a request nears it.
327    pub context_window_tokens: Option<u64>,
328    /// Discounted rates outside the vendor's peak hours.
329    pub off_peak: Option<OffPeak>,
330}
331
332/// A time-of-day discount: outside the peak windows every rate is multiplied by `factor`.
333///
334/// # Example
335///
336/// ```
337/// use adk_model::pricing::OffPeak;
338/// use chrono::{TimeZone, Utc};
339///
340/// // DeepSeek: peak 01:00–04:00 and 06:00–10:00 UTC on weekdays, half price otherwise.
341/// let off_peak = OffPeak::weekdays(0.5, &[(1, 4), (6, 10)]);
342/// assert!(off_peak.is_peak(Utc.with_ymd_and_hms(2026, 10, 12, 7, 30, 0).unwrap()));
343/// assert!(!off_peak.is_peak(Utc.with_ymd_and_hms(2026, 10, 12, 12, 0, 0).unwrap()));
344/// assert!(!off_peak.is_peak(Utc.with_ymd_and_hms(2026, 10, 11, 7, 30, 0).unwrap()));
345/// ```
346#[derive(Debug, Clone, PartialEq)]
347pub struct OffPeak {
348    /// Multiplier applied to every rate off peak.
349    pub factor: f64,
350    /// Peak windows as `[start, end)` UTC hours, Monday through Friday.
351    pub peak_hours_utc: Vec<(u32, u32)>,
352}
353
354impl OffPeak {
355    /// Peak during `peak_hours_utc` on weekdays; `factor` applies at all other times.
356    pub fn weekdays(factor: f64, peak_hours_utc: &[(u32, u32)]) -> Self {
357        Self { factor, peak_hours_utc: peak_hours_utc.to_vec() }
358    }
359
360    /// Whether `at` falls in a peak window.
361    pub fn is_peak(&self, at: chrono::DateTime<chrono::Utc>) -> bool {
362        use chrono::{Datelike, Timelike, Weekday};
363        if matches!(at.weekday(), Weekday::Sat | Weekday::Sun) {
364            return false;
365        }
366        let hour = at.hour();
367        self.peak_hours_utc.iter().any(|(start, end)| hour >= *start && hour < *end)
368    }
369}
370
371impl ModelPrice {
372    /// Creates a price with only base rates.
373    pub fn new(vendor: PriceVendor, model: impl Into<String>, rates: ModelRates) -> Self {
374        Self {
375            vendor,
376            model: model.into(),
377            rates,
378            long_context: None,
379            change: None,
380            max_output_tokens: None,
381            context_window_tokens: None,
382            off_peak: None,
383        }
384    }
385
386    /// Discounts every rate outside the peak windows of `off_peak`.
387    pub fn with_off_peak(mut self, off_peak: OffPeak) -> Self {
388        self.off_peak = Some(off_peak);
389        self
390    }
391
392    /// Sets the model's maximum output tokens per request.
393    pub fn with_max_output_tokens(mut self, tokens: u64) -> Self {
394        self.max_output_tokens = Some(tokens);
395        self
396    }
397
398    /// Sets the most tokens a request to the model may carry.
399    pub fn with_context_window(mut self, tokens: u64) -> Self {
400        self.context_window_tokens = Some(tokens);
401        self
402    }
403
404    /// Upper bound in USD on a request of at most `prompt_tokens` input tokens and
405    /// `output_tokens` output tokens, priced on `date`.
406    ///
407    /// Every input token is priced at the highest input-side rate (uncached, cache read
408    /// or cache write) of the tier the prompt bound falls in, so cache writes and
409    /// long-context switches never push the actual cost above the bound.
410    pub fn max_cost_usd(&self, prompt_tokens: u64, output_tokens: u64, date: NaiveDate) -> f64 {
411        let rates = self.rates_for(prompt_tokens, date);
412        let input =
413            rates.input.max(rates.cache_read).max(rates.cache_write_5m).max(rates.cache_write_1h);
414        (prompt_tokens as f64 * input + output_tokens as f64 * rates.output) / 1_000_000.0
415    }
416
417    /// Adds a long-context tier.
418    pub fn with_long_context(mut self, min_prompt_tokens: u64, rates: ModelRates) -> Self {
419        self.long_context = Some(LongContextTier { min_prompt_tokens, rates });
420        self
421    }
422
423    /// Schedules new base rates from `effective` onward.
424    pub fn with_change(mut self, effective: NaiveDate, rates: ModelRates) -> Self {
425        self.change = Some(RateChange { effective, rates });
426        self
427    }
428
429    /// The rate card for a prompt of `prompt_tokens` on `date`.
430    pub fn rates_for(&self, prompt_tokens: u64, date: NaiveDate) -> ModelRates {
431        if let Some(tier) = self.long_context
432            && prompt_tokens >= tier.min_prompt_tokens
433        {
434            return tier.rates;
435        }
436        match self.change {
437            Some(change) if date >= change.effective => change.rates,
438            _ => self.rates,
439        }
440    }
441
442    /// Cost in USD of one response's usage, priced on `date`.
443    ///
444    /// # Example
445    ///
446    /// ```
447    /// use adk_core::UsageMetadata;
448    /// use adk_model::pricing::{ModelPrice, ModelRates, PriceVendor};
449    ///
450    /// let price = ModelPrice::new(PriceVendor::Google, "my-model", ModelRates::new(1.0, 4.0));
451    /// let usage = UsageMetadata {
452    ///     prompt_token_count: 500_000,
453    ///     candidates_token_count: 250_000,
454    ///     ..Default::default()
455    /// };
456    /// let today = chrono::Utc::now().date_naive();
457    /// assert!((price.cost_usd(&usage, today) - 1.5).abs() < 1e-9);
458    /// ```
459    pub fn cost_usd(&self, usage: &UsageMetadata, date: NaiveDate) -> f64 {
460        self.cost_with_rates(usage, self.rates_for(non_negative(usage.prompt_token_count), date))
461    }
462
463    /// Cost in USD of one response's usage at the instant `at`, with any off-peak
464    /// discount applied.
465    pub fn cost_usd_at(&self, usage: &UsageMetadata, at: chrono::DateTime<chrono::Utc>) -> f64 {
466        let mut rates = self.rates_for(non_negative(usage.prompt_token_count), at.date_naive());
467        if let Some(off_peak) = &self.off_peak
468            && !off_peak.is_peak(at)
469        {
470            rates = ModelRates {
471                input: rates.input * off_peak.factor,
472                output: rates.output * off_peak.factor,
473                cache_read: rates.cache_read * off_peak.factor,
474                cache_write_5m: rates.cache_write_5m * off_peak.factor,
475                cache_write_1h: rates.cache_write_1h * off_peak.factor,
476            };
477        }
478        self.cost_with_rates(usage, rates)
479    }
480
481    fn cost_with_rates(&self, usage: &UsageMetadata, rates: ModelRates) -> f64 {
482        let prompt = non_negative(usage.prompt_token_count);
483        let cache_read = non_negative(usage.cache_read_input_token_count.unwrap_or(0));
484        let cache_write = non_negative(usage.cache_creation_input_token_count.unwrap_or(0));
485        let write_1h = one_hour_cache_writes(usage).min(cache_write);
486        let write_5m = cache_write - write_1h;
487        let uncached = prompt.saturating_sub(cache_read.saturating_add(cache_write));
488        let output = non_negative(usage.candidates_token_count);
489        (uncached as f64 * rates.input
490            + cache_read as f64 * rates.cache_read
491            + write_5m as f64 * rates.cache_write_5m
492            + write_1h as f64 * rates.cache_write_1h
493            + output as f64 * rates.output)
494            / 1_000_000.0
495    }
496}
497
498/// A vendor's list price for one model billed in units rather than tokens.
499///
500/// # Example
501///
502/// ```
503/// use adk_core::{UnitRate, UsageUnit, UsageVector};
504/// use adk_model::pricing::{PriceVendor, PricingCatalog, UnitPrice};
505///
506/// let catalog = PricingCatalog::new("internal").with_unit_price(UnitPrice::new(
507///     PriceVendor::Meta,
508///     "muse-image-1.0",
509///     UnitRate::new(UsageUnit::Images, 10_000, 1),
510/// ));
511/// let four = UsageVector::new().with(UsageUnit::Images, 4);
512/// assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "muse-image-1.0", &four), Some(40_000));
513/// ```
514#[derive(Debug, Clone, PartialEq, Eq)]
515pub struct UnitPrice {
516    /// Vendor whose published price this is.
517    pub vendor: PriceVendor,
518    /// Model identifier, matched as [`PricingCatalog::lookup`] matches token prices.
519    pub model: String,
520    /// The price per unit.
521    pub rate: UnitRate,
522}
523
524impl UnitPrice {
525    /// `rate` for `model`, as published by `vendor`.
526    pub fn new(vendor: PriceVendor, model: impl Into<String>, rate: UnitRate) -> Self {
527        Self { vendor, model: model.into(), rate }
528    }
529}
530
531/// A table of model prices, looked up by provider and model identifier.
532///
533/// [`PricingCatalog::standard`] is the table every `adk-model` provider uses.
534/// Build a custom table with [`PricingCatalog::new`] and
535/// [`with_price`](Self::with_price) to price fine-tuned or self-hosted models
536/// in your own [`Llm`](adk_core::Llm) implementations.
537///
538/// # Example
539///
540/// ```
541/// use adk_core::UsageMetadata;
542/// use adk_model::pricing::{ModelPrice, ModelRates, PriceVendor, PricingCatalog};
543///
544/// let catalog = PricingCatalog::new("internal-2026-10")
545///     .with_price(ModelPrice::new(PriceVendor::OpenAI, "ft-support-bot", ModelRates::new(3.0, 12.0)));
546/// let usage = UsageMetadata { prompt_token_count: 1_000_000, ..Default::default() };
547/// assert_eq!(catalog.cost_usd(None, "ft-support-bot", &usage), Some(3.0));
548/// assert_eq!(catalog.version(), "internal-2026-10");
549/// ```
550#[derive(Debug, Clone)]
551pub struct PricingCatalog {
552    version: String,
553    prices: Vec<ModelPrice>,
554    fees: Vec<BuiltinToolFee>,
555    units: Vec<UnitPrice>,
556}
557
558impl PricingCatalog {
559    /// Creates an empty catalog labelled `version`.
560    pub fn new(version: impl Into<String>) -> Self {
561        Self { version: version.into(), prices: Vec::new(), fees: Vec::new(), units: Vec::new() }
562    }
563
564    /// The standard catalog of published list prices, verified on
565    /// [`PRICING_EFFECTIVE_DATE`].
566    pub fn standard() -> &'static PricingCatalog {
567        static STANDARD: LazyLock<PricingCatalog> = LazyLock::new(standard_catalog);
568        &STANDARD
569    }
570
571    /// Adds or replaces the price for `price.model`.
572    pub fn with_price(mut self, price: ModelPrice) -> Self {
573        self.prices.retain(|existing| existing.model != price.model);
574        self.prices.push(price);
575        self
576    }
577
578    /// Version label; for the standard catalog, the verification date.
579    pub fn version(&self) -> &str {
580        &self.version
581    }
582
583    /// Every price in the catalog.
584    pub fn prices(&self) -> &[ModelPrice] {
585        &self.prices
586    }
587
588    /// Adds a built-in tool fee. Fees are matched in the order they were added.
589    ///
590    /// # Example
591    ///
592    /// ```
593    /// use adk_core::{BuiltinToolUse, UsageMetadata};
594    /// use adk_model::pricing::{
595    ///     BuiltinToolFee, ModelPrice, ModelRates, PriceVendor, PricingCatalog,
596    /// };
597    ///
598    /// let catalog = PricingCatalog::new("internal")
599    ///     .with_price(ModelPrice::new(PriceVendor::Anthropic, "my-claude", ModelRates::new(1.0, 5.0)))
600    ///     .with_builtin_tool_fee(BuiltinToolFee::per_use(PriceVendor::Anthropic, "web_search", 0.01));
601    /// let usage = UsageMetadata {
602    ///     builtin_tool_uses: vec![BuiltinToolUse::new("web_search", 2)],
603    ///     ..Default::default()
604    /// };
605    /// assert_eq!(catalog.cost_usd(Some("anthropic"), "my-claude", &usage), Some(0.02));
606    /// ```
607    pub fn with_builtin_tool_fee(mut self, fee: BuiltinToolFee) -> Self {
608        self.fees.push(fee);
609        self
610    }
611
612    /// Every built-in tool fee in the catalog.
613    pub fn builtin_tool_fees(&self) -> &[BuiltinToolFee] {
614        &self.fees
615    }
616
617    /// Adds or replaces the price of `price.model` in `price.rate.unit`.
618    pub fn with_unit_price(mut self, price: UnitPrice) -> Self {
619        self.units.retain(|existing| {
620            existing.model != price.model || existing.rate.unit != price.rate.unit
621        });
622        self.units.push(price);
623        self
624    }
625
626    /// Every per-unit price in the catalog.
627    pub fn unit_prices(&self) -> &[UnitPrice] {
628        &self.units
629    }
630
631    /// Resolves the price of `unit` on `model` as served by `provider`.
632    ///
633    /// The model matches as in [`lookup`](Self::lookup): exactly, or as a dated alias.
634    /// `None` for `provider` matches any vendor.
635    pub fn unit_price(
636        &self,
637        provider: Option<&str>,
638        model: &str,
639        unit: UsageUnit,
640    ) -> Option<&UnitPrice> {
641        let canonical = canonical_model_id(model);
642        let candidates = self.units.iter().filter(|price| price.rate.unit == unit);
643        let candidate =
644            candidates.clone().find(|price| price.model == canonical).or_else(|| {
645                candidates
646                    .filter(|price| {
647                        canonical.strip_prefix(price.model.as_str()).is_some_and(is_version_suffix)
648                    })
649                    .max_by_key(|price| price.model.len())
650            })?;
651        match provider {
652            Some(provider) if !candidate.vendor.billed_by(provider) => None,
653            _ => Some(candidate),
654        }
655    }
656
657    /// Cost in micro-USD of `usage` on `model` as served by `provider`, or `None` when a
658    /// unit it counts has no price.
659    ///
660    /// Pass the most a call can use to get the bound its spend hold reserves, and what it
661    /// used to get what it commits.
662    ///
663    /// # Example
664    ///
665    /// ```
666    /// use adk_core::{UsageUnit, UsageVector};
667    /// use adk_model::pricing::PricingCatalog;
668    ///
669    /// let catalog = PricingCatalog::standard();
670    /// // 90.4 s of audio bills as 90 s at $0.18 per hour.
671    /// let audio = UsageVector::new().with(UsageUnit::AudioMillis, 90_400);
672    /// assert_eq!(
673    ///     catalog.unit_cost_micro_usd(Some("muse"), "muse-voice-transcribe-1.0", &audio),
674    ///     Some(4_500)
675    /// );
676    /// let pages = UsageVector::new().with(UsageUnit::Pages, 1);
677    /// assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "muse-voice-transcribe-1.0", &pages), None);
678    /// ```
679    pub fn unit_cost_micro_usd(
680        &self,
681        provider: Option<&str>,
682        model: &str,
683        usage: &UsageVector,
684    ) -> Option<u64> {
685        usage.iter().try_fold(0u64, |total, (unit, amount)| {
686            let price = self.unit_price(provider, model, unit)?;
687            Some(total.saturating_add(price.rate.cost_micro_usd(amount)))
688        })
689    }
690
691    /// Resolves the fee for `kind` on `model` as served by `provider`.
692    ///
693    /// Fees apply only on the vendor's own API ([`PriceVendor::first_party`]);
694    /// `None` for `provider` matches any vendor.
695    pub fn builtin_tool_fee(
696        &self,
697        provider: Option<&str>,
698        model: &str,
699        kind: &str,
700    ) -> Option<&BuiltinToolFee> {
701        let vendor = self.lookup(provider, model).map(|price| price.vendor);
702        self.fees.iter().find(|fee| {
703            fee.kind == kind
704                && vendor.is_none_or(|vendor| vendor == fee.vendor)
705                && provider.is_none_or(|provider| fee.vendor.first_party(provider))
706                && fee.applies_to(model)
707        })
708    }
709
710    /// Fees in USD for the built-in tool uses in `usage`. Unpriced kinds add nothing.
711    pub fn builtin_tool_cost_usd(
712        &self,
713        provider: Option<&str>,
714        model: &str,
715        usage: &UsageMetadata,
716    ) -> f64 {
717        usage
718            .builtin_tool_uses
719            .iter()
720            .filter_map(|used| match self.builtin_tool_fee(provider, model, &used.kind) {
721                Some(fee) => Some(fee.cost_usd(used.count)),
722                None => {
723                    tracing::debug!(
724                        builtin_tool.kind = %used.kind,
725                        gen_ai.request.model = %model,
726                        "no published fee for built-in tool; cost covers tokens only"
727                    );
728                    None
729                }
730            })
731            .sum()
732    }
733
734    /// The most tokens a request to `model` as served by `provider` may carry, as its vendor
735    /// publishes it, or `None` when the catalog has no figure for it.
736    ///
737    /// Model ids resolve as in [`lookup`](Self::lookup).
738    ///
739    /// # Example
740    ///
741    /// ```
742    /// use adk_model::pricing::PricingCatalog;
743    ///
744    /// let catalog = PricingCatalog::standard();
745    /// assert_eq!(catalog.context_window(Some("anthropic"), "claude-sonnet-5-5"), Some(1_000_000));
746    /// assert_eq!(catalog.context_window(Some("gemini"), "gemini-3.8-flash"), Some(1_048_576));
747    /// assert_eq!(catalog.context_window(Some("openai"), "my-fine-tune"), None);
748    /// ```
749    pub fn context_window(&self, provider: Option<&str>, model: &str) -> Option<u64> {
750        self.lookup(provider, model)?.context_window_tokens
751    }
752
753    /// Resolves the price for `model` as served by `provider`.
754    ///
755    /// `provider` is the [`LlmResponse::provider`](adk_core::LlmResponse::provider)
756    /// identifier. `None` matches any vendor, for callers that price a model
757    /// they know to be billed at list price.
758    pub fn lookup(&self, provider: Option<&str>, model: &str) -> Option<&ModelPrice> {
759        let canonical = canonical_model_id(model);
760        let candidate =
761            self.prices.iter().find(|price| price.model == canonical).or_else(|| {
762                self.prices
763                    .iter()
764                    .filter(|price| {
765                        canonical.strip_prefix(price.model.as_str()).is_some_and(is_version_suffix)
766                    })
767                    .max_by_key(|price| price.model.len())
768            })?;
769        match provider {
770            Some(provider) if !candidate.vendor.billed_by(provider) => None,
771            _ => Some(candidate),
772        }
773    }
774
775    /// Upper bound in micro-USD on what `request` can cost on `model` as served by
776    /// `provider`, or `None` when it cannot be bounded.
777    ///
778    /// `max_output_tokens` is the output cap the client sends with the request; `None`
779    /// uses the model's maximum output ([`ModelPrice::max_output_tokens`]). Built-in tool
780    /// fees are included: per-response fees once each, per-use fees up to each declared
781    /// built-in tool's `max_uses`. The bound is `None` for an unpriced model, a model with
782    /// neither output cap, a request whose input size is unknown
783    /// ([`request_input_token_bound`]), or a request declaring a fee-bearing built-in tool
784    /// without `max_uses`. Local Ollama models bound at zero.
785    ///
786    /// # Example
787    ///
788    /// ```
789    /// use adk_core::{Content, LlmRequest};
790    /// use adk_model::pricing::PricingCatalog;
791    ///
792    /// let request = LlmRequest::new("gpt-4.1", vec![Content::new("user").with_text("hi")]);
793    /// let catalog = PricingCatalog::standard();
794    /// let bound = catalog.max_cost_micro_usd(Some("openai"), "gpt-4.1", &request, Some(1_000));
795    /// // (2,048 + 16 + 2) input tokens × $2.00 + 1,000 output tokens × $8.00, rounded up.
796    /// assert_eq!(bound, Some(12_133));
797    /// assert_eq!(catalog.max_cost_micro_usd(Some("openai"), "my-fine-tune", &request, Some(1_000)), None);
798    /// ```
799    pub fn max_cost_micro_usd(
800        &self,
801        provider: Option<&str>,
802        model: &str,
803        request: &LlmRequest,
804        max_output_tokens: Option<u64>,
805    ) -> Option<u64> {
806        if provider == Some("ollama") {
807            return (!model.contains("cloud")).then_some(0);
808        }
809        let price = self.lookup(provider, model)?;
810        let output = max_output_tokens.or(price.max_output_tokens)?;
811        let prompt = request_input_token_bound(request)?;
812        let today = chrono::Utc::now().date_naive();
813        // A call that starts before a scheduled rate change can be priced after it.
814        let tomorrow = today.succ_opt().unwrap_or(today);
815        let usd = price
816            .max_cost_usd(prompt, output, today)
817            .max(price.max_cost_usd(prompt, output, tomorrow))
818            + self.builtin_tool_fee_bound_usd(provider, model, price.vendor, request)?;
819        // One extra micro-USD absorbs floating-point rounding in the commit.
820        adk_core::usd_to_micro_usd(usd).map(|micro| micro.saturating_add(1))
821    }
822
823    /// Upper bound in USD on the built-in tool fees one response to `request` can incur.
824    ///
825    /// Per-response fees count once each. Per-use fees are bounded only when every
826    /// built-in tool the request declares caps its uses (`max_uses`); otherwise the
827    /// fees, and so the request, cannot be bounded.
828    fn builtin_tool_fee_bound_usd(
829        &self,
830        provider: Option<&str>,
831        model: &str,
832        vendor: PriceVendor,
833        request: &LlmRequest,
834    ) -> Option<f64> {
835        let declared: Vec<&serde_json::Value> =
836            request.tools.values().filter_map(adk_core::builtin_tool_configuration).collect();
837        if declared.is_empty() {
838            return Some(0.0);
839        }
840        let applicable = self.fees.iter().filter(|fee| {
841            fee.usd > 0.0
842                && fee.vendor == vendor
843                && provider.is_none_or(|provider| fee.vendor.first_party(provider))
844                && fee.applies_to(model)
845        });
846        let mut per_response = 0.0;
847        let mut per_use: Option<f64> = None;
848        for fee in applicable {
849            match fee.unit {
850                FeeUnit::PerResponse => per_response += fee.usd,
851                FeeUnit::PerUse => per_use = Some(per_use.map_or(fee.usd, |max| max.max(fee.usd))),
852            }
853        }
854        let Some(per_use) = per_use else {
855            return Some(per_response);
856        };
857        let mut uses = 0u64;
858        for configuration in declared {
859            uses = uses.saturating_add(configuration.get("max_uses")?.as_u64()?);
860        }
861        Some(per_response + uses as f64 * per_use)
862    }
863
864    /// Cost in USD of one response's usage, or `None` when the model is unpriced.
865    ///
866    /// The cost is the token cost plus the fees for the response's
867    /// [`builtin_tool_uses`](UsageMetadata::builtin_tool_uses) that the catalog
868    /// prices. Local Ollama models cost zero.
869    pub fn cost_usd(
870        &self,
871        provider: Option<&str>,
872        model: &str,
873        usage: &UsageMetadata,
874    ) -> Option<f64> {
875        if provider == Some("ollama") {
876            return (!model.contains("cloud")).then_some(0.0);
877        }
878        let price = self.lookup(provider, model)?;
879        Some(
880            price.cost_usd_at(usage, chrono::Utc::now())
881                + self.builtin_tool_cost_usd(provider, model, usage),
882        )
883    }
884}
885
886/// Tokens counted for one inline image, audio or video part when its byte size is smaller.
887///
888/// Providers bill media by dimensions or duration rather than bytes, so a small but
889/// highly compressed file can cost more tokens than it has bytes.
890pub const MEDIA_PART_MIN_TOKENS: u64 = 16_384;
891
892/// Fixed input tokens added to every request bound for provider-side framing: role
893/// markers, tool-use system prompts and response-format instructions.
894pub const REQUEST_OVERHEAD_TOKENS: u64 = 2_048;
895
896/// Upper bound on the input tokens of `request`, or `None` when the request references
897/// content whose size is unknown (a `FileData` URI).
898///
899/// Every tokenizer `adk-model` providers use emits at most one token per UTF-8 byte, so
900/// the byte length of each text and JSON part bounds its tokens. Inline media counts its
901/// byte length, at least [`MEDIA_PART_MIN_TOKENS`]; [`REQUEST_OVERHEAD_TOKENS`] plus 16
902/// tokens per message and per tool cover the framing a provider adds.
903///
904/// # Example
905///
906/// ```
907/// use adk_core::{Content, LlmRequest};
908/// use adk_model::pricing::{REQUEST_OVERHEAD_TOKENS, request_input_token_bound};
909///
910/// let request = LlmRequest::new("gpt-5.4-mini", vec![Content::new("user").with_text("hello")]);
911/// assert_eq!(request_input_token_bound(&request), Some(REQUEST_OVERHEAD_TOKENS + 16 + 5));
912/// ```
913pub fn request_input_token_bound(request: &LlmRequest) -> Option<u64> {
914    let json_len = |value: &dyn erased::Json| value.byte_len();
915    let mut tokens = REQUEST_OVERHEAD_TOKENS;
916    for content in &request.contents {
917        tokens = tokens.saturating_add(16);
918        for part in &content.parts {
919            let part_tokens = match part {
920                Part::Text { text } => text.len() as u64,
921                Part::Thinking { thinking, signature } => {
922                    (thinking.len() + signature.as_ref().map_or(0, String::len)) as u64
923                }
924                Part::InlineData { data, .. } => (data.len() as u64).max(MEDIA_PART_MIN_TOKENS),
925                Part::FileData { .. } => return None,
926                _ => json_len(part),
927            };
928            tokens = tokens.saturating_add(part_tokens);
929        }
930    }
931    for declaration in request.tools.values() {
932        tokens = tokens.saturating_add(16).saturating_add(json_len(declaration));
933    }
934    if let Some(config) = &request.config {
935        if let Some(schema) = &config.response_schema {
936            tokens = tokens.saturating_add(json_len(schema));
937        }
938        tokens = tokens.saturating_add(config.stop_sequences.iter().map(|s| s.len() as u64).sum());
939    }
940    Some(tokens)
941}
942
943/// The output cap a request sets, if any.
944#[cfg(any(
945    feature = "anthropic",
946    feature = "azure-ai",
947    feature = "bedrock",
948    feature = "gemini",
949    feature = "ollama",
950    feature = "openai"
951))]
952pub(crate) fn request_output_cap(request: &LlmRequest) -> Option<u64> {
953    request
954        .config
955        .as_ref()
956        .and_then(|config| config.max_output_tokens)
957        .and_then(|tokens| u64::try_from(tokens).ok())
958}
959
960mod erased {
961    /// Serialized JSON length of a value, for token bounds.
962    pub trait Json {
963        fn byte_len(&self) -> u64;
964    }
965
966    impl<T: serde::Serialize> Json for T {
967        fn byte_len(&self) -> u64 {
968            serde_json::to_vec(self).map_or(u64::MAX / 4, |bytes| bytes.len() as u64)
969        }
970    }
971}
972
973fn non_negative(tokens: i32) -> u64 {
974    u64::try_from(tokens).unwrap_or(0)
975}
976
977/// Anthropic reports the 1-hour share of `cache_creation_input_tokens`
978/// separately; it is carried in the retained provider usage.
979fn one_hour_cache_writes(usage: &UsageMetadata) -> u64 {
980    let Some(provider_usage) = usage.provider_usage.as_ref() else {
981        return 0;
982    };
983    provider_usage
984        .get("cache_creation_input_tokens_1h")
985        .or_else(|| provider_usage.pointer("/cache_creation/ephemeral_1h_input_tokens"))
986        .and_then(serde_json::Value::as_u64)
987        .unwrap_or(0)
988}
989
990/// Strips transport prefixes and suffixes so a served identifier matches the catalog.
991fn canonical_model_id(model: &str) -> String {
992    let lowered = model.trim().to_ascii_lowercase();
993    let mut id = lowered.rsplit('/').next().unwrap_or(&lowered);
994    // Bedrock cross-region inference profiles and vendor prefixes.
995    for region in ["us.", "eu.", "apac.", "global.", "us-gov.", "jp.", "au.", "ca."] {
996        if let Some(rest) = id.strip_prefix(region) {
997            id = rest;
998            break;
999        }
1000    }
1001    if let Some(rest) = id.strip_prefix("anthropic.") {
1002        id = rest;
1003    }
1004    // Bedrock model versions: `-v1:0`, `-v2`.
1005    let id = match id.rfind("-v") {
1006        Some(index)
1007            if id[index + 2..]
1008                .split(':')
1009                .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())) =>
1010        {
1011            &id[..index]
1012        }
1013        _ => id,
1014    };
1015    // Vertex AI pins Claude versions with `@`; OpenRouter writes Claude versions with dots.
1016    let mut id = id.replace('@', "-");
1017    if id.starts_with("claude-") {
1018        id = id.replace('.', "-");
1019    }
1020    id
1021}
1022
1023/// A dated or revision suffix: `-20250929`, `-2025-04-14`, `-001` or `-latest`.
1024fn is_version_suffix(rest: &str) -> bool {
1025    let Some(rest) = rest.strip_prefix('-') else {
1026        return false;
1027    };
1028    if rest == "latest" {
1029        return true;
1030    }
1031    let digits =
1032        |part: &str, len: usize| part.len() == len && part.bytes().all(|b| b.is_ascii_digit());
1033    if rest.len() >= 3 && rest.bytes().all(|b| b.is_ascii_digit()) {
1034        return true;
1035    }
1036    let parts: Vec<&str> = rest.split('-').collect();
1037    matches!(parts.as_slice(), [year, month, day] if digits(year, 4) && digits(month, 2) && digits(day, 2))
1038}
1039
1040fn standard_catalog() -> PricingCatalog {
1041    use PriceVendor::{Anthropic, DeepSeek, Google, Groq, Meta, Mistral, OpenAI, XAi};
1042
1043    let gemini = |model: &str, input: f64, output: f64, cache_read: f64| {
1044        ModelPrice::new(Google, model, ModelRates::new(input, output).with_cache_read(cache_read))
1045    };
1046    let openai = |model: &str, input: f64, output: f64, cache_read: f64| {
1047        ModelPrice::new(OpenAI, model, ModelRates::new(input, output).with_cache_read(cache_read))
1048    };
1049    let claude = |model: &str, input: f64, output: f64, read: f64, write_5m: f64, write_1h: f64| {
1050        ModelPrice::new(
1051            Anthropic,
1052            model,
1053            ModelRates::new(input, output)
1054                .with_cache_read(read)
1055                .with_cache_writes(write_5m, write_1h),
1056        )
1057    };
1058    // Gemini's long-context rates apply to prompts over 200K tokens.
1059    const GEMINI_LONG: u64 = 200_001;
1060    // OpenAI's long-context rates apply above 272K input tokens.
1061    const OPENAI_LONG: u64 = 272_001;
1062    // xAI bills every token of a request at the long-context rate once the prompt
1063    // reaches 200K tokens.
1064    const XAI_LONG: u64 = 200_000;
1065    let cached = |vendor: PriceVendor, model: &str, input: f64, output: f64, cache_read: f64| {
1066        ModelPrice::new(vendor, model, ModelRates::new(input, output).with_cache_read(cache_read))
1067    };
1068    let deepseek_off_peak = OffPeak::weekdays(0.5, &[(1, 4), (6, 10)]);
1069    let grok = |model: &str, base: (f64, f64, f64), long: (f64, f64, f64)| {
1070        cached(XAi, model, base.0, base.2, base.1)
1071            .with_long_context(XAI_LONG, ModelRates::new(long.0, long.2).with_cache_read(long.1))
1072    };
1073    // (input, cached input, output) per million tokens.
1074    let grok_47 = ((2.00, 0.50, 6.00), (4.00, 1.00, 12.00));
1075    let grok_45 = ((2.00, 0.30, 6.00), (4.00, 0.60, 12.00));
1076    let grok_420 = ((1.25, 0.20, 2.50), (2.50, 0.40, 5.00));
1077    let grok_build = ((1.00, 0.20, 2.00), (2.00, 0.40, 4.00));
1078    // Gemini 3.8, 3.7 and 3.6 Flash introductory rates end on 2026-12-31.
1079    let flash_2027 = NaiveDate::from_ymd_opt(2027, 1, 1).unwrap_or(NaiveDate::MAX);
1080    let flash_2027_rates = ModelRates::new(1.50, 7.50).with_cache_read(0.15);
1081    // Gemini 4 Carbon and Argon introductory rates end on 2026-11-30.
1082    let gemini_4_december = NaiveDate::from_ymd_opt(2026, 12, 1).unwrap_or(NaiveDate::MAX);
1083    let gemini_4_rates = ModelRates::new(4.00, 20.00).with_cache_read(0.20);
1084
1085    let prices = vec![
1086        // ── Google Gemini ──
1087        // https://aistudio.google.com/docs/pricing, retrieved 2026-11-29. `gemini-3.7-flash`
1088        // is deprecated and not listed there; requests for it are routed to and reported as
1089        // `gemini-3.8-flash` (https://aistudio.google.com/docs/deprecations).
1090        gemini("gemini-4-hydrogen", 1.50, 7.50, 0.075),
1091        gemini("gemini-4-neon", 3.00, 15.00, 0.15),
1092        gemini("gemini-4-carbon", 2.00, 10.00, 0.10).with_change(gemini_4_december, gemini_4_rates),
1093        gemini("gemini-4-argon", 2.00, 10.00, 0.10).with_change(gemini_4_december, gemini_4_rates),
1094        gemini("gemini-3.8-flash", 0.75, 3.75, 0.075).with_change(flash_2027, flash_2027_rates),
1095        gemini("gemini-3.7-flash", 0.75, 3.75, 0.075).with_change(flash_2027, flash_2027_rates),
1096        gemini("gemini-3.6-flash", 0.75, 3.75, 0.075).with_change(flash_2027, flash_2027_rates),
1097        gemini("gemini-3.5-flash", 1.50, 9.00, 0.15),
1098        gemini("gemini-3.5-flash-lite", 0.30, 2.50, 0.03),
1099        gemini("gemini-3.1-pro-preview-customtools", 2.00, 12.00, 0.20)
1100            .with_long_context(GEMINI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
1101        gemini("gemini-3.1-pro-preview", 2.00, 12.00, 0.20)
1102            .with_long_context(GEMINI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
1103        gemini("gemini-3-pro-preview", 2.00, 12.00, 0.20)
1104            .with_long_context(GEMINI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
1105        gemini("gemini-3.1-flash-lite", 0.25, 1.50, 0.025),
1106        gemini("gemini-3-flash-preview", 0.50, 3.00, 0.05),
1107        gemini("gemini-2.5-pro", 1.25, 10.00, 0.125)
1108            .with_long_context(GEMINI_LONG, ModelRates::new(2.50, 15.00).with_cache_read(0.25)),
1109        gemini("gemini-2.5-flash", 0.30, 2.50, 0.03),
1110        gemini("gemini-2.5-flash-preview-09-2025", 0.30, 2.50, 0.03),
1111        gemini("gemini-2.5-flash-lite", 0.10, 0.40, 0.01),
1112        gemini("gemini-2.5-flash-lite-preview-09-2025", 0.10, 0.40, 0.01),
1113        // Image output is billed at this rate; text output costs less.
1114        gemini("gemini-2.5-flash-image", 0.30, 30.00, 0.30),
1115        gemini("gemini-2.5-flash-image-preview", 0.30, 30.00, 0.30),
1116        gemini("gemini-2.5-computer-use-preview-10-2025", 1.25, 10.00, 1.25)
1117            .with_long_context(GEMINI_LONG, ModelRates::new(2.50, 15.00)),
1118        gemini("gemini-2.5-flash-preview-tts", 0.50, 10.00, 0.50),
1119        gemini("gemini-2.5-pro-preview-tts", 1.00, 20.00, 1.00),
1120        gemini("gemini-embedding-2", 0.20, 0.0, 0.20),
1121        gemini("gemini-embedding-001", 0.15, 0.0, 0.15),
1122        // ── OpenAI ──
1123        // https://developers.openai.com/api/docs/pricing, retrieved 2026-11-17: "Short
1124        // context: ≤272K input tokens. Long context: >272K input tokens."
1125        openai("gpt-6-astra", 10.00, 50.00, 1.00)
1126            .with_long_context(OPENAI_LONG, ModelRates::new(20.00, 75.00).with_cache_read(2.00)),
1127        openai("gpt-6.1-sol", 2.00, 10.00, 0.10)
1128            .with_long_context(OPENAI_LONG, ModelRates::new(4.00, 15.00).with_cache_read(0.20)),
1129        openai("gpt-6.1-terra", 1.00, 5.00, 0.05)
1130            .with_long_context(OPENAI_LONG, ModelRates::new(2.00, 7.50).with_cache_read(0.10)),
1131        openai("gpt-6-sol", 2.00, 10.00, 0.20)
1132            .with_long_context(OPENAI_LONG, ModelRates::new(4.00, 15.00).with_cache_read(0.40)),
1133        openai("gpt-6-luna", 0.10, 0.50, 0.01)
1134            .with_long_context(OPENAI_LONG, ModelRates::new(0.20, 0.75).with_cache_read(0.02)),
1135        openai("gpt-6-cyber", 20.00, 100.00, 2.00)
1136            .with_long_context(OPENAI_LONG, ModelRates::new(40.00, 150.00).with_cache_read(4.00)),
1137        openai("gpt-5.6", 4.00, 20.00, 0.40)
1138            .with_long_context(OPENAI_LONG, ModelRates::new(8.00, 30.00).with_cache_read(0.80)),
1139        openai("gpt-5.6-sol", 4.00, 20.00, 0.40)
1140            .with_long_context(OPENAI_LONG, ModelRates::new(8.00, 30.00).with_cache_read(0.80)),
1141        openai("daybreak-blue-latest", 4.00, 20.00, 0.40),
1142        openai("gpt-5.6-terra", 2.00, 12.00, 0.20)
1143            .with_long_context(OPENAI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
1144        openai("gpt-5.6-luna", 0.20, 1.20, 0.02)
1145            .with_long_context(OPENAI_LONG, ModelRates::new(0.40, 1.80).with_cache_read(0.04)),
1146        openai("gpt-5.6-cyber", 12.50, 75.00, 1.25),
1147        openai("daybreak-red-latest", 12.50, 75.00, 1.25),
1148        openai("gpt-5.5", 5.00, 30.00, 0.50)
1149            .with_long_context(OPENAI_LONG, ModelRates::new(10.00, 45.00).with_cache_read(1.00)),
1150        openai("gpt-5.5-pro", 30.00, 180.00, 30.00)
1151            .with_long_context(OPENAI_LONG, ModelRates::new(60.00, 270.00)),
1152        openai("gpt-5.5-cyber", 12.50, 75.00, 1.25),
1153        openai("gpt-5.4", 2.50, 15.00, 0.25)
1154            .with_long_context(OPENAI_LONG, ModelRates::new(5.00, 22.50).with_cache_read(0.50)),
1155        openai("gpt-5.4-mini", 0.75, 4.50, 0.075),
1156        openai("gpt-5.4-nano", 0.20, 1.25, 0.02),
1157        openai("gpt-5.4-pro", 30.00, 180.00, 30.00)
1158            .with_long_context(OPENAI_LONG, ModelRates::new(60.00, 270.00)),
1159        openai("gpt-5.3-codex", 1.75, 14.00, 0.175),
1160        openai("gpt-5.2", 1.75, 14.00, 0.175),
1161        openai("gpt-5.2-pro", 21.00, 168.00, 21.00),
1162        openai("gpt-5.1", 1.25, 10.00, 0.125),
1163        openai("gpt-5", 1.25, 10.00, 0.125),
1164        openai("gpt-5-mini", 0.25, 2.00, 0.025),
1165        openai("gpt-5-nano", 0.05, 0.40, 0.005),
1166        openai("gpt-5-pro", 15.00, 120.00, 15.00),
1167        openai("gpt-5-search-api", 1.25, 10.00, 0.125),
1168        openai("chat-latest", 5.00, 30.00, 0.50),
1169        openai("gpt-4.1", 2.00, 8.00, 0.50),
1170        openai("gpt-4.1-mini", 0.40, 1.60, 0.10),
1171        openai("gpt-4.1-nano", 0.10, 0.40, 0.025),
1172        openai("o3", 2.00, 8.00, 0.50),
1173        openai("o4-mini", 1.10, 4.40, 0.275),
1174        openai("o3-mini", 1.10, 4.40, 0.55),
1175        openai("o1", 15.00, 60.00, 7.50),
1176        openai("gpt-4o", 2.50, 10.00, 1.25),
1177        openai("gpt-4o-mini", 0.15, 0.60, 0.075),
1178        // ── Anthropic ──
1179        // https://platform.claude.com/docs/en/about-claude/pricing, retrieved 2026-11-17.
1180        claude("claude-fable-5-2", 8.0, 40.0, 0.20, 10.0, 16.0),
1181        claude("claude-mythos-5-2", 8.0, 40.0, 0.20, 10.0, 16.0),
1182        claude("claude-fable-5-1", 10.0, 50.0, 0.25, 12.5, 20.0),
1183        claude("claude-mythos-5-1", 10.0, 50.0, 0.25, 12.5, 20.0),
1184        claude("claude-fable-5", 10.0, 50.0, 1.0, 12.5, 20.0),
1185        claude("claude-mythos-5", 10.0, 50.0, 1.0, 12.5, 20.0),
1186        claude("claude-opus-5-5", 4.0, 20.0, 0.20, 5.0, 8.0),
1187        claude("claude-opus-5", 5.0, 25.0, 0.50, 6.25, 10.0),
1188        claude("claude-sonnet-5-5", 2.0, 10.0, 0.10, 2.5, 4.0),
1189        claude("claude-sonnet-5", 2.0, 10.0, 0.20, 2.5, 4.0),
1190        // Haiku 5.5 bills the whole request at the long-prompt rate over 100K tokens.
1191        claude("claude-haiku-5-5", 0.10, 0.50, 0.01, 0.125, 0.20).with_long_context(
1192            100_001,
1193            ModelRates::new(0.50, 2.50).with_cache_read(0.05).with_cache_writes(0.625, 1.0),
1194        ),
1195        claude("claude-opus-4-8", 5.0, 25.0, 0.50, 6.25, 10.0),
1196        claude("claude-opus-4-7", 5.0, 25.0, 0.50, 6.25, 10.0),
1197        claude("claude-opus-4-6", 5.0, 25.0, 0.50, 6.25, 10.0),
1198        claude("claude-opus-4-5", 5.0, 25.0, 0.50, 6.25, 10.0),
1199        claude("claude-opus-4-1", 15.0, 75.0, 1.50, 18.75, 30.0),
1200        claude("claude-opus-4", 15.0, 75.0, 1.50, 18.75, 30.0),
1201        claude("claude-sonnet-4-6", 3.0, 15.0, 0.30, 3.75, 6.0),
1202        claude("claude-sonnet-4-5", 3.0, 15.0, 0.30, 3.75, 6.0),
1203        claude("claude-sonnet-4", 3.0, 15.0, 0.30, 3.75, 6.0),
1204        claude("claude-haiku-4-5", 1.0, 5.0, 0.10, 1.25, 2.0),
1205        claude("claude-haiku-3-5", 0.80, 4.0, 0.08, 1.0, 1.60),
1206        claude("claude-3-5-haiku", 0.80, 4.0, 0.08, 1.0, 1.60),
1207        // ── DeepSeek ──
1208        // Source: https://api-docs.deepseek.com/quick_start/pricing, retrieved 2026-10-11.
1209        // Peak rates (cache miss, cache hit, output); "Peak hours are 01:00 - 04:00 and
1210        // 06:00 - 10:00 UTC, Monday through Friday" and "Off-peak rates are half of the
1211        // peak rates". The legacy `deepseek-v4-flash` is "billed at the Flash price";
1212        // `deepseek-chat` and `deepseek-reasoner` are no longer listed and stay unpriced.
1213        cached(DeepSeek, "deepseek-flash", 0.30, 1.20, 0.006)
1214            .with_off_peak(deepseek_off_peak.clone()),
1215        cached(DeepSeek, "deepseek-v4-flash", 0.30, 1.20, 0.006)
1216            .with_off_peak(deepseek_off_peak.clone()),
1217        cached(DeepSeek, "deepseek-v4-pro", 1.32, 3.96, 0.044).with_off_peak(deepseek_off_peak),
1218        // ── Groq ──
1219        // Source: https://console.groq.com/docs/models and the per-model pages under
1220        // https://console.groq.com/docs/model/, retrieved 2026-11-17. Cached-input rates
1221        // are listed for the GPT-OSS models.
1222        cached(Groq, "gpt-oss-120b", 0.15, 0.60, 0.075),
1223        cached(Groq, "gpt-oss-20b", 0.075, 0.30, 0.037),
1224        cached(Groq, "gpt-oss-safeguard-20b", 0.075, 0.30, 0.037),
1225        ModelPrice::new(Groq, "qwen3.8-27b", ModelRates::new(0.80, 4.00)),
1226        // ── Meta Muse ──
1227        // Source: https://dev.meta.ai/docs/pricing-rate-limits, retrieved 2026-11-17.
1228        // Standard rates cover muse-spark-1.3/1.2/1.1; Contributor checkpoints are
1229        // discounted in exchange for training consent.
1230        cached(Meta, "muse-spark-1.3", 1.25, 4.25, 0.15),
1231        cached(Meta, "muse-spark-1.2", 1.25, 4.25, 0.15),
1232        cached(Meta, "muse-spark-1.1", 1.25, 4.25, 0.15),
1233        cached(Meta, "muse-spark-1.3-contributor", 0.10, 0.20, 0.002),
1234        cached(Meta, "muse-spark-1.2-contributor", 0.10, 0.20, 0.002),
1235        cached(Meta, "muse-wonder-1.0", 4.00, 20.00, 0.20),
1236        // Muse Ember bills the whole request at its long-context rate once the input,
1237        // cached tokens included, exceeds 200K tokens.
1238        cached(Meta, "muse-ember-1.0", 0.10, 0.50, 0.004)
1239            .with_long_context(200_001, ModelRates::new(0.30, 1.50).with_cache_read(0.012)),
1240        // muse-image-1.0, muse-voice-transcribe-1.0 and sam-3.1 bill per unit, not per
1241        // token; their rates are in `standard_unit_prices`.
1242        // ── xAI ──
1243        // Source: https://docs.x.ai/docs/models, retrieved 2026-11-17. Aliases are the ones
1244        // the page lists for each model; `-latest` and dated suffixes resolve automatically.
1245        grok("grok-4.7", grok_47.0, grok_47.1),
1246        grok("grok-4.6", grok_47.0, grok_47.1),
1247        grok("grok-4.5", grok_45.0, grok_45.1),
1248        grok("grok-build-latest", grok_45.0, grok_45.1),
1249        grok("grok-4.3", grok_420.0, grok_420.1),
1250        grok("grok-4.20", grok_420.0, grok_420.1),
1251        grok("grok-4.20-0309-reasoning", grok_420.0, grok_420.1),
1252        grok("grok-4.20-reasoning", grok_420.0, grok_420.1),
1253        grok("grok-4.20-0309-non-reasoning", grok_420.0, grok_420.1),
1254        grok("grok-4.20-non-reasoning", grok_420.0, grok_420.1),
1255        grok("grok-4.20-multi-agent-0309", grok_420.0, grok_420.1),
1256        grok("grok-4.20-multi-agent", grok_420.0, grok_420.1),
1257        grok("grok-build-0.1", grok_build.0, grok_build.1),
1258        grok("grok-code-fast-1", grok_build.0, grok_build.1),
1259        grok("grok-code-fast", grok_build.0, grok_build.1),
1260        // ── Mistral ──
1261        // Source: https://docs.mistral.ai/inference/pricing, with API ids from the model
1262        // pages under https://docs.mistral.ai/models/, retrieved 2026-11-17. Only the
1263        // `-latest` aliases the pages list are priced, so a retired dated id never
1264        // resolves to a current model's rate. `mistral-large-latest` names Mistral Large 4;
1265        // Medium 3.5 and Large 3 are deprecated and keep the rates they were listed at.
1266        cached(Mistral, "mistral-large-4", 0.7, 2.1, 0.07),
1267        cached(Mistral, "mistral-large-4-0", 0.7, 2.1, 0.07),
1268        cached(Mistral, "mistral-large-latest", 0.7, 2.1, 0.07),
1269        cached(Mistral, "mistral-medium-3-5", 1.5, 7.5, 0.15),
1270        cached(Mistral, "mistral-medium-3", 1.5, 7.5, 0.15),
1271        cached(Mistral, "mistral-medium-latest", 1.5, 7.5, 0.15),
1272        cached(Mistral, "mistral-large-2512", 0.5, 1.5, 0.05),
1273        cached(Mistral, "mistral-small-2603", 0.15, 0.6, 0.015),
1274        cached(Mistral, "mistral-small-latest", 0.15, 0.6, 0.015),
1275        cached(Mistral, "ministral-14b-2512", 0.2, 0.2, 0.02),
1276        cached(Mistral, "ministral-14b-latest", 0.2, 0.2, 0.02),
1277        cached(Mistral, "ministral-8b-2512", 0.15, 0.15, 0.015),
1278        cached(Mistral, "ministral-8b-latest", 0.15, 0.15, 0.015),
1279        cached(Mistral, "ministral-3b-2512", 0.1, 0.1, 0.01),
1280        cached(Mistral, "ministral-3b-latest", 0.1, 0.1, 0.01),
1281        cached(Mistral, "codestral-2508", 0.3, 0.9, 0.03),
1282        cached(Mistral, "codestral-latest", 0.3, 0.9, 0.03),
1283    ];
1284
1285    // Maximum output tokens per request, reasoning included, used to bound requests that
1286    // set no output cap. Sources, retrieved 2026-11-17:
1287    // - Anthropic: https://platform.claude.com/docs/en/about-claude/models/overview
1288    //   ("Max output", synchronous Messages API).
1289    // - Gemini: https://aistudio.google.com/docs/models/<id> ("Output token limit");
1290    //   https://aistudio.google.com/docs/thinking counts thought tokens in the limit.
1291    // - OpenAI: https://developers.openai.com/api/docs/models/<id> ("max output tokens");
1292    //   https://developers.openai.com/api/docs/guides/reasoning counts reasoning tokens.
1293    // - DeepSeek: https://api-docs.deepseek.com/quick_start/pricing ("MAXIMUM: 384K").
1294    // - Groq: https://console.groq.com/docs/models ("Max Completion Tokens").
1295    // - Mistral: https://docs.mistral.ai/models/<slug> states only a context window, which
1296    //   Mistral defines as input plus output tokens, so the window bounds the output.
1297    // - Meta: https://dev.meta.ai/docs/muse-ember ("Max output").
1298    // xAI publishes no output limit, so Grok requests bound only with an explicit cap.
1299    const GEMINI_MAX_OUTPUT: u64 = 65_536;
1300    const CLAUDE_MAX_OUTPUT: u64 = 128_000;
1301    let max_output: &[(&str, u64)] = &[
1302        ("claude-fable-5-2", CLAUDE_MAX_OUTPUT),
1303        ("claude-mythos-5-2", CLAUDE_MAX_OUTPUT),
1304        ("claude-fable-5-1", CLAUDE_MAX_OUTPUT),
1305        ("claude-mythos-5-1", CLAUDE_MAX_OUTPUT),
1306        ("claude-fable-5", CLAUDE_MAX_OUTPUT),
1307        ("claude-mythos-5", CLAUDE_MAX_OUTPUT),
1308        ("claude-opus-5-5", CLAUDE_MAX_OUTPUT),
1309        ("claude-opus-5", CLAUDE_MAX_OUTPUT),
1310        ("claude-sonnet-5-5", CLAUDE_MAX_OUTPUT),
1311        ("claude-sonnet-5", CLAUDE_MAX_OUTPUT),
1312        ("claude-haiku-5-5", CLAUDE_MAX_OUTPUT),
1313        ("claude-opus-4-8", CLAUDE_MAX_OUTPUT),
1314        ("claude-opus-4-7", CLAUDE_MAX_OUTPUT),
1315        ("claude-opus-4-6", CLAUDE_MAX_OUTPUT),
1316        ("claude-opus-4-5", 64_000),
1317        ("claude-opus-4-1", 32_000),
1318        ("claude-opus-4", 32_000),
1319        ("claude-sonnet-4-6", CLAUDE_MAX_OUTPUT),
1320        ("claude-sonnet-4-5", 64_000),
1321        ("claude-sonnet-4", 64_000),
1322        ("claude-haiku-4-5", 64_000),
1323        ("gemini-4-hydrogen", GEMINI_MAX_OUTPUT),
1324        ("gemini-4-neon", GEMINI_MAX_OUTPUT),
1325        ("gemini-4-carbon", GEMINI_MAX_OUTPUT),
1326        ("gemini-4-argon", GEMINI_MAX_OUTPUT),
1327        ("gemini-3.8-flash", GEMINI_MAX_OUTPUT),
1328        ("gemini-3.7-flash", GEMINI_MAX_OUTPUT),
1329        ("gemini-3.6-flash", GEMINI_MAX_OUTPUT),
1330        ("gemini-3.5-flash", GEMINI_MAX_OUTPUT),
1331        ("gemini-3.5-flash-lite", GEMINI_MAX_OUTPUT),
1332        ("gemini-3.1-pro-preview", GEMINI_MAX_OUTPUT),
1333        ("gemini-3.1-flash-lite", GEMINI_MAX_OUTPUT),
1334        ("gemini-3-flash-preview", GEMINI_MAX_OUTPUT),
1335        ("gemini-2.5-pro", GEMINI_MAX_OUTPUT),
1336        ("gemini-2.5-flash", GEMINI_MAX_OUTPUT),
1337        ("gemini-2.5-flash-lite", GEMINI_MAX_OUTPUT),
1338        ("gpt-6-astra", 128_000),
1339        ("gpt-6.1-sol", 128_000),
1340        ("gpt-6.1-terra", 128_000),
1341        ("gpt-6-sol", 128_000),
1342        ("gpt-6-luna", 128_000),
1343        ("gpt-6-cyber", 128_000),
1344        ("gpt-5.6", 128_000),
1345        ("gpt-5.6-sol", 128_000),
1346        ("gpt-5.6-terra", 128_000),
1347        ("gpt-5.6-luna", 128_000),
1348        ("gpt-5.6-cyber", 128_000),
1349        ("gpt-5.5", 128_000),
1350        ("gpt-5.5-pro", 128_000),
1351        ("gpt-5.4", 128_000),
1352        ("gpt-5.4-pro", 128_000),
1353        ("gpt-5.4-mini", 128_000),
1354        ("gpt-5.4-nano", 128_000),
1355        ("gpt-5.3-codex", 128_000),
1356        ("gpt-5.2", 128_000),
1357        ("gpt-5.2-pro", 128_000),
1358        ("gpt-5.1", 128_000),
1359        ("gpt-5", 128_000),
1360        ("gpt-5-mini", 128_000),
1361        ("gpt-5-nano", 128_000),
1362        ("gpt-5-pro", 272_000),
1363        ("gpt-4.1", 32_768),
1364        ("gpt-4.1-mini", 32_768),
1365        ("gpt-4.1-nano", 32_768),
1366        ("o3", 100_000),
1367        ("o4-mini", 100_000),
1368        ("o3-mini", 100_000),
1369        ("o1", 100_000),
1370        ("gpt-4o", 16_384),
1371        ("gpt-4o-mini", 16_384),
1372        ("deepseek-flash", 393_216),
1373        ("deepseek-v4-flash", 393_216),
1374        ("deepseek-v4-pro", 393_216),
1375        ("gpt-oss-120b", 65_536),
1376        ("gpt-oss-20b", 65_536),
1377        ("gpt-oss-safeguard-20b", 65_536),
1378        ("qwen3.8-27b", 16_384),
1379        ("chat-latest", 128_000),
1380        ("muse-ember-1.0", 524_288),
1381        ("mistral-large-4", 1_000_000),
1382        ("mistral-large-4-0", 1_000_000),
1383        ("mistral-medium-3-5", 262_144),
1384        ("mistral-medium-3", 262_144),
1385        ("mistral-medium-latest", 262_144),
1386        ("mistral-large-2512", 262_144),
1387        ("mistral-large-latest", 1_000_000),
1388        ("mistral-small-2603", 262_144),
1389        ("mistral-small-latest", 262_144),
1390        ("ministral-14b-2512", 262_144),
1391        ("ministral-14b-latest", 262_144),
1392        ("ministral-8b-2512", 262_144),
1393        ("ministral-8b-latest", 262_144),
1394        ("ministral-3b-2512", 262_144),
1395        ("ministral-3b-latest", 262_144),
1396        ("codestral-2508", 131_072),
1397        ("codestral-latest", 131_072),
1398    ];
1399    // The most tokens a request may carry: the page's stated maximum input where it gives
1400    // one, else its context window. Sources, retrieved 2026-11-17:
1401    // - Anthropic: https://platform.claude.com/docs/en/about-claude/models/overview
1402    //   ("Context").
1403    // - Gemini: https://aistudio.google.com/docs/models/<id> ("Input token limit", separate
1404    //   from the 65,536-token output limit; Gemini 4 shares one 1,048,576-token window).
1405    // - OpenAI: https://developers.openai.com/api/docs/models/<id> ("Maximum input tokens"
1406    //   where listed, else "context window").
1407    // - DeepSeek: https://api-docs.deepseek.com/quick_start/pricing ("CONTEXT LENGTH 1M");
1408    //   the page states `deepseek-v4-flash` is served by deepseek-flash.
1409    // - Groq: https://console.groq.com/docs/models ("CONTEXT WINDOW (TOKENS)").
1410    // - xAI: https://docs.x.ai/docs/models ("Context").
1411    // - Mistral: https://docs.mistral.ai/models/<slug> ("Context").
1412    // - Meta: https://dev.meta.ai/docs/muse-spark, /muse-wonder and /muse-ember ("Context").
1413    const CLAUDE_WINDOW: u64 = 1_000_000;
1414    const GEMINI_INPUT: u64 = 1_048_576;
1415    let context_window: &[(&str, u64)] = &[
1416        ("claude-fable-5-2", CLAUDE_WINDOW),
1417        ("claude-mythos-5-2", CLAUDE_WINDOW),
1418        ("claude-fable-5-1", CLAUDE_WINDOW),
1419        ("claude-mythos-5-1", CLAUDE_WINDOW),
1420        ("claude-fable-5", CLAUDE_WINDOW),
1421        ("claude-mythos-5", CLAUDE_WINDOW),
1422        ("claude-opus-5-5", CLAUDE_WINDOW),
1423        ("claude-opus-5", CLAUDE_WINDOW),
1424        ("claude-sonnet-5-5", CLAUDE_WINDOW),
1425        ("claude-sonnet-5", CLAUDE_WINDOW),
1426        ("claude-haiku-5-5", CLAUDE_WINDOW),
1427        ("claude-opus-4-8", CLAUDE_WINDOW),
1428        ("claude-opus-4-7", CLAUDE_WINDOW),
1429        ("claude-opus-4-6", CLAUDE_WINDOW),
1430        ("claude-sonnet-4-6", CLAUDE_WINDOW),
1431        ("claude-opus-4-5", 200_000),
1432        ("claude-opus-4-1", 200_000),
1433        ("claude-opus-4", 200_000),
1434        ("claude-sonnet-4-5", 200_000),
1435        ("claude-sonnet-4", 200_000),
1436        ("claude-haiku-4-5", 200_000),
1437        ("gemini-4-hydrogen", GEMINI_INPUT),
1438        ("gemini-4-neon", GEMINI_INPUT),
1439        ("gemini-4-carbon", GEMINI_INPUT),
1440        ("gemini-4-argon", GEMINI_INPUT),
1441        ("gemini-3.8-flash", GEMINI_INPUT),
1442        ("gemini-3.7-flash", GEMINI_INPUT),
1443        ("gemini-3.6-flash", GEMINI_INPUT),
1444        ("gemini-3.5-flash", GEMINI_INPUT),
1445        ("gemini-3.5-flash-lite", GEMINI_INPUT),
1446        ("gemini-3.1-pro-preview", GEMINI_INPUT),
1447        ("gemini-3.1-flash-lite", GEMINI_INPUT),
1448        ("gemini-3-flash-preview", GEMINI_INPUT),
1449        ("gemini-2.5-pro", GEMINI_INPUT),
1450        ("gemini-2.5-flash", GEMINI_INPUT),
1451        ("gemini-2.5-flash-lite", GEMINI_INPUT),
1452        ("gpt-6-astra", 922_000),
1453        ("gpt-6.1-sol", 922_000),
1454        ("gpt-6.1-terra", 922_000),
1455        ("gpt-6-sol", 922_000),
1456        ("gpt-6-luna", 922_000),
1457        ("gpt-6-cyber", 922_000),
1458        ("gpt-5.6", 922_000),
1459        ("gpt-5.6-sol", 922_000),
1460        ("gpt-5.6-terra", 922_000),
1461        ("gpt-5.6-luna", 922_000),
1462        ("gpt-5.6-cyber", 272_000),
1463        ("gpt-5.5", 1_050_000),
1464        ("gpt-5.5-pro", 1_050_000),
1465        ("gpt-5.4", 1_050_000),
1466        ("gpt-5.4-pro", 1_050_000),
1467        ("gpt-5.3-codex", 272_000),
1468        ("gpt-5.2-pro", 400_000),
1469        ("gpt-5-pro", 400_000),
1470        ("chat-latest", 272_000),
1471        ("gpt-5.4-mini", 272_000),
1472        ("gpt-5.4-nano", 272_000),
1473        ("gpt-5.2", 400_000),
1474        ("gpt-5.1", 400_000),
1475        ("gpt-5", 272_000),
1476        ("gpt-5-mini", 272_000),
1477        ("gpt-5-nano", 272_000),
1478        ("gpt-4.1", 1_047_576),
1479        ("gpt-4.1-mini", 1_047_576),
1480        ("gpt-4o", 128_000),
1481        ("gpt-4o-mini", 128_000),
1482        ("o3", 200_000),
1483        ("o4-mini", 200_000),
1484        ("deepseek-flash", 1_000_000),
1485        ("deepseek-v4-flash", 1_000_000),
1486        ("deepseek-v4-pro", 1_000_000),
1487        ("gpt-oss-120b", 131_072),
1488        ("gpt-oss-20b", 131_072),
1489        ("gpt-oss-safeguard-20b", 131_072),
1490        ("qwen3.8-27b", 131_072),
1491        ("grok-4.7", 500_000),
1492        ("grok-4.6", 500_000),
1493        ("grok-4.5", 500_000),
1494        ("grok-build-latest", 500_000),
1495        ("grok-build-0.1", 256_000),
1496        ("grok-code-fast-1", 256_000),
1497        ("grok-code-fast", 256_000),
1498        ("grok-4.3", 1_000_000),
1499        ("grok-4.20", 1_000_000),
1500        ("grok-4.20-0309-reasoning", 1_000_000),
1501        ("grok-4.20-reasoning", 1_000_000),
1502        ("grok-4.20-0309-non-reasoning", 1_000_000),
1503        ("grok-4.20-non-reasoning", 1_000_000),
1504        ("grok-4.20-multi-agent-0309", 1_000_000),
1505        ("grok-4.20-multi-agent", 1_000_000),
1506        ("mistral-large-4", 1_000_000),
1507        ("mistral-large-4-0", 1_000_000),
1508        ("mistral-large-latest", 1_000_000),
1509        ("mistral-medium-3-5", 256_000),
1510        ("mistral-large-2512", 256_000),
1511        ("mistral-small-2603", 256_000),
1512        ("ministral-14b-2512", 256_000),
1513        ("codestral-2508", 128_000),
1514        ("muse-spark-1.3", 1_048_576),
1515        ("muse-spark-1.2", 1_048_576),
1516        ("muse-spark-1.1", 1_048_576),
1517        ("muse-wonder-1.0", 1_048_576),
1518        ("muse-ember-1.0", 1_048_576),
1519    ];
1520    let prices = prices
1521        .into_iter()
1522        .map(|price| match max_output.iter().find(|(model, _)| *model == price.model) {
1523            Some((_, tokens)) => price.with_max_output_tokens(*tokens),
1524            None => price,
1525        })
1526        .map(|price| match context_window.iter().find(|(model, _)| *model == price.model) {
1527            Some((_, tokens)) => price.with_context_window(*tokens),
1528            None => price,
1529        })
1530        .collect();
1531    PricingCatalog {
1532        version: PRICING_EFFECTIVE_DATE.to_string(),
1533        prices,
1534        fees: standard_fees(),
1535        units: standard_unit_prices(),
1536    }
1537}
1538
1539/// Published per-unit prices, verified on 2026-10-31.
1540fn standard_unit_prices() -> Vec<UnitPrice> {
1541    use PriceVendor::Meta;
1542    vec![
1543        // https://dev.meta.ai/docs/pricing-rate-limits (fetched 2026-10-31): muse-image-1.0
1544        // "$0.01 per image", billed only for images generated and returned.
1545        UnitPrice::new(Meta, "muse-image-1.0", UnitRate::new(UsageUnit::Images, 10_000, 1)),
1546        // muse-voice-transcribe-1.0 "$0.18 per hour of audio processed", "metered in whole
1547        // seconds, rounded down"; streaming and file transcription are priced the same.
1548        UnitPrice::new(
1549            Meta,
1550            "muse-voice-transcribe-1.0",
1551            UnitRate::new(UsageUnit::AudioMillis, 180_000, 3_600_000).rounded_down_to(1_000),
1552        ),
1553        // sam-3.1 image segmentation "$2.50 per 1,000 images".
1554        UnitPrice::new(Meta, "sam-3.1", UnitRate::new(UsageUnit::Images, 2_500_000, 1_000)),
1555        // sam-3.1 video segmentation "$0.20 per 1,000 frames", "a minimum of 50 frames per
1556        // request" (https://dev.meta.ai/docs/sam/segmenting, fetched 2026-11-21).
1557        UnitPrice::new(
1558            Meta,
1559            "sam-3.1",
1560            UnitRate::new(UsageUnit::Frames, 200_000, 1_000).with_minimum_per_request(50),
1561        ),
1562    ]
1563}
1564
1565/// Published built-in tool fees, verified on 2026-10-11.
1566///
1567/// Free monthly or daily allowances are not tracked, so a run inside an allowance
1568/// is over-estimated. Kinds without a per-use fee here (Anthropic and OpenAI code
1569/// execution, billed per container; OpenAI image generation and MCP; Gemini 3 Maps,
1570/// billed per Maps query, which responses do not report) add no fee.
1571fn standard_fees() -> Vec<BuiltinToolFee> {
1572    use PriceVendor::{Anthropic, Google, OpenAI};
1573    vec![
1574        // https://platform.claude.com/docs/en/about-claude/pricing (fetched 2026-10-11):
1575        // web search "$10 per 1,000 searches"; web fetch "no additional cost".
1576        BuiltinToolFee::per_use(Anthropic, "web_search", 0.010),
1577        BuiltinToolFee::per_use(Anthropic, "web_fetch", 0.0),
1578        // https://developers.openai.com/api/docs/pricing (fetched 2026-10-11):
1579        // web search "$10.00 / 1k calls"; file search tool call "$2.50 / 1k calls".
1580        // `web_search_preview` on non-reasoning models costs $25.00 / 1k calls and is
1581        // under-estimated, because the response does not name the tool version.
1582        BuiltinToolFee::per_use(OpenAI, "web_search", 0.010),
1583        BuiltinToolFee::per_use(OpenAI, "file_search", 0.0025),
1584        // https://aistudio.google.com/docs/pricing (fetched 2026-11-17): Gemini 3 and newer,
1585        // Google Search "$14 per 1,000 requests" (search queries).
1586        BuiltinToolFee::per_use(Google, "google_search", 0.014)
1587            .for_models(["gemini-3*", "gemini-4*"]),
1588        // Gemini 2.5 Pro and Flash, Google Search "$35 / 1,000 grounded prompts" and
1589        // Google Maps "$25 / 1,000 grounded prompts".
1590        BuiltinToolFee::per_response(Google, "google_search", 0.035)
1591            .for_models(["gemini-2.5-pro", "gemini-2.5-flash"]),
1592        BuiltinToolFee::per_response(Google, "google_maps", 0.025)
1593            .for_models(["gemini-2.5-pro", "gemini-2.5-flash"]),
1594        // "Code execution is billed at the standard token rates for the selected model."
1595        BuiltinToolFee::per_use(Google, "code_execution", 0.0),
1596    ]
1597}
1598
1599#[cfg(test)]
1600mod tests {
1601    use super::*;
1602
1603    #[test]
1604    fn muse_media_is_priced_per_unit() {
1605        let catalog = PricingCatalog::standard();
1606        let images = |count| UsageVector::new().with(UsageUnit::Images, count);
1607        assert_eq!(
1608            catalog.unit_cost_micro_usd(Some("muse"), "muse-image-1.0", &images(1)),
1609            Some(10_000)
1610        );
1611        assert_eq!(
1612            catalog.unit_cost_micro_usd(Some("muse"), "sam-3.1", &images(1_000)),
1613            Some(2_500_000)
1614        );
1615        assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "sam-3.1", &images(1)), Some(2_500));
1616        let frames = |count| UsageVector::new().with(UsageUnit::Frames, count);
1617        let video = |count| catalog.unit_cost_micro_usd(Some("muse"), "sam-3.1", &frames(count));
1618        // Thirty seconds at 30 fps; a 12-frame clip bills the 50-frame minimum.
1619        assert_eq!(video(900), Some(180_000));
1620        assert_eq!(video(12), Some(10_000));
1621        assert_eq!(video(50), Some(10_000));
1622        assert_eq!(video(3_600), Some(720_000));
1623        let audio = |ms| UsageVector::new().with(UsageUnit::AudioMillis, ms);
1624        let transcribe =
1625            |ms| catalog.unit_cost_micro_usd(Some("muse"), "muse-voice-transcribe-1.0", &audio(ms));
1626        assert_eq!(transcribe(90_000), Some(4_500));
1627        assert_eq!(transcribe(3_600_000), Some(180_000));
1628        assert_eq!(transcribe(999), Some(0));
1629    }
1630
1631    #[test]
1632    fn a_unit_price_applies_only_where_the_vendor_bills_it() {
1633        let catalog = PricingCatalog::standard();
1634        let images = UsageVector::new().with(UsageUnit::Images, 1);
1635        assert_eq!(catalog.unit_cost_micro_usd(Some("openai"), "muse-image-1.0", &images), None);
1636        assert_eq!(catalog.unit_cost_micro_usd(None, "muse-image-1.0", &images), Some(10_000));
1637        assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "muse-image-2.0", &images), None);
1638        // A token price is not a unit price.
1639        assert!(catalog.lookup(Some("muse"), "muse-image-1.0").is_none());
1640        assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "muse-spark-1.3", &images), None);
1641    }
1642
1643    #[test]
1644    fn a_unit_price_replaces_the_same_model_and_unit() {
1645        let catalog = PricingCatalog::new("t")
1646            .with_unit_price(UnitPrice::new(
1647                PriceVendor::Meta,
1648                "m",
1649                UnitRate::new(UsageUnit::Images, 1, 1),
1650            ))
1651            .with_unit_price(UnitPrice::new(
1652                PriceVendor::Meta,
1653                "m",
1654                UnitRate::new(UsageUnit::Pages, 5, 1),
1655            ))
1656            .with_unit_price(UnitPrice::new(
1657                PriceVendor::Meta,
1658                "m",
1659                UnitRate::new(UsageUnit::Images, 2, 1),
1660            ));
1661        assert_eq!(catalog.unit_prices().len(), 2);
1662        let both = UsageVector::new().with(UsageUnit::Images, 3).with(UsageUnit::Pages, 1);
1663        assert_eq!(catalog.unit_cost_micro_usd(None, "m", &both), Some(11));
1664        assert_eq!(catalog.unit_cost_micro_usd(None, "m", &UsageVector::new()), Some(0));
1665    }
1666
1667    fn today() -> NaiveDate {
1668        NaiveDate::from_ymd_opt(2026, 10, 10).unwrap()
1669    }
1670
1671    fn usage(prompt: i32, output: i32) -> UsageMetadata {
1672        UsageMetadata {
1673            prompt_token_count: prompt,
1674            candidates_token_count: output,
1675            total_token_count: prompt + output,
1676            ..Default::default()
1677        }
1678    }
1679
1680    fn tool_usage(uses: &[(&str, u32)]) -> UsageMetadata {
1681        UsageMetadata {
1682            builtin_tool_uses: uses
1683                .iter()
1684                .map(|(kind, count)| adk_core::BuiltinToolUse::new(*kind, *count))
1685                .collect(),
1686            ..Default::default()
1687        }
1688    }
1689
1690    #[test]
1691    fn builtin_tool_fees_are_added_on_the_vendor_api_only() {
1692        let catalog = PricingCatalog::standard();
1693        let searched = tool_usage(&[("web_search", 3), ("web_fetch", 2), ("code_execution", 1)]);
1694        let cost = |provider: &str, model: &str, usage: &UsageMetadata| {
1695            catalog.cost_usd(Some(provider), model, usage).unwrap()
1696        };
1697        assert!((cost("anthropic", "claude-sonnet-4-6", &searched) - 0.03).abs() < 1e-12);
1698        assert_eq!(cost("bedrock", "claude-sonnet-4-6", &searched), 0.0);
1699        assert!(
1700            (cost("openai", "gpt-5.6-luna", &tool_usage(&[("web_search", 2), ("file_search", 4)]))
1701                - 0.03)
1702                .abs()
1703                < 1e-12
1704        );
1705
1706        let gemini3 =
1707            tool_usage(&[("google_search", 4), ("code_execution", 2), ("google_maps", 1)]);
1708        assert!((cost("gemini", "gemini-3.7-flash", &gemini3) - 0.056).abs() < 1e-12);
1709        let gemini25 = tool_usage(&[("google_search", 4), ("google_maps", 1)]);
1710        assert!((cost("gemini", "gemini-2.5-flash", &gemini25) - 0.06).abs() < 1e-12);
1711        assert!(
1712            catalog
1713                .builtin_tool_fee(Some("gemini"), "gemini-2.5-flash-lite", "google_search")
1714                .is_none()
1715        );
1716        assert!(
1717            catalog
1718                .builtin_tool_fee(Some("anthropic"), "claude-haiku-4-5", "code_execution")
1719                .is_none()
1720        );
1721    }
1722
1723    fn price(provider: &str, model: &str) -> &'static ModelPrice {
1724        PricingCatalog::standard()
1725            .lookup(Some(provider), model)
1726            .unwrap_or_else(|| panic!("{provider}/{model} should be priced"))
1727    }
1728
1729    #[test]
1730    fn context_windows_resolve_by_provider_and_dated_alias() {
1731        let catalog = PricingCatalog::standard();
1732        let window = |provider: &str, model: &str| catalog.context_window(Some(provider), model);
1733        assert_eq!(window("anthropic", "claude-sonnet-5-5"), Some(1_000_000));
1734        assert_eq!(window("bedrock", "us.anthropic.claude-haiku-4-5-20251001-v1:0"), Some(200_000));
1735        assert_eq!(window("gemini", "models/gemini-3.5-flash-lite"), Some(1_048_576));
1736        assert_eq!(window("openai", "gpt-5.6-terra"), Some(922_000));
1737        assert_eq!(window("groq", "openai/gpt-oss-120b"), Some(131_072));
1738        // A vendor's window applies only where the provider serves that vendor's models.
1739        assert_eq!(window("groq", "claude-sonnet-5-5"), None);
1740        assert_eq!(window("anthropic", "claude-fable-5-2"), Some(1_000_000));
1741        assert_eq!(window("anthropic", "claude-opus-4-5-20251101"), Some(200_000));
1742        assert_eq!(window("xai", "grok-code-fast-1"), Some(256_000));
1743        // Priced, but no published window was recorded.
1744        assert_eq!(window("gemini", "gemini-2.5-flash-image"), None);
1745        // Every model with a recorded window is priced, so none is silently dropped.
1746        let recorded =
1747            catalog.prices().iter().filter(|p| p.context_window_tokens.is_some()).count();
1748        assert_eq!(recorded, 103);
1749    }
1750
1751    #[test]
1752    fn gemini_cached_tokens_are_billed_once() {
1753        // promptTokenCount includes cachedContentTokenCount.
1754        let usage = UsageMetadata {
1755            cache_read_input_token_count: Some(400_000),
1756            ..usage(1_000_000, 200_000)
1757        };
1758        let cost = price("gemini", "gemini-2.5-flash").cost_usd(&usage, today());
1759        // 600K × $0.30 + 400K × $0.03 + 200K × $2.50
1760        assert!((cost - (0.18 + 0.012 + 0.50)).abs() < 1e-9, "{cost}");
1761    }
1762
1763    #[test]
1764    fn gemini_long_context_switches_the_whole_request() {
1765        let price = price("gemini", "models/gemini-2.5-pro");
1766        let short = price.cost_usd(&usage(200_000, 0), today());
1767        let long = price.cost_usd(&usage(200_001, 0), today());
1768        assert!((short - 0.25).abs() < 1e-9, "{short}");
1769        assert!((long - 200_001.0 * 2.50 / 1e6).abs() < 1e-9, "{long}");
1770    }
1771
1772    #[test]
1773    fn gemini_flash_introductory_rates_end_in_2027() {
1774        let price = price("gemini", "gemini-3.7-flash");
1775        let before = price.cost_usd(&usage(1_000_000, 0), today());
1776        let after =
1777            price.cost_usd(&usage(1_000_000, 0), NaiveDate::from_ymd_opt(2027, 1, 1).unwrap());
1778        assert!((before - 0.75).abs() < 1e-9);
1779        assert!((after - 1.50).abs() < 1e-9);
1780    }
1781
1782    #[test]
1783    fn anthropic_cache_writes_split_by_ttl() {
1784        // Normalized prompt = input + cache reads + cache writes.
1785        let usage = UsageMetadata {
1786            prompt_token_count: 1_000 + 200_000 + 100_000,
1787            candidates_token_count: 2_000,
1788            cache_read_input_token_count: Some(200_000),
1789            cache_creation_input_token_count: Some(100_000),
1790            provider_usage: Some(serde_json::json!({ "cache_creation_input_tokens_1h": 40_000 })),
1791            ..Default::default()
1792        };
1793        let cost = price("anthropic", "claude-sonnet-4-5-20250929").cost_usd(&usage, today());
1794        let expected =
1795            (1_000.0 * 3.0 + 200_000.0 * 0.30 + 60_000.0 * 3.75 + 40_000.0 * 6.0 + 2_000.0 * 15.0)
1796                / 1e6;
1797        assert!((cost - expected).abs() < 1e-9, "{cost} vs {expected}");
1798    }
1799
1800    #[test]
1801    fn haiku_55_long_prompt_counts_cached_tokens() {
1802        let usage =
1803            UsageMetadata { cache_read_input_token_count: Some(90_000), ..usage(100_001, 0) };
1804        let cost = price("anthropic", "claude-haiku-5-5").cost_usd(&usage, today());
1805        let expected = (10_001.0 * 0.50 + 90_000.0 * 0.05) / 1e6;
1806        assert!((cost - expected).abs() < 1e-12, "{cost}");
1807    }
1808
1809    #[test]
1810    fn openai_long_context_starts_above_272k() {
1811        let gpt_55 = price("openai", "gpt-5.5");
1812        assert_eq!(gpt_55.rates_for(272_000, today()).input, 5.00);
1813        assert_eq!(gpt_55.rates_for(272_001, today()).input, 10.00);
1814        let sol = price("openai", "gpt-6.1-sol");
1815        assert_eq!(
1816            sol.rates_for(272_000, today()),
1817            ModelRates::new(2.00, 10.00).with_cache_read(0.10)
1818        );
1819        assert_eq!(
1820            sol.rates_for(272_001, today()),
1821            ModelRates::new(4.00, 15.00).with_cache_read(0.20)
1822        );
1823    }
1824
1825    #[test]
1826    fn dated_aliases_resolve_and_unlisted_releases_do_not() {
1827        let catalog = PricingCatalog::standard();
1828        for (provider, model, expected) in [
1829            ("openai", "gpt-4.1-2025-04-14", "gpt-4.1"),
1830            ("openai", "gpt-4o-mini-2024-07-18", "gpt-4o-mini"),
1831            ("anthropic", "claude-opus-4-1-20250805", "claude-opus-4-1"),
1832            ("anthropic", "claude-3-5-haiku-20241022", "claude-3-5-haiku"),
1833            ("bedrock", "us.anthropic.claude-sonnet-4-5-20250929-v1:0", "claude-sonnet-4-5"),
1834            ("bedrock", "anthropic.claude-haiku-4-5-20251001-v1:0", "claude-haiku-4-5"),
1835            ("openrouter", "anthropic/claude-sonnet-4.5", "claude-sonnet-4-5"),
1836            ("openrouter", "google/gemini-3.7-flash", "gemini-3.7-flash"),
1837            ("gemini", "models/gemini-2.5-flash-001", "gemini-2.5-flash"),
1838            ("anthropic", "claude-opus-5-5-latest", "claude-opus-5-5"),
1839            ("groq", "openai/gpt-oss-120b", "gpt-oss-120b"),
1840            ("groq", "qwen/qwen3.8-27b", "qwen3.8-27b"),
1841            ("xai", "grok-4.5-latest", "grok-4.5"),
1842            ("xai", "grok-4.20-0309", "grok-4.20"),
1843            ("xai", "grok-code-fast-1-0825", "grok-code-fast-1"),
1844            ("openrouter", "x-ai/grok-4.6", "grok-4.6"),
1845            ("mistral", "mistral-medium-latest", "mistral-medium-latest"),
1846            ("mistral", "codestral-2508", "codestral-2508"),
1847            ("mistral", "mistral-large-4", "mistral-large-4"),
1848            ("openai", "gpt-6.1-sol", "gpt-6.1-sol"),
1849            ("anthropic", "claude-fable-5-2", "claude-fable-5-2"),
1850            ("bedrock", "global.anthropic.claude-fable-5-2", "claude-fable-5-2"),
1851        ] {
1852            assert_eq!(
1853                catalog.lookup(Some(provider), model).map(|price| price.model.as_str()),
1854                Some(expected),
1855                "{provider}/{model}"
1856            );
1857        }
1858        for (provider, model) in [
1859            ("anthropic", "claude-opus-4-9"),
1860            ("openai", "gpt-5-turbo"),
1861            ("openai", "gpt-image-2"),
1862            ("gemini", "gemini-3.1-flash-live-preview"),
1863            ("gemini", "gemini-3.8-live"),
1864            ("groq", "llama-3.3-70b-versatile"),
1865            ("groq", "minimaxai/minimax-m2.7"),
1866            ("cerebras", "gpt-oss-120b"),
1867            ("xai", "grok-5"),
1868            ("mistral", "mistral-medium-2508"),
1869            ("together", "gpt-4.1"),
1870            ("deepseek", "gpt-4.1"),
1871            ("opencode", "claude-sonnet-5"),
1872        ] {
1873            assert!(catalog.lookup(Some(provider), model).is_none(), "{provider}/{model}");
1874        }
1875    }
1876
1877    #[test]
1878    fn xai_long_context_starts_at_200k_and_bills_the_whole_request() {
1879        let price = price("xai", "grok-4.6");
1880        let short = price.cost_usd(&usage(199_999, 1_000), today());
1881        let long = price.cost_usd(&usage(200_000, 1_000), today());
1882        assert!((short - (199_999.0 * 2.00 + 1_000.0 * 6.00) / 1e6).abs() < 1e-12, "{short}");
1883        assert!((long - (200_000.0 * 4.00 + 1_000.0 * 12.00) / 1e6).abs() < 1e-12, "{long}");
1884    }
1885
1886    #[test]
1887    fn groq_cached_input_is_billed_at_the_cached_rate() {
1888        let usage =
1889            UsageMetadata { cache_read_input_token_count: Some(500_000), ..usage(1_000_000, 0) };
1890        let cost = price("groq", "openai/gpt-oss-20b").cost_usd(&usage, today());
1891        assert!((cost - (500_000.0 * 0.075 + 500_000.0 * 0.037) / 1e6).abs() < 1e-12, "{cost}");
1892    }
1893
1894    fn text_request(model: &str, text: &str) -> LlmRequest {
1895        LlmRequest::new(model, vec![adk_core::Content::new("user").with_text(text)])
1896    }
1897
1898    #[test]
1899    fn the_cost_bound_covers_the_most_expensive_usage_the_request_allows() {
1900        let catalog = PricingCatalog::standard();
1901        let request = text_request("claude-sonnet-4-5", &"word ".repeat(10_000));
1902        let prompt = request_input_token_bound(&request).unwrap();
1903        let bound = catalog
1904            .max_cost_micro_usd(Some("anthropic"), "claude-sonnet-4-5", &request, Some(4_096))
1905            .unwrap();
1906        // Worst case: every prompt token written to the 1-hour cache, full output.
1907        let worst = UsageMetadata {
1908            prompt_token_count: prompt as i32,
1909            candidates_token_count: 4_096,
1910            cache_creation_input_token_count: Some(prompt as i32),
1911            provider_usage: Some(serde_json::json!({ "cache_creation_input_tokens_1h": prompt })),
1912            ..Default::default()
1913        };
1914        let cost = catalog.cost_usd(Some("anthropic"), "claude-sonnet-4-5", &worst).unwrap();
1915        assert!(adk_core::usd_to_micro_usd(cost).unwrap() <= bound, "{cost} vs {bound}");
1916    }
1917
1918    #[test]
1919    fn a_prompt_bound_past_the_long_context_threshold_uses_long_rates() {
1920        let catalog = PricingCatalog::standard();
1921        let request = text_request("gemini-2.5-pro", &"x".repeat(300_000));
1922        let bound = catalog
1923            .max_cost_micro_usd(Some("gemini"), "gemini-2.5-pro", &request, Some(0))
1924            .unwrap();
1925        let prompt = request_input_token_bound(&request).unwrap() as f64;
1926        assert_eq!(bound, (prompt * 2.50).ceil() as u64 + 1);
1927    }
1928
1929    #[test]
1930    fn requests_without_an_output_cap_use_the_model_limit_or_stay_unbounded() {
1931        let catalog = PricingCatalog::standard();
1932        let request = text_request("gpt-4.1", "hi");
1933        let uncapped = catalog.max_cost_micro_usd(Some("openai"), "gpt-4.1", &request, None);
1934        let capped = catalog.max_cost_micro_usd(Some("openai"), "gpt-4.1", &request, Some(32_768));
1935        assert_eq!(uncapped, capped);
1936        // xAI publishes no output limit.
1937        assert_eq!(catalog.max_cost_micro_usd(Some("xai"), "grok-4.6", &request, None), None);
1938        assert!(catalog.max_cost_micro_usd(Some("xai"), "grok-4.6", &request, Some(100)).is_some());
1939        assert_eq!(
1940            catalog.max_cost_micro_usd(Some("together"), "gpt-4.1", &request, Some(1)),
1941            None
1942        );
1943        assert_eq!(catalog.max_cost_micro_usd(Some("ollama"), "qwen3.5", &request, None), Some(0));
1944    }
1945
1946    #[test]
1947    fn built_in_tool_fees_are_bounded_by_max_uses_or_left_unbounded() {
1948        let catalog = PricingCatalog::standard();
1949        let with_tool = |model: &str, tool: serde_json::Value| {
1950            let mut request = text_request(model, "search the web");
1951            request.tools.insert("web_search".to_string(), tool);
1952            request
1953        };
1954        let plain = catalog
1955            .max_cost_micro_usd(
1956                Some("anthropic"),
1957                "claude-sonnet-4-6",
1958                &text_request("claude-sonnet-4-6", "search the web"),
1959                Some(1_000),
1960            )
1961            .unwrap();
1962        let capped = with_tool(
1963            "claude-sonnet-4-6",
1964            serde_json::json!({ "x-adk-anthropic-tool": { "type": "web_search_20250305", "max_uses": 3 } }),
1965        );
1966        let bound = catalog.max_cost_micro_usd(
1967            Some("anthropic"),
1968            "claude-sonnet-4-6",
1969            &capped,
1970            Some(1_000),
1971        );
1972        // Three searches at $0.01 each, plus the declaration's own input bytes.
1973        assert!(bound.unwrap() >= plain + 30_000, "{bound:?} vs {plain}");
1974        // Off the vendor's own API the fee does not apply.
1975        assert!(
1976            catalog
1977                .max_cost_micro_usd(Some("bedrock"), "claude-sonnet-4-6", &capped, Some(1_000))
1978                .unwrap()
1979                < plain + 30_000
1980        );
1981
1982        let uncapped = with_tool(
1983            "claude-sonnet-4-6",
1984            serde_json::json!({ "x-adk-anthropic-tool": { "type": "web_search_20250305" } }),
1985        );
1986        assert_eq!(
1987            catalog.max_cost_micro_usd(
1988                Some("anthropic"),
1989                "claude-sonnet-4-6",
1990                &uncapped,
1991                Some(1_000)
1992            ),
1993            None
1994        );
1995
1996        // Gemini 2.5 grounding is billed once per response.
1997        let grounded = with_tool(
1998            "gemini-2.5-flash",
1999            serde_json::json!({ "x-adk-gemini-tool": { "googleSearch": {} } }),
2000        );
2001        let bound = catalog
2002            .max_cost_micro_usd(Some("gemini"), "gemini-2.5-flash", &grounded, Some(0))
2003            .unwrap();
2004        let tokens = request_input_token_bound(&grounded).unwrap() as f64;
2005        assert_eq!(bound, (tokens * 0.30 + 35_000.0 + 25_000.0).ceil() as u64 + 1);
2006    }
2007
2008    #[test]
2009    fn a_request_referencing_a_file_uri_cannot_be_bounded() {
2010        let mut request = text_request("gpt-4.1", "describe");
2011        request.contents[0].parts.push(Part::FileData {
2012            mime_type: "video/mp4".to_string(),
2013            file_uri: "gs://bucket/video.mp4".to_string(),
2014            annotations: None,
2015        });
2016        assert_eq!(request_input_token_bound(&request), None);
2017        let mut inline = text_request("gpt-4.1", "");
2018        inline.contents[0].parts.push(Part::InlineData {
2019            mime_type: "image/png".to_string(),
2020            data: vec![0; 10],
2021            uri: None,
2022            annotations: None,
2023        });
2024        assert_eq!(
2025            request_input_token_bound(&inline),
2026            Some(REQUEST_OVERHEAD_TOKENS + 16 + MEDIA_PART_MIN_TOKENS)
2027        );
2028    }
2029
2030    #[test]
2031    fn gemini_reports_37_flash_as_38_flash_and_both_are_priced() {
2032        let catalog = PricingCatalog::standard();
2033        let usage = usage(1_000_000, 100_000);
2034        for model in ["gemini-3.8-flash", "gemini-3.7-flash", "models/gemini-3.8-flash"] {
2035            let cost = price("gemini", model).cost_usd(&usage, today());
2036            assert!((cost - (0.75 + 0.375)).abs() < 1e-9, "{model}: {cost}");
2037        }
2038        assert_eq!(price("gemini", "gemini-3.8-flash").max_output_tokens, Some(65_536));
2039        let after = price("gemini", "gemini-3.8-flash")
2040            .cost_usd(&usage, NaiveDate::from_ymd_opt(2027, 1, 1).unwrap());
2041        assert!((after - (1.50 + 0.75)).abs() < 1e-9, "{after}");
2042        assert!(
2043            catalog
2044                .cost_usd(Some("gemini"), "gemini-3.1-pro-preview-customtools", &usage)
2045                .is_some()
2046        );
2047    }
2048
2049    #[test]
2050    fn deepseek_bills_peak_rates_in_peak_hours_and_half_off_peak() {
2051        use chrono::TimeZone;
2052        let usage = UsageMetadata {
2053            cache_read_input_token_count: Some(500_000),
2054            ..usage(1_000_000, 100_000)
2055        };
2056        let flash = price("deepseek", "deepseek-flash");
2057        // Monday 2026-10-12 07:00 UTC is peak; 12:00 UTC and Sunday are off-peak.
2058        let peak = chrono::Utc.with_ymd_and_hms(2026, 10, 12, 7, 0, 0).unwrap();
2059        let midday = chrono::Utc.with_ymd_and_hms(2026, 10, 12, 12, 0, 0).unwrap();
2060        let sunday = chrono::Utc.with_ymd_and_hms(2026, 10, 11, 7, 0, 0).unwrap();
2061        // 500K uncached × $0.30 + 500K cache hits × $0.006 + 100K × $1.20.
2062        let expected_peak = 0.15 + 0.003 + 0.12;
2063        assert!((flash.cost_usd_at(&usage, peak) - expected_peak).abs() < 1e-9);
2064        assert!((flash.cost_usd_at(&usage, midday) - expected_peak / 2.0).abs() < 1e-9);
2065        assert!((flash.cost_usd_at(&usage, sunday) - expected_peak / 2.0).abs() < 1e-9);
2066        let pro = price("deepseek", "deepseek-v4-pro");
2067        assert!((pro.cost_usd_at(&usage, peak) - (0.66 + 0.022 + 0.396)).abs() < 1e-9);
2068        assert_eq!(price("deepseek", "deepseek-v4-flash").rates, flash.rates);
2069        assert!(PricingCatalog::standard().lookup(Some("deepseek"), "deepseek-chat").is_none());
2070        // The bound prices at peak, so it covers an off-peak call too.
2071        let request = text_request("deepseek-flash", "hi");
2072        let bound = PricingCatalog::standard()
2073            .max_cost_micro_usd(Some("deepseek"), "deepseek-flash", &request, None)
2074            .unwrap();
2075        let prompt = request_input_token_bound(&request).unwrap() as f64;
2076        assert_eq!(bound, (prompt * 0.30 + 393_216.0 * 1.20).ceil() as u64 + 1);
2077    }
2078
2079    #[test]
2080    fn local_ollama_is_free_and_cloud_ollama_is_unpriced() {
2081        let catalog = PricingCatalog::standard();
2082        assert_eq!(catalog.cost_usd(Some("ollama"), "qwen3.5", &usage(10, 10)), Some(0.0));
2083        assert_eq!(catalog.cost_usd(Some("ollama"), "gpt-oss:120b-cloud", &usage(10, 10)), None);
2084    }
2085
2086    #[test]
2087    fn negative_counts_never_produce_negative_cost() {
2088        let usage = UsageMetadata { cache_read_input_token_count: Some(5_000), ..usage(-10, -10) };
2089        assert_eq!(price("openai", "gpt-4.1").cost_usd(&usage, today()), 5_000.0 * 0.5 / 1e6);
2090    }
2091
2092    #[cfg(feature = "gemini")]
2093    #[test]
2094    fn gemini_rates_match_adk_gemini_pricing() {
2095        for price in PricingCatalog::standard().prices() {
2096            if price.vendor != PriceVendor::Google {
2097                continue;
2098            }
2099            let Some(vendor) = adk_gemini::pricing::GeminiPricing::for_model_id(&price.model)
2100            else {
2101                continue;
2102            };
2103            // adk-gemini prices on today's date, so it matches the base rates or, once a
2104            // dated change is in force (Gemini 4 Carbon and Argon from 2026-12-01), the new ones.
2105            let same = |a: f64, b: f64| (a - b).abs() < 1e-9;
2106            let matches = |rates: ModelRates| {
2107                same(rates.input, vendor.input)
2108                    && same(rates.output, vendor.output)
2109                    && (vendor.cache_input <= 0.0 || same(rates.cache_read, vendor.cache_input))
2110            };
2111            assert!(
2112                matches(price.rates) || price.change.is_some_and(|change| matches(change.rates)),
2113                "{}: adk-gemini prices it at {vendor:?}",
2114                price.model
2115            );
2116            match price.long_context {
2117                Some(tier) => assert_eq!(tier.rates.input, vendor.input_long, "{}", price.model),
2118                None => assert_eq!(vendor.input_long, vendor.input, "{}", price.model),
2119            }
2120        }
2121    }
2122
2123    #[cfg(feature = "openai")]
2124    #[test]
2125    fn openai_rates_match_openai_pricing() {
2126        for price in PricingCatalog::standard().prices() {
2127            if price.vendor != PriceVendor::OpenAI {
2128                continue;
2129            }
2130            let vendor = crate::openai::pricing::lookup_pricing(&price.model)
2131                .unwrap_or_else(|| panic!("{} is missing from openai::pricing", price.model));
2132            assert_eq!(price.rates.input, vendor.input, "{}", price.model);
2133            assert_eq!(price.rates.output, vendor.output, "{}", price.model);
2134            assert_eq!(price.rates.cache_read, vendor.cached_input, "{}", price.model);
2135        }
2136    }
2137
2138    #[cfg(feature = "anthropic")]
2139    #[test]
2140    fn anthropic_rates_match_adk_anthropic_pricing() {
2141        for price in PricingCatalog::standard().prices() {
2142            if price.vendor != PriceVendor::Anthropic {
2143                continue;
2144            }
2145            let vendor = adk_anthropic::pricing::ModelPricing::for_model_id(&price.model)
2146                .unwrap_or_else(|| {
2147                    panic!("{} is missing from adk_anthropic::pricing", price.model)
2148                });
2149            assert_eq!(price.rates.input, vendor.input, "{}", price.model);
2150            assert_eq!(price.rates.output, vendor.output, "{}", price.model);
2151            assert_eq!(price.rates.cache_read, vendor.cache_read, "{}", price.model);
2152            assert_eq!(price.rates.cache_write_5m, vendor.cache_write_5m, "{}", price.model);
2153            assert_eq!(price.rates.cache_write_1h, vendor.cache_write_1h, "{}", price.model);
2154        }
2155    }
2156}