use adk_core::{LlmRequest, Part, UnitRate, UsageMetadata, UsageUnit, UsageVector};
use chrono::NaiveDate;
use std::sync::LazyLock;
pub const PRICING_EFFECTIVE_DATE: &str = "2026-11-17";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PriceVendor {
Google,
OpenAI,
Anthropic,
DeepSeek,
Groq,
Meta,
XAi,
Mistral,
}
impl PriceVendor {
pub fn billed_by(self, provider: &str) -> bool {
match self {
Self::Google => matches!(provider, "gemini" | "openrouter"),
Self::OpenAI => matches!(
provider,
"openai" | "openai-responses" | "azure-openai" | "azure-ai" | "openrouter"
),
Self::Anthropic => {
matches!(provider, "anthropic" | "bedrock" | "azure-ai" | "openrouter")
}
Self::DeepSeek => provider == "deepseek",
Self::Groq => provider == "groq",
Self::Meta => provider == "muse",
Self::XAi => matches!(provider, "xai" | "openrouter"),
Self::Mistral => matches!(provider, "mistral" | "openrouter"),
}
}
}
impl PriceVendor {
pub fn first_party(self, provider: &str) -> bool {
match self {
Self::Google => provider == "gemini",
Self::OpenAI => matches!(provider, "openai" | "openai-responses"),
Self::Anthropic => provider == "anthropic",
Self::DeepSeek => provider == "deepseek",
Self::Groq => provider == "groq",
Self::Meta => provider == "muse",
Self::XAi => provider == "xai",
Self::Mistral => provider == "mistral",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FeeUnit {
PerUse,
PerResponse,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BuiltinToolFee {
pub vendor: PriceVendor,
pub kind: String,
pub models: Vec<String>,
pub usd: f64,
pub unit: FeeUnit,
}
impl BuiltinToolFee {
pub fn per_use(vendor: PriceVendor, kind: impl Into<String>, usd: f64) -> Self {
Self { vendor, kind: kind.into(), models: Vec::new(), usd, unit: FeeUnit::PerUse }
}
pub fn per_response(vendor: PriceVendor, kind: impl Into<String>, usd: f64) -> Self {
Self { unit: FeeUnit::PerResponse, ..Self::per_use(vendor, kind, usd) }
}
pub fn for_models(mut self, models: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.models = models.into_iter().map(Into::into).collect();
self
}
pub fn applies_to(&self, model: &str) -> bool {
if self.models.is_empty() {
return true;
}
let canonical = canonical_model_id(model);
self.models.iter().any(|pattern| match pattern.strip_suffix('*') {
Some(prefix) => canonical.starts_with(prefix),
None => {
canonical == *pattern
|| canonical.strip_prefix(pattern.as_str()).is_some_and(is_version_suffix)
}
})
}
pub fn cost_usd(&self, count: u32) -> f64 {
match self.unit {
FeeUnit::PerUse => f64::from(count) * self.usd,
FeeUnit::PerResponse if count > 0 => self.usd,
FeeUnit::PerResponse => 0.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ModelRates {
pub input: f64,
pub output: f64,
pub cache_read: f64,
pub cache_write_5m: f64,
pub cache_write_1h: f64,
}
impl ModelRates {
pub const fn new(input: f64, output: f64) -> Self {
Self { input, output, cache_read: input, cache_write_5m: input, cache_write_1h: input }
}
pub const fn with_cache_read(mut self, rate: f64) -> Self {
self.cache_read = rate;
self
}
pub const fn with_cache_writes(mut self, five_minute: f64, one_hour: f64) -> Self {
self.cache_write_5m = five_minute;
self.cache_write_1h = one_hour;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LongContextTier {
pub min_prompt_tokens: u64,
pub rates: ModelRates,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RateChange {
pub effective: NaiveDate,
pub rates: ModelRates,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ModelPrice {
pub vendor: PriceVendor,
pub model: String,
pub rates: ModelRates,
pub long_context: Option<LongContextTier>,
pub change: Option<RateChange>,
pub max_output_tokens: Option<u64>,
pub context_window_tokens: Option<u64>,
pub off_peak: Option<OffPeak>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct OffPeak {
pub factor: f64,
pub peak_hours_utc: Vec<(u32, u32)>,
}
impl OffPeak {
pub fn weekdays(factor: f64, peak_hours_utc: &[(u32, u32)]) -> Self {
Self { factor, peak_hours_utc: peak_hours_utc.to_vec() }
}
pub fn is_peak(&self, at: chrono::DateTime<chrono::Utc>) -> bool {
use chrono::{Datelike, Timelike, Weekday};
if matches!(at.weekday(), Weekday::Sat | Weekday::Sun) {
return false;
}
let hour = at.hour();
self.peak_hours_utc.iter().any(|(start, end)| hour >= *start && hour < *end)
}
}
impl ModelPrice {
pub fn new(vendor: PriceVendor, model: impl Into<String>, rates: ModelRates) -> Self {
Self {
vendor,
model: model.into(),
rates,
long_context: None,
change: None,
max_output_tokens: None,
context_window_tokens: None,
off_peak: None,
}
}
pub fn with_off_peak(mut self, off_peak: OffPeak) -> Self {
self.off_peak = Some(off_peak);
self
}
pub fn with_max_output_tokens(mut self, tokens: u64) -> Self {
self.max_output_tokens = Some(tokens);
self
}
pub fn with_context_window(mut self, tokens: u64) -> Self {
self.context_window_tokens = Some(tokens);
self
}
pub fn max_cost_usd(&self, prompt_tokens: u64, output_tokens: u64, date: NaiveDate) -> f64 {
let rates = self.rates_for(prompt_tokens, date);
let input =
rates.input.max(rates.cache_read).max(rates.cache_write_5m).max(rates.cache_write_1h);
(prompt_tokens as f64 * input + output_tokens as f64 * rates.output) / 1_000_000.0
}
pub fn with_long_context(mut self, min_prompt_tokens: u64, rates: ModelRates) -> Self {
self.long_context = Some(LongContextTier { min_prompt_tokens, rates });
self
}
pub fn with_change(mut self, effective: NaiveDate, rates: ModelRates) -> Self {
self.change = Some(RateChange { effective, rates });
self
}
pub fn rates_for(&self, prompt_tokens: u64, date: NaiveDate) -> ModelRates {
if let Some(tier) = self.long_context
&& prompt_tokens >= tier.min_prompt_tokens
{
return tier.rates;
}
match self.change {
Some(change) if date >= change.effective => change.rates,
_ => self.rates,
}
}
pub fn cost_usd(&self, usage: &UsageMetadata, date: NaiveDate) -> f64 {
self.cost_with_rates(usage, self.rates_for(non_negative(usage.prompt_token_count), date))
}
pub fn cost_usd_at(&self, usage: &UsageMetadata, at: chrono::DateTime<chrono::Utc>) -> f64 {
let mut rates = self.rates_for(non_negative(usage.prompt_token_count), at.date_naive());
if let Some(off_peak) = &self.off_peak
&& !off_peak.is_peak(at)
{
rates = ModelRates {
input: rates.input * off_peak.factor,
output: rates.output * off_peak.factor,
cache_read: rates.cache_read * off_peak.factor,
cache_write_5m: rates.cache_write_5m * off_peak.factor,
cache_write_1h: rates.cache_write_1h * off_peak.factor,
};
}
self.cost_with_rates(usage, rates)
}
fn cost_with_rates(&self, usage: &UsageMetadata, rates: ModelRates) -> f64 {
let prompt = non_negative(usage.prompt_token_count);
let cache_read = non_negative(usage.cache_read_input_token_count.unwrap_or(0));
let cache_write = non_negative(usage.cache_creation_input_token_count.unwrap_or(0));
let write_1h = one_hour_cache_writes(usage).min(cache_write);
let write_5m = cache_write - write_1h;
let uncached = prompt.saturating_sub(cache_read.saturating_add(cache_write));
let output = non_negative(usage.candidates_token_count);
(uncached as f64 * rates.input
+ cache_read as f64 * rates.cache_read
+ write_5m as f64 * rates.cache_write_5m
+ write_1h as f64 * rates.cache_write_1h
+ output as f64 * rates.output)
/ 1_000_000.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitPrice {
pub vendor: PriceVendor,
pub model: String,
pub rate: UnitRate,
}
impl UnitPrice {
pub fn new(vendor: PriceVendor, model: impl Into<String>, rate: UnitRate) -> Self {
Self { vendor, model: model.into(), rate }
}
}
#[derive(Debug, Clone)]
pub struct PricingCatalog {
version: String,
prices: Vec<ModelPrice>,
fees: Vec<BuiltinToolFee>,
units: Vec<UnitPrice>,
}
impl PricingCatalog {
pub fn new(version: impl Into<String>) -> Self {
Self { version: version.into(), prices: Vec::new(), fees: Vec::new(), units: Vec::new() }
}
pub fn standard() -> &'static PricingCatalog {
static STANDARD: LazyLock<PricingCatalog> = LazyLock::new(standard_catalog);
&STANDARD
}
pub fn with_price(mut self, price: ModelPrice) -> Self {
self.prices.retain(|existing| existing.model != price.model);
self.prices.push(price);
self
}
pub fn version(&self) -> &str {
&self.version
}
pub fn prices(&self) -> &[ModelPrice] {
&self.prices
}
pub fn with_builtin_tool_fee(mut self, fee: BuiltinToolFee) -> Self {
self.fees.push(fee);
self
}
pub fn builtin_tool_fees(&self) -> &[BuiltinToolFee] {
&self.fees
}
pub fn with_unit_price(mut self, price: UnitPrice) -> Self {
self.units.retain(|existing| {
existing.model != price.model || existing.rate.unit != price.rate.unit
});
self.units.push(price);
self
}
pub fn unit_prices(&self) -> &[UnitPrice] {
&self.units
}
pub fn unit_price(
&self,
provider: Option<&str>,
model: &str,
unit: UsageUnit,
) -> Option<&UnitPrice> {
let canonical = canonical_model_id(model);
let candidates = self.units.iter().filter(|price| price.rate.unit == unit);
let candidate =
candidates.clone().find(|price| price.model == canonical).or_else(|| {
candidates
.filter(|price| {
canonical.strip_prefix(price.model.as_str()).is_some_and(is_version_suffix)
})
.max_by_key(|price| price.model.len())
})?;
match provider {
Some(provider) if !candidate.vendor.billed_by(provider) => None,
_ => Some(candidate),
}
}
pub fn unit_cost_micro_usd(
&self,
provider: Option<&str>,
model: &str,
usage: &UsageVector,
) -> Option<u64> {
usage.iter().try_fold(0u64, |total, (unit, amount)| {
let price = self.unit_price(provider, model, unit)?;
Some(total.saturating_add(price.rate.cost_micro_usd(amount)))
})
}
pub fn builtin_tool_fee(
&self,
provider: Option<&str>,
model: &str,
kind: &str,
) -> Option<&BuiltinToolFee> {
let vendor = self.lookup(provider, model).map(|price| price.vendor);
self.fees.iter().find(|fee| {
fee.kind == kind
&& vendor.is_none_or(|vendor| vendor == fee.vendor)
&& provider.is_none_or(|provider| fee.vendor.first_party(provider))
&& fee.applies_to(model)
})
}
pub fn builtin_tool_cost_usd(
&self,
provider: Option<&str>,
model: &str,
usage: &UsageMetadata,
) -> f64 {
usage
.builtin_tool_uses
.iter()
.filter_map(|used| match self.builtin_tool_fee(provider, model, &used.kind) {
Some(fee) => Some(fee.cost_usd(used.count)),
None => {
tracing::debug!(
builtin_tool.kind = %used.kind,
gen_ai.request.model = %model,
"no published fee for built-in tool; cost covers tokens only"
);
None
}
})
.sum()
}
pub fn context_window(&self, provider: Option<&str>, model: &str) -> Option<u64> {
self.lookup(provider, model)?.context_window_tokens
}
pub fn lookup(&self, provider: Option<&str>, model: &str) -> Option<&ModelPrice> {
let canonical = canonical_model_id(model);
let candidate =
self.prices.iter().find(|price| price.model == canonical).or_else(|| {
self.prices
.iter()
.filter(|price| {
canonical.strip_prefix(price.model.as_str()).is_some_and(is_version_suffix)
})
.max_by_key(|price| price.model.len())
})?;
match provider {
Some(provider) if !candidate.vendor.billed_by(provider) => None,
_ => Some(candidate),
}
}
pub fn max_cost_micro_usd(
&self,
provider: Option<&str>,
model: &str,
request: &LlmRequest,
max_output_tokens: Option<u64>,
) -> Option<u64> {
if provider == Some("ollama") {
return (!model.contains("cloud")).then_some(0);
}
let price = self.lookup(provider, model)?;
let output = max_output_tokens.or(price.max_output_tokens)?;
let prompt = request_input_token_bound(request)?;
let today = chrono::Utc::now().date_naive();
let tomorrow = today.succ_opt().unwrap_or(today);
let usd = price
.max_cost_usd(prompt, output, today)
.max(price.max_cost_usd(prompt, output, tomorrow))
+ self.builtin_tool_fee_bound_usd(provider, model, price.vendor, request)?;
adk_core::usd_to_micro_usd(usd).map(|micro| micro.saturating_add(1))
}
fn builtin_tool_fee_bound_usd(
&self,
provider: Option<&str>,
model: &str,
vendor: PriceVendor,
request: &LlmRequest,
) -> Option<f64> {
let declared: Vec<&serde_json::Value> =
request.tools.values().filter_map(adk_core::builtin_tool_configuration).collect();
if declared.is_empty() {
return Some(0.0);
}
let applicable = self.fees.iter().filter(|fee| {
fee.usd > 0.0
&& fee.vendor == vendor
&& provider.is_none_or(|provider| fee.vendor.first_party(provider))
&& fee.applies_to(model)
});
let mut per_response = 0.0;
let mut per_use: Option<f64> = None;
for fee in applicable {
match fee.unit {
FeeUnit::PerResponse => per_response += fee.usd,
FeeUnit::PerUse => per_use = Some(per_use.map_or(fee.usd, |max| max.max(fee.usd))),
}
}
let Some(per_use) = per_use else {
return Some(per_response);
};
let mut uses = 0u64;
for configuration in declared {
uses = uses.saturating_add(configuration.get("max_uses")?.as_u64()?);
}
Some(per_response + uses as f64 * per_use)
}
pub fn cost_usd(
&self,
provider: Option<&str>,
model: &str,
usage: &UsageMetadata,
) -> Option<f64> {
if provider == Some("ollama") {
return (!model.contains("cloud")).then_some(0.0);
}
let price = self.lookup(provider, model)?;
Some(
price.cost_usd_at(usage, chrono::Utc::now())
+ self.builtin_tool_cost_usd(provider, model, usage),
)
}
}
pub const MEDIA_PART_MIN_TOKENS: u64 = 16_384;
pub const REQUEST_OVERHEAD_TOKENS: u64 = 2_048;
pub fn request_input_token_bound(request: &LlmRequest) -> Option<u64> {
let json_len = |value: &dyn erased::Json| value.byte_len();
let mut tokens = REQUEST_OVERHEAD_TOKENS;
for content in &request.contents {
tokens = tokens.saturating_add(16);
for part in &content.parts {
let part_tokens = match part {
Part::Text { text } => text.len() as u64,
Part::Thinking { thinking, signature } => {
(thinking.len() + signature.as_ref().map_or(0, String::len)) as u64
}
Part::InlineData { data, .. } => (data.len() as u64).max(MEDIA_PART_MIN_TOKENS),
Part::FileData { .. } => return None,
_ => json_len(part),
};
tokens = tokens.saturating_add(part_tokens);
}
}
for declaration in request.tools.values() {
tokens = tokens.saturating_add(16).saturating_add(json_len(declaration));
}
if let Some(config) = &request.config {
if let Some(schema) = &config.response_schema {
tokens = tokens.saturating_add(json_len(schema));
}
tokens = tokens.saturating_add(config.stop_sequences.iter().map(|s| s.len() as u64).sum());
}
Some(tokens)
}
#[cfg(any(
feature = "anthropic",
feature = "azure-ai",
feature = "bedrock",
feature = "gemini",
feature = "ollama",
feature = "openai"
))]
pub(crate) fn request_output_cap(request: &LlmRequest) -> Option<u64> {
request
.config
.as_ref()
.and_then(|config| config.max_output_tokens)
.and_then(|tokens| u64::try_from(tokens).ok())
}
mod erased {
pub trait Json {
fn byte_len(&self) -> u64;
}
impl<T: serde::Serialize> Json for T {
fn byte_len(&self) -> u64 {
serde_json::to_vec(self).map_or(u64::MAX / 4, |bytes| bytes.len() as u64)
}
}
}
fn non_negative(tokens: i32) -> u64 {
u64::try_from(tokens).unwrap_or(0)
}
fn one_hour_cache_writes(usage: &UsageMetadata) -> u64 {
let Some(provider_usage) = usage.provider_usage.as_ref() else {
return 0;
};
provider_usage
.get("cache_creation_input_tokens_1h")
.or_else(|| provider_usage.pointer("/cache_creation/ephemeral_1h_input_tokens"))
.and_then(serde_json::Value::as_u64)
.unwrap_or(0)
}
fn canonical_model_id(model: &str) -> String {
let lowered = model.trim().to_ascii_lowercase();
let mut id = lowered.rsplit('/').next().unwrap_or(&lowered);
for region in ["us.", "eu.", "apac.", "global.", "us-gov.", "jp.", "au.", "ca."] {
if let Some(rest) = id.strip_prefix(region) {
id = rest;
break;
}
}
if let Some(rest) = id.strip_prefix("anthropic.") {
id = rest;
}
let id = match id.rfind("-v") {
Some(index)
if id[index + 2..]
.split(':')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())) =>
{
&id[..index]
}
_ => id,
};
let mut id = id.replace('@', "-");
if id.starts_with("claude-") {
id = id.replace('.', "-");
}
id
}
fn is_version_suffix(rest: &str) -> bool {
let Some(rest) = rest.strip_prefix('-') else {
return false;
};
if rest == "latest" {
return true;
}
let digits =
|part: &str, len: usize| part.len() == len && part.bytes().all(|b| b.is_ascii_digit());
if rest.len() >= 3 && rest.bytes().all(|b| b.is_ascii_digit()) {
return true;
}
let parts: Vec<&str> = rest.split('-').collect();
matches!(parts.as_slice(), [year, month, day] if digits(year, 4) && digits(month, 2) && digits(day, 2))
}
fn standard_catalog() -> PricingCatalog {
use PriceVendor::{Anthropic, DeepSeek, Google, Groq, Meta, Mistral, OpenAI, XAi};
let gemini = |model: &str, input: f64, output: f64, cache_read: f64| {
ModelPrice::new(Google, model, ModelRates::new(input, output).with_cache_read(cache_read))
};
let openai = |model: &str, input: f64, output: f64, cache_read: f64| {
ModelPrice::new(OpenAI, model, ModelRates::new(input, output).with_cache_read(cache_read))
};
let claude = |model: &str, input: f64, output: f64, read: f64, write_5m: f64, write_1h: f64| {
ModelPrice::new(
Anthropic,
model,
ModelRates::new(input, output)
.with_cache_read(read)
.with_cache_writes(write_5m, write_1h),
)
};
const GEMINI_LONG: u64 = 200_001;
const OPENAI_LONG: u64 = 272_001;
const XAI_LONG: u64 = 200_000;
let cached = |vendor: PriceVendor, model: &str, input: f64, output: f64, cache_read: f64| {
ModelPrice::new(vendor, model, ModelRates::new(input, output).with_cache_read(cache_read))
};
let deepseek_off_peak = OffPeak::weekdays(0.5, &[(1, 4), (6, 10)]);
let grok = |model: &str, base: (f64, f64, f64), long: (f64, f64, f64)| {
cached(XAi, model, base.0, base.2, base.1)
.with_long_context(XAI_LONG, ModelRates::new(long.0, long.2).with_cache_read(long.1))
};
let grok_47 = ((2.00, 0.50, 6.00), (4.00, 1.00, 12.00));
let grok_45 = ((2.00, 0.30, 6.00), (4.00, 0.60, 12.00));
let grok_420 = ((1.25, 0.20, 2.50), (2.50, 0.40, 5.00));
let grok_build = ((1.00, 0.20, 2.00), (2.00, 0.40, 4.00));
let flash_2027 = NaiveDate::from_ymd_opt(2027, 1, 1).unwrap_or(NaiveDate::MAX);
let flash_2027_rates = ModelRates::new(1.50, 7.50).with_cache_read(0.15);
let gemini_4_december = NaiveDate::from_ymd_opt(2026, 12, 1).unwrap_or(NaiveDate::MAX);
let gemini_4_rates = ModelRates::new(4.00, 20.00).with_cache_read(0.20);
let prices = vec![
gemini("gemini-4-hydrogen", 1.50, 7.50, 0.075),
gemini("gemini-4-neon", 3.00, 15.00, 0.15),
gemini("gemini-4-carbon", 2.00, 10.00, 0.10).with_change(gemini_4_december, gemini_4_rates),
gemini("gemini-4-argon", 2.00, 10.00, 0.10).with_change(gemini_4_december, gemini_4_rates),
gemini("gemini-3.8-flash", 0.75, 3.75, 0.075).with_change(flash_2027, flash_2027_rates),
gemini("gemini-3.7-flash", 0.75, 3.75, 0.075).with_change(flash_2027, flash_2027_rates),
gemini("gemini-3.6-flash", 0.75, 3.75, 0.075).with_change(flash_2027, flash_2027_rates),
gemini("gemini-3.5-flash", 1.50, 9.00, 0.15),
gemini("gemini-3.5-flash-lite", 0.30, 2.50, 0.03),
gemini("gemini-3.1-pro-preview-customtools", 2.00, 12.00, 0.20)
.with_long_context(GEMINI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
gemini("gemini-3.1-pro-preview", 2.00, 12.00, 0.20)
.with_long_context(GEMINI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
gemini("gemini-3-pro-preview", 2.00, 12.00, 0.20)
.with_long_context(GEMINI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
gemini("gemini-3.1-flash-lite", 0.25, 1.50, 0.025),
gemini("gemini-3-flash-preview", 0.50, 3.00, 0.05),
gemini("gemini-2.5-pro", 1.25, 10.00, 0.125)
.with_long_context(GEMINI_LONG, ModelRates::new(2.50, 15.00).with_cache_read(0.25)),
gemini("gemini-2.5-flash", 0.30, 2.50, 0.03),
gemini("gemini-2.5-flash-preview-09-2025", 0.30, 2.50, 0.03),
gemini("gemini-2.5-flash-lite", 0.10, 0.40, 0.01),
gemini("gemini-2.5-flash-lite-preview-09-2025", 0.10, 0.40, 0.01),
gemini("gemini-2.5-flash-image", 0.30, 30.00, 0.30),
gemini("gemini-2.5-flash-image-preview", 0.30, 30.00, 0.30),
gemini("gemini-2.5-computer-use-preview-10-2025", 1.25, 10.00, 1.25)
.with_long_context(GEMINI_LONG, ModelRates::new(2.50, 15.00)),
gemini("gemini-2.5-flash-preview-tts", 0.50, 10.00, 0.50),
gemini("gemini-2.5-pro-preview-tts", 1.00, 20.00, 1.00),
gemini("gemini-embedding-2", 0.20, 0.0, 0.20),
gemini("gemini-embedding-001", 0.15, 0.0, 0.15),
openai("gpt-6-astra", 10.00, 50.00, 1.00)
.with_long_context(OPENAI_LONG, ModelRates::new(20.00, 75.00).with_cache_read(2.00)),
openai("gpt-6.1-sol", 2.00, 10.00, 0.10)
.with_long_context(OPENAI_LONG, ModelRates::new(4.00, 15.00).with_cache_read(0.20)),
openai("gpt-6.1-terra", 1.00, 5.00, 0.05)
.with_long_context(OPENAI_LONG, ModelRates::new(2.00, 7.50).with_cache_read(0.10)),
openai("gpt-6-sol", 2.00, 10.00, 0.20)
.with_long_context(OPENAI_LONG, ModelRates::new(4.00, 15.00).with_cache_read(0.40)),
openai("gpt-6-luna", 0.10, 0.50, 0.01)
.with_long_context(OPENAI_LONG, ModelRates::new(0.20, 0.75).with_cache_read(0.02)),
openai("gpt-6-cyber", 20.00, 100.00, 2.00)
.with_long_context(OPENAI_LONG, ModelRates::new(40.00, 150.00).with_cache_read(4.00)),
openai("gpt-5.6", 4.00, 20.00, 0.40)
.with_long_context(OPENAI_LONG, ModelRates::new(8.00, 30.00).with_cache_read(0.80)),
openai("gpt-5.6-sol", 4.00, 20.00, 0.40)
.with_long_context(OPENAI_LONG, ModelRates::new(8.00, 30.00).with_cache_read(0.80)),
openai("daybreak-blue-latest", 4.00, 20.00, 0.40),
openai("gpt-5.6-terra", 2.00, 12.00, 0.20)
.with_long_context(OPENAI_LONG, ModelRates::new(4.00, 18.00).with_cache_read(0.40)),
openai("gpt-5.6-luna", 0.20, 1.20, 0.02)
.with_long_context(OPENAI_LONG, ModelRates::new(0.40, 1.80).with_cache_read(0.04)),
openai("gpt-5.6-cyber", 12.50, 75.00, 1.25),
openai("daybreak-red-latest", 12.50, 75.00, 1.25),
openai("gpt-5.5", 5.00, 30.00, 0.50)
.with_long_context(OPENAI_LONG, ModelRates::new(10.00, 45.00).with_cache_read(1.00)),
openai("gpt-5.5-pro", 30.00, 180.00, 30.00)
.with_long_context(OPENAI_LONG, ModelRates::new(60.00, 270.00)),
openai("gpt-5.5-cyber", 12.50, 75.00, 1.25),
openai("gpt-5.4", 2.50, 15.00, 0.25)
.with_long_context(OPENAI_LONG, ModelRates::new(5.00, 22.50).with_cache_read(0.50)),
openai("gpt-5.4-mini", 0.75, 4.50, 0.075),
openai("gpt-5.4-nano", 0.20, 1.25, 0.02),
openai("gpt-5.4-pro", 30.00, 180.00, 30.00)
.with_long_context(OPENAI_LONG, ModelRates::new(60.00, 270.00)),
openai("gpt-5.3-codex", 1.75, 14.00, 0.175),
openai("gpt-5.2", 1.75, 14.00, 0.175),
openai("gpt-5.2-pro", 21.00, 168.00, 21.00),
openai("gpt-5.1", 1.25, 10.00, 0.125),
openai("gpt-5", 1.25, 10.00, 0.125),
openai("gpt-5-mini", 0.25, 2.00, 0.025),
openai("gpt-5-nano", 0.05, 0.40, 0.005),
openai("gpt-5-pro", 15.00, 120.00, 15.00),
openai("gpt-5-search-api", 1.25, 10.00, 0.125),
openai("chat-latest", 5.00, 30.00, 0.50),
openai("gpt-4.1", 2.00, 8.00, 0.50),
openai("gpt-4.1-mini", 0.40, 1.60, 0.10),
openai("gpt-4.1-nano", 0.10, 0.40, 0.025),
openai("o3", 2.00, 8.00, 0.50),
openai("o4-mini", 1.10, 4.40, 0.275),
openai("o3-mini", 1.10, 4.40, 0.55),
openai("o1", 15.00, 60.00, 7.50),
openai("gpt-4o", 2.50, 10.00, 1.25),
openai("gpt-4o-mini", 0.15, 0.60, 0.075),
claude("claude-fable-5-2", 8.0, 40.0, 0.20, 10.0, 16.0),
claude("claude-mythos-5-2", 8.0, 40.0, 0.20, 10.0, 16.0),
claude("claude-fable-5-1", 10.0, 50.0, 0.25, 12.5, 20.0),
claude("claude-mythos-5-1", 10.0, 50.0, 0.25, 12.5, 20.0),
claude("claude-fable-5", 10.0, 50.0, 1.0, 12.5, 20.0),
claude("claude-mythos-5", 10.0, 50.0, 1.0, 12.5, 20.0),
claude("claude-opus-5-5", 4.0, 20.0, 0.20, 5.0, 8.0),
claude("claude-opus-5", 5.0, 25.0, 0.50, 6.25, 10.0),
claude("claude-sonnet-5-5", 2.0, 10.0, 0.10, 2.5, 4.0),
claude("claude-sonnet-5", 2.0, 10.0, 0.20, 2.5, 4.0),
claude("claude-haiku-5-5", 0.10, 0.50, 0.01, 0.125, 0.20).with_long_context(
100_001,
ModelRates::new(0.50, 2.50).with_cache_read(0.05).with_cache_writes(0.625, 1.0),
),
claude("claude-opus-4-8", 5.0, 25.0, 0.50, 6.25, 10.0),
claude("claude-opus-4-7", 5.0, 25.0, 0.50, 6.25, 10.0),
claude("claude-opus-4-6", 5.0, 25.0, 0.50, 6.25, 10.0),
claude("claude-opus-4-5", 5.0, 25.0, 0.50, 6.25, 10.0),
claude("claude-opus-4-1", 15.0, 75.0, 1.50, 18.75, 30.0),
claude("claude-opus-4", 15.0, 75.0, 1.50, 18.75, 30.0),
claude("claude-sonnet-4-6", 3.0, 15.0, 0.30, 3.75, 6.0),
claude("claude-sonnet-4-5", 3.0, 15.0, 0.30, 3.75, 6.0),
claude("claude-sonnet-4", 3.0, 15.0, 0.30, 3.75, 6.0),
claude("claude-haiku-4-5", 1.0, 5.0, 0.10, 1.25, 2.0),
claude("claude-haiku-3-5", 0.80, 4.0, 0.08, 1.0, 1.60),
claude("claude-3-5-haiku", 0.80, 4.0, 0.08, 1.0, 1.60),
cached(DeepSeek, "deepseek-flash", 0.30, 1.20, 0.006)
.with_off_peak(deepseek_off_peak.clone()),
cached(DeepSeek, "deepseek-v4-flash", 0.30, 1.20, 0.006)
.with_off_peak(deepseek_off_peak.clone()),
cached(DeepSeek, "deepseek-v4-pro", 1.32, 3.96, 0.044).with_off_peak(deepseek_off_peak),
cached(Groq, "gpt-oss-120b", 0.15, 0.60, 0.075),
cached(Groq, "gpt-oss-20b", 0.075, 0.30, 0.037),
cached(Groq, "gpt-oss-safeguard-20b", 0.075, 0.30, 0.037),
ModelPrice::new(Groq, "qwen3.8-27b", ModelRates::new(0.80, 4.00)),
cached(Meta, "muse-spark-1.3", 1.25, 4.25, 0.15),
cached(Meta, "muse-spark-1.2", 1.25, 4.25, 0.15),
cached(Meta, "muse-spark-1.1", 1.25, 4.25, 0.15),
cached(Meta, "muse-spark-1.3-contributor", 0.10, 0.20, 0.002),
cached(Meta, "muse-spark-1.2-contributor", 0.10, 0.20, 0.002),
cached(Meta, "muse-wonder-1.0", 4.00, 20.00, 0.20),
cached(Meta, "muse-ember-1.0", 0.10, 0.50, 0.004)
.with_long_context(200_001, ModelRates::new(0.30, 1.50).with_cache_read(0.012)),
grok("grok-4.7", grok_47.0, grok_47.1),
grok("grok-4.6", grok_47.0, grok_47.1),
grok("grok-4.5", grok_45.0, grok_45.1),
grok("grok-build-latest", grok_45.0, grok_45.1),
grok("grok-4.3", grok_420.0, grok_420.1),
grok("grok-4.20", grok_420.0, grok_420.1),
grok("grok-4.20-0309-reasoning", grok_420.0, grok_420.1),
grok("grok-4.20-reasoning", grok_420.0, grok_420.1),
grok("grok-4.20-0309-non-reasoning", grok_420.0, grok_420.1),
grok("grok-4.20-non-reasoning", grok_420.0, grok_420.1),
grok("grok-4.20-multi-agent-0309", grok_420.0, grok_420.1),
grok("grok-4.20-multi-agent", grok_420.0, grok_420.1),
grok("grok-build-0.1", grok_build.0, grok_build.1),
grok("grok-code-fast-1", grok_build.0, grok_build.1),
grok("grok-code-fast", grok_build.0, grok_build.1),
cached(Mistral, "mistral-large-4", 0.7, 2.1, 0.07),
cached(Mistral, "mistral-large-4-0", 0.7, 2.1, 0.07),
cached(Mistral, "mistral-large-latest", 0.7, 2.1, 0.07),
cached(Mistral, "mistral-medium-3-5", 1.5, 7.5, 0.15),
cached(Mistral, "mistral-medium-3", 1.5, 7.5, 0.15),
cached(Mistral, "mistral-medium-latest", 1.5, 7.5, 0.15),
cached(Mistral, "mistral-large-2512", 0.5, 1.5, 0.05),
cached(Mistral, "mistral-small-2603", 0.15, 0.6, 0.015),
cached(Mistral, "mistral-small-latest", 0.15, 0.6, 0.015),
cached(Mistral, "ministral-14b-2512", 0.2, 0.2, 0.02),
cached(Mistral, "ministral-14b-latest", 0.2, 0.2, 0.02),
cached(Mistral, "ministral-8b-2512", 0.15, 0.15, 0.015),
cached(Mistral, "ministral-8b-latest", 0.15, 0.15, 0.015),
cached(Mistral, "ministral-3b-2512", 0.1, 0.1, 0.01),
cached(Mistral, "ministral-3b-latest", 0.1, 0.1, 0.01),
cached(Mistral, "codestral-2508", 0.3, 0.9, 0.03),
cached(Mistral, "codestral-latest", 0.3, 0.9, 0.03),
];
const GEMINI_MAX_OUTPUT: u64 = 65_536;
const CLAUDE_MAX_OUTPUT: u64 = 128_000;
let max_output: &[(&str, u64)] = &[
("claude-fable-5-2", CLAUDE_MAX_OUTPUT),
("claude-mythos-5-2", CLAUDE_MAX_OUTPUT),
("claude-fable-5-1", CLAUDE_MAX_OUTPUT),
("claude-mythos-5-1", CLAUDE_MAX_OUTPUT),
("claude-fable-5", CLAUDE_MAX_OUTPUT),
("claude-mythos-5", CLAUDE_MAX_OUTPUT),
("claude-opus-5-5", CLAUDE_MAX_OUTPUT),
("claude-opus-5", CLAUDE_MAX_OUTPUT),
("claude-sonnet-5-5", CLAUDE_MAX_OUTPUT),
("claude-sonnet-5", CLAUDE_MAX_OUTPUT),
("claude-haiku-5-5", CLAUDE_MAX_OUTPUT),
("claude-opus-4-8", CLAUDE_MAX_OUTPUT),
("claude-opus-4-7", CLAUDE_MAX_OUTPUT),
("claude-opus-4-6", CLAUDE_MAX_OUTPUT),
("claude-opus-4-5", 64_000),
("claude-opus-4-1", 32_000),
("claude-opus-4", 32_000),
("claude-sonnet-4-6", CLAUDE_MAX_OUTPUT),
("claude-sonnet-4-5", 64_000),
("claude-sonnet-4", 64_000),
("claude-haiku-4-5", 64_000),
("gemini-4-hydrogen", GEMINI_MAX_OUTPUT),
("gemini-4-neon", GEMINI_MAX_OUTPUT),
("gemini-4-carbon", GEMINI_MAX_OUTPUT),
("gemini-4-argon", GEMINI_MAX_OUTPUT),
("gemini-3.8-flash", GEMINI_MAX_OUTPUT),
("gemini-3.7-flash", GEMINI_MAX_OUTPUT),
("gemini-3.6-flash", GEMINI_MAX_OUTPUT),
("gemini-3.5-flash", GEMINI_MAX_OUTPUT),
("gemini-3.5-flash-lite", GEMINI_MAX_OUTPUT),
("gemini-3.1-pro-preview", GEMINI_MAX_OUTPUT),
("gemini-3.1-flash-lite", GEMINI_MAX_OUTPUT),
("gemini-3-flash-preview", GEMINI_MAX_OUTPUT),
("gemini-2.5-pro", GEMINI_MAX_OUTPUT),
("gemini-2.5-flash", GEMINI_MAX_OUTPUT),
("gemini-2.5-flash-lite", GEMINI_MAX_OUTPUT),
("gpt-6-astra", 128_000),
("gpt-6.1-sol", 128_000),
("gpt-6.1-terra", 128_000),
("gpt-6-sol", 128_000),
("gpt-6-luna", 128_000),
("gpt-6-cyber", 128_000),
("gpt-5.6", 128_000),
("gpt-5.6-sol", 128_000),
("gpt-5.6-terra", 128_000),
("gpt-5.6-luna", 128_000),
("gpt-5.6-cyber", 128_000),
("gpt-5.5", 128_000),
("gpt-5.5-pro", 128_000),
("gpt-5.4", 128_000),
("gpt-5.4-pro", 128_000),
("gpt-5.4-mini", 128_000),
("gpt-5.4-nano", 128_000),
("gpt-5.3-codex", 128_000),
("gpt-5.2", 128_000),
("gpt-5.2-pro", 128_000),
("gpt-5.1", 128_000),
("gpt-5", 128_000),
("gpt-5-mini", 128_000),
("gpt-5-nano", 128_000),
("gpt-5-pro", 272_000),
("gpt-4.1", 32_768),
("gpt-4.1-mini", 32_768),
("gpt-4.1-nano", 32_768),
("o3", 100_000),
("o4-mini", 100_000),
("o3-mini", 100_000),
("o1", 100_000),
("gpt-4o", 16_384),
("gpt-4o-mini", 16_384),
("deepseek-flash", 393_216),
("deepseek-v4-flash", 393_216),
("deepseek-v4-pro", 393_216),
("gpt-oss-120b", 65_536),
("gpt-oss-20b", 65_536),
("gpt-oss-safeguard-20b", 65_536),
("qwen3.8-27b", 16_384),
("chat-latest", 128_000),
("muse-ember-1.0", 524_288),
("mistral-large-4", 1_000_000),
("mistral-large-4-0", 1_000_000),
("mistral-medium-3-5", 262_144),
("mistral-medium-3", 262_144),
("mistral-medium-latest", 262_144),
("mistral-large-2512", 262_144),
("mistral-large-latest", 1_000_000),
("mistral-small-2603", 262_144),
("mistral-small-latest", 262_144),
("ministral-14b-2512", 262_144),
("ministral-14b-latest", 262_144),
("ministral-8b-2512", 262_144),
("ministral-8b-latest", 262_144),
("ministral-3b-2512", 262_144),
("ministral-3b-latest", 262_144),
("codestral-2508", 131_072),
("codestral-latest", 131_072),
];
const CLAUDE_WINDOW: u64 = 1_000_000;
const GEMINI_INPUT: u64 = 1_048_576;
let context_window: &[(&str, u64)] = &[
("claude-fable-5-2", CLAUDE_WINDOW),
("claude-mythos-5-2", CLAUDE_WINDOW),
("claude-fable-5-1", CLAUDE_WINDOW),
("claude-mythos-5-1", CLAUDE_WINDOW),
("claude-fable-5", CLAUDE_WINDOW),
("claude-mythos-5", CLAUDE_WINDOW),
("claude-opus-5-5", CLAUDE_WINDOW),
("claude-opus-5", CLAUDE_WINDOW),
("claude-sonnet-5-5", CLAUDE_WINDOW),
("claude-sonnet-5", CLAUDE_WINDOW),
("claude-haiku-5-5", CLAUDE_WINDOW),
("claude-opus-4-8", CLAUDE_WINDOW),
("claude-opus-4-7", CLAUDE_WINDOW),
("claude-opus-4-6", CLAUDE_WINDOW),
("claude-sonnet-4-6", CLAUDE_WINDOW),
("claude-opus-4-5", 200_000),
("claude-opus-4-1", 200_000),
("claude-opus-4", 200_000),
("claude-sonnet-4-5", 200_000),
("claude-sonnet-4", 200_000),
("claude-haiku-4-5", 200_000),
("gemini-4-hydrogen", GEMINI_INPUT),
("gemini-4-neon", GEMINI_INPUT),
("gemini-4-carbon", GEMINI_INPUT),
("gemini-4-argon", GEMINI_INPUT),
("gemini-3.8-flash", GEMINI_INPUT),
("gemini-3.7-flash", GEMINI_INPUT),
("gemini-3.6-flash", GEMINI_INPUT),
("gemini-3.5-flash", GEMINI_INPUT),
("gemini-3.5-flash-lite", GEMINI_INPUT),
("gemini-3.1-pro-preview", GEMINI_INPUT),
("gemini-3.1-flash-lite", GEMINI_INPUT),
("gemini-3-flash-preview", GEMINI_INPUT),
("gemini-2.5-pro", GEMINI_INPUT),
("gemini-2.5-flash", GEMINI_INPUT),
("gemini-2.5-flash-lite", GEMINI_INPUT),
("gpt-6-astra", 922_000),
("gpt-6.1-sol", 922_000),
("gpt-6.1-terra", 922_000),
("gpt-6-sol", 922_000),
("gpt-6-luna", 922_000),
("gpt-6-cyber", 922_000),
("gpt-5.6", 922_000),
("gpt-5.6-sol", 922_000),
("gpt-5.6-terra", 922_000),
("gpt-5.6-luna", 922_000),
("gpt-5.6-cyber", 272_000),
("gpt-5.5", 1_050_000),
("gpt-5.5-pro", 1_050_000),
("gpt-5.4", 1_050_000),
("gpt-5.4-pro", 1_050_000),
("gpt-5.3-codex", 272_000),
("gpt-5.2-pro", 400_000),
("gpt-5-pro", 400_000),
("chat-latest", 272_000),
("gpt-5.4-mini", 272_000),
("gpt-5.4-nano", 272_000),
("gpt-5.2", 400_000),
("gpt-5.1", 400_000),
("gpt-5", 272_000),
("gpt-5-mini", 272_000),
("gpt-5-nano", 272_000),
("gpt-4.1", 1_047_576),
("gpt-4.1-mini", 1_047_576),
("gpt-4o", 128_000),
("gpt-4o-mini", 128_000),
("o3", 200_000),
("o4-mini", 200_000),
("deepseek-flash", 1_000_000),
("deepseek-v4-flash", 1_000_000),
("deepseek-v4-pro", 1_000_000),
("gpt-oss-120b", 131_072),
("gpt-oss-20b", 131_072),
("gpt-oss-safeguard-20b", 131_072),
("qwen3.8-27b", 131_072),
("grok-4.7", 500_000),
("grok-4.6", 500_000),
("grok-4.5", 500_000),
("grok-build-latest", 500_000),
("grok-build-0.1", 256_000),
("grok-code-fast-1", 256_000),
("grok-code-fast", 256_000),
("grok-4.3", 1_000_000),
("grok-4.20", 1_000_000),
("grok-4.20-0309-reasoning", 1_000_000),
("grok-4.20-reasoning", 1_000_000),
("grok-4.20-0309-non-reasoning", 1_000_000),
("grok-4.20-non-reasoning", 1_000_000),
("grok-4.20-multi-agent-0309", 1_000_000),
("grok-4.20-multi-agent", 1_000_000),
("mistral-large-4", 1_000_000),
("mistral-large-4-0", 1_000_000),
("mistral-large-latest", 1_000_000),
("mistral-medium-3-5", 256_000),
("mistral-large-2512", 256_000),
("mistral-small-2603", 256_000),
("ministral-14b-2512", 256_000),
("codestral-2508", 128_000),
("muse-spark-1.3", 1_048_576),
("muse-spark-1.2", 1_048_576),
("muse-spark-1.1", 1_048_576),
("muse-wonder-1.0", 1_048_576),
("muse-ember-1.0", 1_048_576),
];
let prices = prices
.into_iter()
.map(|price| match max_output.iter().find(|(model, _)| *model == price.model) {
Some((_, tokens)) => price.with_max_output_tokens(*tokens),
None => price,
})
.map(|price| match context_window.iter().find(|(model, _)| *model == price.model) {
Some((_, tokens)) => price.with_context_window(*tokens),
None => price,
})
.collect();
PricingCatalog {
version: PRICING_EFFECTIVE_DATE.to_string(),
prices,
fees: standard_fees(),
units: standard_unit_prices(),
}
}
fn standard_unit_prices() -> Vec<UnitPrice> {
use PriceVendor::Meta;
vec![
UnitPrice::new(Meta, "muse-image-1.0", UnitRate::new(UsageUnit::Images, 10_000, 1)),
UnitPrice::new(
Meta,
"muse-voice-transcribe-1.0",
UnitRate::new(UsageUnit::AudioMillis, 180_000, 3_600_000).rounded_down_to(1_000),
),
UnitPrice::new(Meta, "sam-3.1", UnitRate::new(UsageUnit::Images, 2_500_000, 1_000)),
UnitPrice::new(
Meta,
"sam-3.1",
UnitRate::new(UsageUnit::Frames, 200_000, 1_000).with_minimum_per_request(50),
),
]
}
fn standard_fees() -> Vec<BuiltinToolFee> {
use PriceVendor::{Anthropic, Google, OpenAI};
vec![
BuiltinToolFee::per_use(Anthropic, "web_search", 0.010),
BuiltinToolFee::per_use(Anthropic, "web_fetch", 0.0),
BuiltinToolFee::per_use(OpenAI, "web_search", 0.010),
BuiltinToolFee::per_use(OpenAI, "file_search", 0.0025),
BuiltinToolFee::per_use(Google, "google_search", 0.014)
.for_models(["gemini-3*", "gemini-4*"]),
BuiltinToolFee::per_response(Google, "google_search", 0.035)
.for_models(["gemini-2.5-pro", "gemini-2.5-flash"]),
BuiltinToolFee::per_response(Google, "google_maps", 0.025)
.for_models(["gemini-2.5-pro", "gemini-2.5-flash"]),
BuiltinToolFee::per_use(Google, "code_execution", 0.0),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn muse_media_is_priced_per_unit() {
let catalog = PricingCatalog::standard();
let images = |count| UsageVector::new().with(UsageUnit::Images, count);
assert_eq!(
catalog.unit_cost_micro_usd(Some("muse"), "muse-image-1.0", &images(1)),
Some(10_000)
);
assert_eq!(
catalog.unit_cost_micro_usd(Some("muse"), "sam-3.1", &images(1_000)),
Some(2_500_000)
);
assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "sam-3.1", &images(1)), Some(2_500));
let frames = |count| UsageVector::new().with(UsageUnit::Frames, count);
let video = |count| catalog.unit_cost_micro_usd(Some("muse"), "sam-3.1", &frames(count));
assert_eq!(video(900), Some(180_000));
assert_eq!(video(12), Some(10_000));
assert_eq!(video(50), Some(10_000));
assert_eq!(video(3_600), Some(720_000));
let audio = |ms| UsageVector::new().with(UsageUnit::AudioMillis, ms);
let transcribe =
|ms| catalog.unit_cost_micro_usd(Some("muse"), "muse-voice-transcribe-1.0", &audio(ms));
assert_eq!(transcribe(90_000), Some(4_500));
assert_eq!(transcribe(3_600_000), Some(180_000));
assert_eq!(transcribe(999), Some(0));
}
#[test]
fn a_unit_price_applies_only_where_the_vendor_bills_it() {
let catalog = PricingCatalog::standard();
let images = UsageVector::new().with(UsageUnit::Images, 1);
assert_eq!(catalog.unit_cost_micro_usd(Some("openai"), "muse-image-1.0", &images), None);
assert_eq!(catalog.unit_cost_micro_usd(None, "muse-image-1.0", &images), Some(10_000));
assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "muse-image-2.0", &images), None);
assert!(catalog.lookup(Some("muse"), "muse-image-1.0").is_none());
assert_eq!(catalog.unit_cost_micro_usd(Some("muse"), "muse-spark-1.3", &images), None);
}
#[test]
fn a_unit_price_replaces_the_same_model_and_unit() {
let catalog = PricingCatalog::new("t")
.with_unit_price(UnitPrice::new(
PriceVendor::Meta,
"m",
UnitRate::new(UsageUnit::Images, 1, 1),
))
.with_unit_price(UnitPrice::new(
PriceVendor::Meta,
"m",
UnitRate::new(UsageUnit::Pages, 5, 1),
))
.with_unit_price(UnitPrice::new(
PriceVendor::Meta,
"m",
UnitRate::new(UsageUnit::Images, 2, 1),
));
assert_eq!(catalog.unit_prices().len(), 2);
let both = UsageVector::new().with(UsageUnit::Images, 3).with(UsageUnit::Pages, 1);
assert_eq!(catalog.unit_cost_micro_usd(None, "m", &both), Some(11));
assert_eq!(catalog.unit_cost_micro_usd(None, "m", &UsageVector::new()), Some(0));
}
fn today() -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 10, 10).unwrap()
}
fn usage(prompt: i32, output: i32) -> UsageMetadata {
UsageMetadata {
prompt_token_count: prompt,
candidates_token_count: output,
total_token_count: prompt + output,
..Default::default()
}
}
fn tool_usage(uses: &[(&str, u32)]) -> UsageMetadata {
UsageMetadata {
builtin_tool_uses: uses
.iter()
.map(|(kind, count)| adk_core::BuiltinToolUse::new(*kind, *count))
.collect(),
..Default::default()
}
}
#[test]
fn builtin_tool_fees_are_added_on_the_vendor_api_only() {
let catalog = PricingCatalog::standard();
let searched = tool_usage(&[("web_search", 3), ("web_fetch", 2), ("code_execution", 1)]);
let cost = |provider: &str, model: &str, usage: &UsageMetadata| {
catalog.cost_usd(Some(provider), model, usage).unwrap()
};
assert!((cost("anthropic", "claude-sonnet-4-6", &searched) - 0.03).abs() < 1e-12);
assert_eq!(cost("bedrock", "claude-sonnet-4-6", &searched), 0.0);
assert!(
(cost("openai", "gpt-5.6-luna", &tool_usage(&[("web_search", 2), ("file_search", 4)]))
- 0.03)
.abs()
< 1e-12
);
let gemini3 =
tool_usage(&[("google_search", 4), ("code_execution", 2), ("google_maps", 1)]);
assert!((cost("gemini", "gemini-3.7-flash", &gemini3) - 0.056).abs() < 1e-12);
let gemini25 = tool_usage(&[("google_search", 4), ("google_maps", 1)]);
assert!((cost("gemini", "gemini-2.5-flash", &gemini25) - 0.06).abs() < 1e-12);
assert!(
catalog
.builtin_tool_fee(Some("gemini"), "gemini-2.5-flash-lite", "google_search")
.is_none()
);
assert!(
catalog
.builtin_tool_fee(Some("anthropic"), "claude-haiku-4-5", "code_execution")
.is_none()
);
}
fn price(provider: &str, model: &str) -> &'static ModelPrice {
PricingCatalog::standard()
.lookup(Some(provider), model)
.unwrap_or_else(|| panic!("{provider}/{model} should be priced"))
}
#[test]
fn context_windows_resolve_by_provider_and_dated_alias() {
let catalog = PricingCatalog::standard();
let window = |provider: &str, model: &str| catalog.context_window(Some(provider), model);
assert_eq!(window("anthropic", "claude-sonnet-5-5"), Some(1_000_000));
assert_eq!(window("bedrock", "us.anthropic.claude-haiku-4-5-20251001-v1:0"), Some(200_000));
assert_eq!(window("gemini", "models/gemini-3.5-flash-lite"), Some(1_048_576));
assert_eq!(window("openai", "gpt-5.6-terra"), Some(922_000));
assert_eq!(window("groq", "openai/gpt-oss-120b"), Some(131_072));
assert_eq!(window("groq", "claude-sonnet-5-5"), None);
assert_eq!(window("anthropic", "claude-fable-5-2"), Some(1_000_000));
assert_eq!(window("anthropic", "claude-opus-4-5-20251101"), Some(200_000));
assert_eq!(window("xai", "grok-code-fast-1"), Some(256_000));
assert_eq!(window("gemini", "gemini-2.5-flash-image"), None);
let recorded =
catalog.prices().iter().filter(|p| p.context_window_tokens.is_some()).count();
assert_eq!(recorded, 103);
}
#[test]
fn gemini_cached_tokens_are_billed_once() {
let usage = UsageMetadata {
cache_read_input_token_count: Some(400_000),
..usage(1_000_000, 200_000)
};
let cost = price("gemini", "gemini-2.5-flash").cost_usd(&usage, today());
assert!((cost - (0.18 + 0.012 + 0.50)).abs() < 1e-9, "{cost}");
}
#[test]
fn gemini_long_context_switches_the_whole_request() {
let price = price("gemini", "models/gemini-2.5-pro");
let short = price.cost_usd(&usage(200_000, 0), today());
let long = price.cost_usd(&usage(200_001, 0), today());
assert!((short - 0.25).abs() < 1e-9, "{short}");
assert!((long - 200_001.0 * 2.50 / 1e6).abs() < 1e-9, "{long}");
}
#[test]
fn gemini_flash_introductory_rates_end_in_2027() {
let price = price("gemini", "gemini-3.7-flash");
let before = price.cost_usd(&usage(1_000_000, 0), today());
let after =
price.cost_usd(&usage(1_000_000, 0), NaiveDate::from_ymd_opt(2027, 1, 1).unwrap());
assert!((before - 0.75).abs() < 1e-9);
assert!((after - 1.50).abs() < 1e-9);
}
#[test]
fn anthropic_cache_writes_split_by_ttl() {
let usage = UsageMetadata {
prompt_token_count: 1_000 + 200_000 + 100_000,
candidates_token_count: 2_000,
cache_read_input_token_count: Some(200_000),
cache_creation_input_token_count: Some(100_000),
provider_usage: Some(serde_json::json!({ "cache_creation_input_tokens_1h": 40_000 })),
..Default::default()
};
let cost = price("anthropic", "claude-sonnet-4-5-20250929").cost_usd(&usage, today());
let expected =
(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)
/ 1e6;
assert!((cost - expected).abs() < 1e-9, "{cost} vs {expected}");
}
#[test]
fn haiku_55_long_prompt_counts_cached_tokens() {
let usage =
UsageMetadata { cache_read_input_token_count: Some(90_000), ..usage(100_001, 0) };
let cost = price("anthropic", "claude-haiku-5-5").cost_usd(&usage, today());
let expected = (10_001.0 * 0.50 + 90_000.0 * 0.05) / 1e6;
assert!((cost - expected).abs() < 1e-12, "{cost}");
}
#[test]
fn openai_long_context_starts_above_272k() {
let gpt_55 = price("openai", "gpt-5.5");
assert_eq!(gpt_55.rates_for(272_000, today()).input, 5.00);
assert_eq!(gpt_55.rates_for(272_001, today()).input, 10.00);
let sol = price("openai", "gpt-6.1-sol");
assert_eq!(
sol.rates_for(272_000, today()),
ModelRates::new(2.00, 10.00).with_cache_read(0.10)
);
assert_eq!(
sol.rates_for(272_001, today()),
ModelRates::new(4.00, 15.00).with_cache_read(0.20)
);
}
#[test]
fn dated_aliases_resolve_and_unlisted_releases_do_not() {
let catalog = PricingCatalog::standard();
for (provider, model, expected) in [
("openai", "gpt-4.1-2025-04-14", "gpt-4.1"),
("openai", "gpt-4o-mini-2024-07-18", "gpt-4o-mini"),
("anthropic", "claude-opus-4-1-20250805", "claude-opus-4-1"),
("anthropic", "claude-3-5-haiku-20241022", "claude-3-5-haiku"),
("bedrock", "us.anthropic.claude-sonnet-4-5-20250929-v1:0", "claude-sonnet-4-5"),
("bedrock", "anthropic.claude-haiku-4-5-20251001-v1:0", "claude-haiku-4-5"),
("openrouter", "anthropic/claude-sonnet-4.5", "claude-sonnet-4-5"),
("openrouter", "google/gemini-3.7-flash", "gemini-3.7-flash"),
("gemini", "models/gemini-2.5-flash-001", "gemini-2.5-flash"),
("anthropic", "claude-opus-5-5-latest", "claude-opus-5-5"),
("groq", "openai/gpt-oss-120b", "gpt-oss-120b"),
("groq", "qwen/qwen3.8-27b", "qwen3.8-27b"),
("xai", "grok-4.5-latest", "grok-4.5"),
("xai", "grok-4.20-0309", "grok-4.20"),
("xai", "grok-code-fast-1-0825", "grok-code-fast-1"),
("openrouter", "x-ai/grok-4.6", "grok-4.6"),
("mistral", "mistral-medium-latest", "mistral-medium-latest"),
("mistral", "codestral-2508", "codestral-2508"),
("mistral", "mistral-large-4", "mistral-large-4"),
("openai", "gpt-6.1-sol", "gpt-6.1-sol"),
("anthropic", "claude-fable-5-2", "claude-fable-5-2"),
("bedrock", "global.anthropic.claude-fable-5-2", "claude-fable-5-2"),
] {
assert_eq!(
catalog.lookup(Some(provider), model).map(|price| price.model.as_str()),
Some(expected),
"{provider}/{model}"
);
}
for (provider, model) in [
("anthropic", "claude-opus-4-9"),
("openai", "gpt-5-turbo"),
("openai", "gpt-image-2"),
("gemini", "gemini-3.1-flash-live-preview"),
("gemini", "gemini-3.8-live"),
("groq", "llama-3.3-70b-versatile"),
("groq", "minimaxai/minimax-m2.7"),
("cerebras", "gpt-oss-120b"),
("xai", "grok-5"),
("mistral", "mistral-medium-2508"),
("together", "gpt-4.1"),
("deepseek", "gpt-4.1"),
("opencode", "claude-sonnet-5"),
] {
assert!(catalog.lookup(Some(provider), model).is_none(), "{provider}/{model}");
}
}
#[test]
fn xai_long_context_starts_at_200k_and_bills_the_whole_request() {
let price = price("xai", "grok-4.6");
let short = price.cost_usd(&usage(199_999, 1_000), today());
let long = price.cost_usd(&usage(200_000, 1_000), today());
assert!((short - (199_999.0 * 2.00 + 1_000.0 * 6.00) / 1e6).abs() < 1e-12, "{short}");
assert!((long - (200_000.0 * 4.00 + 1_000.0 * 12.00) / 1e6).abs() < 1e-12, "{long}");
}
#[test]
fn groq_cached_input_is_billed_at_the_cached_rate() {
let usage =
UsageMetadata { cache_read_input_token_count: Some(500_000), ..usage(1_000_000, 0) };
let cost = price("groq", "openai/gpt-oss-20b").cost_usd(&usage, today());
assert!((cost - (500_000.0 * 0.075 + 500_000.0 * 0.037) / 1e6).abs() < 1e-12, "{cost}");
}
fn text_request(model: &str, text: &str) -> LlmRequest {
LlmRequest::new(model, vec![adk_core::Content::new("user").with_text(text)])
}
#[test]
fn the_cost_bound_covers_the_most_expensive_usage_the_request_allows() {
let catalog = PricingCatalog::standard();
let request = text_request("claude-sonnet-4-5", &"word ".repeat(10_000));
let prompt = request_input_token_bound(&request).unwrap();
let bound = catalog
.max_cost_micro_usd(Some("anthropic"), "claude-sonnet-4-5", &request, Some(4_096))
.unwrap();
let worst = UsageMetadata {
prompt_token_count: prompt as i32,
candidates_token_count: 4_096,
cache_creation_input_token_count: Some(prompt as i32),
provider_usage: Some(serde_json::json!({ "cache_creation_input_tokens_1h": prompt })),
..Default::default()
};
let cost = catalog.cost_usd(Some("anthropic"), "claude-sonnet-4-5", &worst).unwrap();
assert!(adk_core::usd_to_micro_usd(cost).unwrap() <= bound, "{cost} vs {bound}");
}
#[test]
fn a_prompt_bound_past_the_long_context_threshold_uses_long_rates() {
let catalog = PricingCatalog::standard();
let request = text_request("gemini-2.5-pro", &"x".repeat(300_000));
let bound = catalog
.max_cost_micro_usd(Some("gemini"), "gemini-2.5-pro", &request, Some(0))
.unwrap();
let prompt = request_input_token_bound(&request).unwrap() as f64;
assert_eq!(bound, (prompt * 2.50).ceil() as u64 + 1);
}
#[test]
fn requests_without_an_output_cap_use_the_model_limit_or_stay_unbounded() {
let catalog = PricingCatalog::standard();
let request = text_request("gpt-4.1", "hi");
let uncapped = catalog.max_cost_micro_usd(Some("openai"), "gpt-4.1", &request, None);
let capped = catalog.max_cost_micro_usd(Some("openai"), "gpt-4.1", &request, Some(32_768));
assert_eq!(uncapped, capped);
assert_eq!(catalog.max_cost_micro_usd(Some("xai"), "grok-4.6", &request, None), None);
assert!(catalog.max_cost_micro_usd(Some("xai"), "grok-4.6", &request, Some(100)).is_some());
assert_eq!(
catalog.max_cost_micro_usd(Some("together"), "gpt-4.1", &request, Some(1)),
None
);
assert_eq!(catalog.max_cost_micro_usd(Some("ollama"), "qwen3.5", &request, None), Some(0));
}
#[test]
fn built_in_tool_fees_are_bounded_by_max_uses_or_left_unbounded() {
let catalog = PricingCatalog::standard();
let with_tool = |model: &str, tool: serde_json::Value| {
let mut request = text_request(model, "search the web");
request.tools.insert("web_search".to_string(), tool);
request
};
let plain = catalog
.max_cost_micro_usd(
Some("anthropic"),
"claude-sonnet-4-6",
&text_request("claude-sonnet-4-6", "search the web"),
Some(1_000),
)
.unwrap();
let capped = with_tool(
"claude-sonnet-4-6",
serde_json::json!({ "x-adk-anthropic-tool": { "type": "web_search_20250305", "max_uses": 3 } }),
);
let bound = catalog.max_cost_micro_usd(
Some("anthropic"),
"claude-sonnet-4-6",
&capped,
Some(1_000),
);
assert!(bound.unwrap() >= plain + 30_000, "{bound:?} vs {plain}");
assert!(
catalog
.max_cost_micro_usd(Some("bedrock"), "claude-sonnet-4-6", &capped, Some(1_000))
.unwrap()
< plain + 30_000
);
let uncapped = with_tool(
"claude-sonnet-4-6",
serde_json::json!({ "x-adk-anthropic-tool": { "type": "web_search_20250305" } }),
);
assert_eq!(
catalog.max_cost_micro_usd(
Some("anthropic"),
"claude-sonnet-4-6",
&uncapped,
Some(1_000)
),
None
);
let grounded = with_tool(
"gemini-2.5-flash",
serde_json::json!({ "x-adk-gemini-tool": { "googleSearch": {} } }),
);
let bound = catalog
.max_cost_micro_usd(Some("gemini"), "gemini-2.5-flash", &grounded, Some(0))
.unwrap();
let tokens = request_input_token_bound(&grounded).unwrap() as f64;
assert_eq!(bound, (tokens * 0.30 + 35_000.0 + 25_000.0).ceil() as u64 + 1);
}
#[test]
fn a_request_referencing_a_file_uri_cannot_be_bounded() {
let mut request = text_request("gpt-4.1", "describe");
request.contents[0].parts.push(Part::FileData {
mime_type: "video/mp4".to_string(),
file_uri: "gs://bucket/video.mp4".to_string(),
annotations: None,
});
assert_eq!(request_input_token_bound(&request), None);
let mut inline = text_request("gpt-4.1", "");
inline.contents[0].parts.push(Part::InlineData {
mime_type: "image/png".to_string(),
data: vec![0; 10],
uri: None,
annotations: None,
});
assert_eq!(
request_input_token_bound(&inline),
Some(REQUEST_OVERHEAD_TOKENS + 16 + MEDIA_PART_MIN_TOKENS)
);
}
#[test]
fn gemini_reports_37_flash_as_38_flash_and_both_are_priced() {
let catalog = PricingCatalog::standard();
let usage = usage(1_000_000, 100_000);
for model in ["gemini-3.8-flash", "gemini-3.7-flash", "models/gemini-3.8-flash"] {
let cost = price("gemini", model).cost_usd(&usage, today());
assert!((cost - (0.75 + 0.375)).abs() < 1e-9, "{model}: {cost}");
}
assert_eq!(price("gemini", "gemini-3.8-flash").max_output_tokens, Some(65_536));
let after = price("gemini", "gemini-3.8-flash")
.cost_usd(&usage, NaiveDate::from_ymd_opt(2027, 1, 1).unwrap());
assert!((after - (1.50 + 0.75)).abs() < 1e-9, "{after}");
assert!(
catalog
.cost_usd(Some("gemini"), "gemini-3.1-pro-preview-customtools", &usage)
.is_some()
);
}
#[test]
fn deepseek_bills_peak_rates_in_peak_hours_and_half_off_peak() {
use chrono::TimeZone;
let usage = UsageMetadata {
cache_read_input_token_count: Some(500_000),
..usage(1_000_000, 100_000)
};
let flash = price("deepseek", "deepseek-flash");
let peak = chrono::Utc.with_ymd_and_hms(2026, 10, 12, 7, 0, 0).unwrap();
let midday = chrono::Utc.with_ymd_and_hms(2026, 10, 12, 12, 0, 0).unwrap();
let sunday = chrono::Utc.with_ymd_and_hms(2026, 10, 11, 7, 0, 0).unwrap();
let expected_peak = 0.15 + 0.003 + 0.12;
assert!((flash.cost_usd_at(&usage, peak) - expected_peak).abs() < 1e-9);
assert!((flash.cost_usd_at(&usage, midday) - expected_peak / 2.0).abs() < 1e-9);
assert!((flash.cost_usd_at(&usage, sunday) - expected_peak / 2.0).abs() < 1e-9);
let pro = price("deepseek", "deepseek-v4-pro");
assert!((pro.cost_usd_at(&usage, peak) - (0.66 + 0.022 + 0.396)).abs() < 1e-9);
assert_eq!(price("deepseek", "deepseek-v4-flash").rates, flash.rates);
assert!(PricingCatalog::standard().lookup(Some("deepseek"), "deepseek-chat").is_none());
let request = text_request("deepseek-flash", "hi");
let bound = PricingCatalog::standard()
.max_cost_micro_usd(Some("deepseek"), "deepseek-flash", &request, None)
.unwrap();
let prompt = request_input_token_bound(&request).unwrap() as f64;
assert_eq!(bound, (prompt * 0.30 + 393_216.0 * 1.20).ceil() as u64 + 1);
}
#[test]
fn local_ollama_is_free_and_cloud_ollama_is_unpriced() {
let catalog = PricingCatalog::standard();
assert_eq!(catalog.cost_usd(Some("ollama"), "qwen3.5", &usage(10, 10)), Some(0.0));
assert_eq!(catalog.cost_usd(Some("ollama"), "gpt-oss:120b-cloud", &usage(10, 10)), None);
}
#[test]
fn negative_counts_never_produce_negative_cost() {
let usage = UsageMetadata { cache_read_input_token_count: Some(5_000), ..usage(-10, -10) };
assert_eq!(price("openai", "gpt-4.1").cost_usd(&usage, today()), 5_000.0 * 0.5 / 1e6);
}
#[cfg(feature = "gemini")]
#[test]
fn gemini_rates_match_adk_gemini_pricing() {
for price in PricingCatalog::standard().prices() {
if price.vendor != PriceVendor::Google {
continue;
}
let Some(vendor) = adk_gemini::pricing::GeminiPricing::for_model_id(&price.model)
else {
continue;
};
let same = |a: f64, b: f64| (a - b).abs() < 1e-9;
let matches = |rates: ModelRates| {
same(rates.input, vendor.input)
&& same(rates.output, vendor.output)
&& (vendor.cache_input <= 0.0 || same(rates.cache_read, vendor.cache_input))
};
assert!(
matches(price.rates) || price.change.is_some_and(|change| matches(change.rates)),
"{}: adk-gemini prices it at {vendor:?}",
price.model
);
match price.long_context {
Some(tier) => assert_eq!(tier.rates.input, vendor.input_long, "{}", price.model),
None => assert_eq!(vendor.input_long, vendor.input, "{}", price.model),
}
}
}
#[cfg(feature = "openai")]
#[test]
fn openai_rates_match_openai_pricing() {
for price in PricingCatalog::standard().prices() {
if price.vendor != PriceVendor::OpenAI {
continue;
}
let vendor = crate::openai::pricing::lookup_pricing(&price.model)
.unwrap_or_else(|| panic!("{} is missing from openai::pricing", price.model));
assert_eq!(price.rates.input, vendor.input, "{}", price.model);
assert_eq!(price.rates.output, vendor.output, "{}", price.model);
assert_eq!(price.rates.cache_read, vendor.cached_input, "{}", price.model);
}
}
#[cfg(feature = "anthropic")]
#[test]
fn anthropic_rates_match_adk_anthropic_pricing() {
for price in PricingCatalog::standard().prices() {
if price.vendor != PriceVendor::Anthropic {
continue;
}
let vendor = adk_anthropic::pricing::ModelPricing::for_model_id(&price.model)
.unwrap_or_else(|| {
panic!("{} is missing from adk_anthropic::pricing", price.model)
});
assert_eq!(price.rates.input, vendor.input, "{}", price.model);
assert_eq!(price.rates.output, vendor.output, "{}", price.model);
assert_eq!(price.rates.cache_read, vendor.cache_read, "{}", price.model);
assert_eq!(price.rates.cache_write_5m, vendor.cache_write_5m, "{}", price.model);
assert_eq!(price.rates.cache_write_1h, vendor.cache_write_1h, "{}", price.model);
}
}
}