diff --git a/litellm-rust/Cargo.lock b/litellm-rust/Cargo.lock index e476bfd4072..b03ad6b9e5a 100644 --- a/litellm-rust/Cargo.lock +++ b/litellm-rust/Cargo.lock @@ -3754,6 +3754,8 @@ dependencies = [ "schemars 1.2.2", "serde", "serde_json", + "strum", + "thiserror 2.0.19", "time", ] diff --git a/litellm-rust/crates/cost/Cargo.toml b/litellm-rust/crates/cost/Cargo.toml index 66cf0602337..7e128d8d944 100644 --- a/litellm-rust/crates/cost/Cargo.toml +++ b/litellm-rust/crates/cost/Cargo.toml @@ -12,6 +12,8 @@ schema = ["serde", "dep:schemars"] [dependencies] jiff = { version = "0.2.37", default-features = false, features = ["std", "tzdb-bundle-always"] } time.workspace = true +thiserror.workspace = true +strum.workspace = true schemars = { workspace = true, optional = true } serde = { workspace = true, optional = true } diff --git a/litellm-rust/crates/cost/src/calculate.rs b/litellm-rust/crates/cost/src/calculate.rs index ab2dacd6f3b..95846a865d0 100644 --- a/litellm-rust/crates/cost/src/calculate.rs +++ b/litellm-rust/crates/cost/src/calculate.rs @@ -2,7 +2,8 @@ use std::collections::BTreeMap; use time::OffsetDateTime; -use crate::money::{UnitPrice, Usd}; +use crate::PriceEvaluationError; +use crate::money::{ScaleFactor, UnitPrice, Usd}; use crate::price::{Band, Channel, InputUnit, Meter, OutputUnit, Prices, ServiceTier}; use crate::selection::SelectionPolicy; @@ -45,6 +46,89 @@ pub struct Line { pub fallback_from: Option, } +#[derive(Clone, Debug, PartialEq)] +pub struct SelectedRate { + pub requested_meter: Meter, + pub resolved: Option<(Meter, UnitPrice)>, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PriceEvaluation { + pub pricing: Priced, + pub rates: Vec, +} + +pub fn calculate_with_rates( + prices: &Prices, + usage: &Usage, + when: &When, + policy: SelectionPolicy<'_>, + project: &[Meter], + factors: &[ScaleFactor], +) -> Result { + if project.iter().any(|meter| !meter.is_token()) { + return Err(PriceEvaluationError::NonTokenProjection); + } + let factor = ScaleFactor::combine(factors).ok_or(PriceEvaluationError::NonFiniteValue)?; + let band = prices.channel_band( + when.channel, + when.tier, + usage.prompt_tokens, + usage.inclusive_threshold, + ); + let rates = project + .iter() + .map(|meter| { + let resolved = policy + .resolve(prices, meter, band, usage, when) + .map(|(source, rate)| { + factor + .price(rate) + .map(|rate| (source, rate)) + .ok_or(PriceEvaluationError::NonFiniteValue) + }) + .transpose()?; + Ok(SelectedRate { + requested_meter: meter.clone(), + resolved, + }) + }) + .collect::>()?; + let pricing = match calculate_with_policy(prices, usage, when, policy) { + Priced::Known(breakdown) => Priced::Known(scale_breakdown(breakdown, factor)?), + Priced::Unpriced { missing, partial } => Priced::Unpriced { + missing, + partial: scale_breakdown(partial, factor)?, + }, + }; + Ok(PriceEvaluation { pricing, rates }) +} + +fn scale_breakdown( + breakdown: Breakdown, + factor: ScaleFactor, +) -> Result { + let total = factor + .amount(breakdown.total) + .ok_or(PriceEvaluationError::NonFiniteValue)?; + let lines = breakdown + .lines + .into_iter() + .map(|line| { + Ok(Line { + unit_price: factor + .price(line.unit_price) + .ok_or(PriceEvaluationError::NonFiniteValue)?, + amount: factor + .amount(line.amount) + .ok_or(PriceEvaluationError::NonFiniteValue)?, + ..line + }) + }) + .collect::>()?; + Ok(Breakdown { total, lines }) +} + impl Breakdown { pub fn input(&self) -> Usd { self.lines @@ -229,6 +313,136 @@ mod tests { const INPUT: Meter = Meter::TEXT_INPUT; const OUTPUT: Meter = Meter::Output(OutputUnit::Token(TokenKind::Text)); + + #[rstest] + #[case::unused_output(Some(2.0), 1.0)] + #[case::scaled_unused_output(Some(2.0), 6.0)] + #[case::missing_output(None, 1.0)] + #[case::missing_output_zero_factor(None, 0.0)] + #[case::explicit_zero_output(Some(0.0), 1.0)] + #[case::known_output_zero_factor(Some(2.0), 0.0)] + fn unused_projection_preserves_actual_pricing( + when: When, + #[case] output: Option, + #[case] factor: f64, + ) { + let prices = prices( + [(INPUT, 1.0)] + .into_iter() + .chain(output.map(|rate| (OUTPUT, rate))), + ); + let usage = Usage { + quantities: BTreeMap::from([(INPUT, 10)]), + ..Usage::default() + }; + let evaluated = calculate_with_rates( + &prices, + &usage, + &when, + SelectionPolicy::Generic, + &[OUTPUT], + &[ScaleFactor::new(factor).unwrap()], + ) + .unwrap(); + assert_eq!( + evaluated.rates, + vec![SelectedRate { + requested_meter: OUTPUT, + resolved: output.map(|rate| (OUTPUT, UnitPrice::new(rate * factor).unwrap())) + }] + ); + assert_eq!( + evaluated.pricing, + Priced::Known(Breakdown { + total: Usd::new(10.0 * factor).unwrap(), + lines: vec![Line { + meter: INPUT, + quantity: 10, + unit_price: UnitPrice::new(factor).unwrap(), + amount: Usd::new(10.0 * factor).unwrap(), + fallback_from: None + }], + }) + ); + } + + #[rstest] + #[case::scaled_partial(6.0)] + #[case::free_partial_still_unknown(0.0)] + fn projection_scales_partial_without_inventing_missing_rates(when: When, #[case] factor: f64) { + let prices = prices([(INPUT, 1.0)]); + let usage = Usage { + quantities: BTreeMap::from([(INPUT, 10), (OUTPUT, 5)]), + ..Usage::default() + }; + let evaluated = calculate_with_rates( + &prices, + &usage, + &when, + SelectionPolicy::Generic, + &[OUTPUT], + &[ScaleFactor::new(factor).unwrap()], + ) + .unwrap(); + assert_eq!( + evaluated.rates, + vec![SelectedRate { + requested_meter: OUTPUT, + resolved: None + }] + ); + let Priced::Unpriced { missing, partial } = evaluated.pricing else { + panic!("missing output must remain unpriced") + }; + assert_eq!(missing, vec![OUTPUT]); + assert_eq!(partial.total.get(), 10.0 * factor); + assert_eq!(partial.lines.len(), 1); + assert_eq!(partial.lines[0].quantity, 10); + assert_eq!(partial.lines[0].unit_price.get(), factor); + } + + #[rstest] + #[case::projected_rate_overflow(0, true)] + #[case::actual_rate_overflow(1, false)] + #[case::actual_amount_overflow(2, false)] + fn adjusted_evaluation_rejects_nonfinite_money( + when: When, + #[case] quantity: u64, + #[case] project: bool, + ) { + let prices = prices([(INPUT, f64::MAX)]); + let usage = Usage { + quantities: BTreeMap::from([(INPUT, quantity)]), + ..Usage::default() + }; + let projection = if project { vec![INPUT] } else { Vec::new() }; + assert_eq!( + calculate_with_rates( + &prices, + &usage, + &when, + SelectionPolicy::Generic, + &projection, + &[ScaleFactor::new(2.0).unwrap()] + ), + Err(PriceEvaluationError::NonFiniteValue) + ); + } + + #[rstest] + fn projection_rejects_non_token_meters(when: When) { + assert_eq!( + calculate_with_rates( + &prices([]), + &Usage::default(), + &when, + SelectionPolicy::Generic, + &[Meter::Input(InputUnit::Image)], + &[] + ), + Err(PriceEvaluationError::NonTokenProjection) + ); + } const READ: Meter = Meter::CacheRead { kind: TokenKind::Text, mode: CacheReadMode::Implicit, diff --git a/litellm-rust/crates/cost/src/error.rs b/litellm-rust/crates/cost/src/error.rs index 80fa89019ca..a496923f351 100644 --- a/litellm-rust/crates/cost/src/error.rs +++ b/litellm-rust/crates/cost/src/error.rs @@ -1,5 +1,13 @@ use std::fmt; +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error, strum::VariantArray)] +pub enum PriceEvaluationError { + #[error("only token meters can be projected")] + NonTokenProjection, + #[error("pricing produced a non-finite amount or rate")] + NonFiniteValue, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct InvalidUtcWindow; diff --git a/litellm-rust/crates/cost/src/money.rs b/litellm-rust/crates/cost/src/money.rs index 23f8d9925eb..7facfec8b00 100644 --- a/litellm-rust/crates/cost/src/money.rs +++ b/litellm-rust/crates/cost/src/money.rs @@ -10,6 +10,32 @@ pub struct Usd(f64); #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub struct Multiplier(f64); +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScaleFactor(f64); + +impl ScaleFactor { + pub fn new(factor: f64) -> Option { + (factor.is_finite() && factor >= 0.0).then_some(Self(factor)) + } + + pub fn combine(factors: &[Self]) -> Option { + if factors.iter().any(|factor| factor.0 == 0.0) { + return Some(Self(0.0)); + } + factors + .iter() + .try_fold(Self(1.0), |factor, next| Self::new(factor.0 * next.0)) + } + + pub fn price(self, price: UnitPrice) -> Option { + UnitPrice::new(price.get() * self.0) + } + + pub fn amount(self, amount: Usd) -> Option { + Usd::new(amount.get() * self.0) + } +} + impl UnitPrice { pub fn new(usd_per_unit: f64) -> Option { (usd_per_unit.is_finite() && usd_per_unit >= 0.0).then_some(Self(usd_per_unit)) @@ -185,6 +211,41 @@ mod tests { use super::*; + #[rstest] + #[case::uplift(6.0, true)] + #[case::neutral(1.0, true)] + #[case::discount(0.5, true)] + #[case::zero(0.0, true)] + #[case::negative(-1.0, false)] + #[case::nan(f64::NAN, false)] + #[case::infinite(f64::INFINITY, false)] + fn selected_factor_accepts_only_finite_non_negative_values( + #[case] value: f64, + #[case] accepted: bool, + ) { + assert_eq!(ScaleFactor::new(value).is_some(), accepted); + } + + #[rstest] + #[case::identity(vec![], Some(1.0))] + #[case::product(vec![2.0, 3.0], Some(6.0))] + #[case::discount(vec![2.0, 0.25], Some(0.5))] + #[case::overflow(vec![f64::MAX, 2.0], None)] + #[case::zero_last(vec![f64::MAX, 2.0, 0.0], Some(0.0))] + #[case::zero_first(vec![0.0, f64::MAX, 2.0], Some(0.0))] + fn selected_factors_combine_once(#[case] factors: Vec, #[case] expected: Option) { + let factors: Vec<_> = factors + .into_iter() + .map(|factor| ScaleFactor::new(factor).unwrap()) + .collect(); + assert_eq!( + ScaleFactor::combine(&factors) + .and_then(|factor| factor.price(UnitPrice::new(1.0).unwrap())) + .map(UnitPrice::get), + expected + ); + } + #[rstest] #[case::price(0.5)] #[case::free(0.0)] diff --git a/litellm-rust/crates/cost/src/price.rs b/litellm-rust/crates/cost/src/price.rs index 505cdc4796f..330abf23d27 100644 --- a/litellm-rust/crates/cost/src/price.rs +++ b/litellm-rust/crates/cost/src/price.rs @@ -48,10 +48,17 @@ pub struct Price { #[derive(Clone, Debug, Default, PartialEq)] pub struct Prices { - rates: BTreeMap, + rates: BTreeMap<(Price, PriceSource), UnitPrice>, off_peak: Option, } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub enum PriceSource { + #[default] + Flat, + TokenTier(u64), +} + #[derive(Clone, Debug, PartialEq)] pub struct OffPeak { schedule: Schedule, @@ -101,21 +108,44 @@ impl Price { impl Prices { pub fn new(rates: BTreeMap, off_peak: Option) -> Self { + Self::from_sources( + rates + .into_iter() + .map(|(price, rate)| ((price, PriceSource::Flat), rate)) + .collect(), + off_peak, + ) + } + + pub fn from_sources( + rates: BTreeMap<(Price, PriceSource), UnitPrice>, + off_peak: Option, + ) -> Self { Self { rates, off_peak } } pub fn get(&self, price: &Price) -> Option { - self.rates.get(price).copied() + self.get_from(price, PriceSource::Flat) + } + + pub fn get_from(&self, price: &Price, source: PriceSource) -> Option { + self.rates.get(&(price.clone(), source)).copied() } pub fn iter(&self) -> impl Iterator { - self.rates.iter().map(|(price, rate)| (price, *rate)) + self.rates.iter().filter_map(|((price, source), rate)| { + (*source == PriceSource::Flat).then_some((price, *rate)) + }) } pub fn off_peak(&self) -> Option<&OffPeak> { self.off_peak.as_ref() } + pub fn has_token_prices(&self) -> bool { + self.rates.keys().any(|(price, _)| price.meter.is_token()) || self.off_peak.is_some() + } + /// The online prompt band a request falls in. Every token meter's `_above_` prices count, /// and the highest band the prompt passes wins. pub fn band(&self, tier: ServiceTier, prompt_tokens: u64, inclusive: bool) -> Band { @@ -129,8 +159,39 @@ impl Prices { prompt_tokens: u64, inclusive: bool, ) -> Band { - self.rates - .keys() + Self::find_band( + self.iter().map(|(price, _)| price), + channel, + tier, + prompt_tokens, + inclusive, + ) + } + + pub(crate) fn all_source_band( + &self, + channel: Channel, + tier: ServiceTier, + prompt_tokens: u64, + inclusive: bool, + ) -> Band { + Self::find_band( + self.rates.keys().map(|(price, _)| price), + channel, + tier, + prompt_tokens, + inclusive, + ) + } + + fn find_band<'a>( + prices: impl Iterator, + channel: Channel, + tier: ServiceTier, + prompt_tokens: u64, + inclusive: bool, + ) -> Band { + prices .filter(|price| { price.channel == channel && price.meter.sets_prompt_band() @@ -247,6 +308,93 @@ mod tests { ttl: CacheTtl::OneHour, }; + #[rstest] + fn source_qualified_rates_do_not_enter_generic_lookup_or_bands() { + let flat = Price::online(INPUT, When::default()); + let first_tier = Price::online(OUTPUT, When::default()); + let last_tier = Price::online( + OUTPUT, + When { + band: Band::over_prompt_tokens(100), + ..Default::default() + }, + ); + let prices = Prices::from_sources( + [ + ( + (flat.clone(), PriceSource::Flat), + UnitPrice::new(1.0).unwrap(), + ), + ( + (flat.clone(), PriceSource::TokenTier(0)), + UnitPrice::new(3.0).unwrap(), + ), + ( + (first_tier.clone(), PriceSource::TokenTier(0)), + UnitPrice::new(4.0).unwrap(), + ), + ( + (last_tier, PriceSource::TokenTier(100)), + UnitPrice::new(5.0).unwrap(), + ), + ] + .into(), + None, + ); + assert_eq!(prices.get(&flat), UnitPrice::new(1.0)); + assert_eq!( + prices.get_from(&flat, PriceSource::TokenTier(0)), + UnitPrice::new(3.0) + ); + assert_eq!( + prices.get_from(&first_tier, PriceSource::TokenTier(0)), + UnitPrice::new(4.0) + ); + assert_eq!(prices.get(&first_tier), None); + assert_eq!( + prices.rate(&OUTPUT, ServiceTier::Standard, Band::Base), + None + ); + assert_eq!(prices.band(ServiceTier::Standard, 101, true), Band::Base); + assert_eq!( + prices.iter().collect::>(), + vec![(&flat, UnitPrice::new(1.0).unwrap())] + ); + assert!(prices.has_token_prices()); + } + + #[rstest] + #[case::input(INPUT, true)] + #[case::output(OUTPUT, true)] + #[case::read(CACHE_READ, true)] + #[case::hour_write(CACHE_WRITE_HOUR, true)] + #[case::reasoning(Meter::Output(OutputUnit::ReasoningToken), true)] + #[case::audio(Meter::Input(InputUnit::Token(TokenKind::Audio)), true)] + #[case::image_token(Meter::Output(OutputUnit::Token(TokenKind::Image)), true)] + #[case::video_token(Meter::Output(OutputUnit::Token(TokenKind::Video)), true)] + #[case::image(Meter::Input(InputUnit::Image), false)] + #[case::characters(Meter::Output(OutputUnit::Character), false)] + #[case::query(Meter::Input(InputUnit::Query { over_results: None }), false)] + #[case::wall_clock(Meter::WallClockSecond, false)] + fn token_presence_is_explicit_and_independent_of_request( + #[case] meter: Meter, + #[case] expected: bool, + #[values(PriceSource::Flat, PriceSource::TokenTier(0))] source: PriceSource, + #[values(Channel::Online, Channel::Batch, Channel::Decisions)] channel: Channel, + ) { + let key = Price { + meter, + channel, + when: When { + tier: ServiceTier::Flex, + band: Band::over_prompt_tokens(100), + }, + }; + let prices = + Prices::from_sources([((key, source), UnitPrice::new(0.0).unwrap())].into(), None); + assert_eq!(prices.has_token_prices(), expected); + } + fn over(tokens: u64) -> Band { Band::over_prompt_tokens(tokens) } diff --git a/litellm-rust/crates/cost/src/price/meter.rs b/litellm-rust/crates/cost/src/price/meter.rs index 7cdcff10c8a..e34b0638f45 100644 --- a/litellm-rust/crates/cost/src/price/meter.rs +++ b/litellm-rust/crates/cost/src/price/meter.rs @@ -91,6 +91,16 @@ pub struct ImageSize(Box); pub struct Resolution(Box); impl Meter { + pub fn is_token(&self) -> bool { + matches!( + self, + Self::Input(InputUnit::Token(_)) + | Self::Output(OutputUnit::Token(_) | OutputUnit::ReasoningToken) + | Self::CacheRead { .. } + | Self::CacheWrite { .. } + ) + } + pub(crate) const TEXT_INPUT: Self = Self::Input(InputUnit::Token(TokenKind::Text)); pub(crate) fn sets_prompt_band(&self) -> bool { diff --git a/litellm-rust/crates/cost/src/selection.rs b/litellm-rust/crates/cost/src/selection.rs index 1d12b156ec2..fef280fc930 100644 --- a/litellm-rust/crates/cost/src/selection.rs +++ b/litellm-rust/crates/cost/src/selection.rs @@ -2,7 +2,10 @@ use std::collections::BTreeSet; use crate::calculate::{Usage, When, resolve}; use crate::money::UnitPrice; -use crate::price::{Band, Channel, Meter, OutputUnit, Price, Prices, ServiceTier, TokenKind}; +use crate::price::{ + Band, CacheReadMode, CacheTtl, Channel, InputUnit, Meter, OutputUnit, Price, PriceSource, + Prices, ServiceTier, TokenKind, +}; #[derive(Clone, Copy, Debug, Default)] pub enum SelectionPolicy<'a> { @@ -48,13 +51,13 @@ impl SelectionPolicy<'_> { if let Some(rate) = off_peak { return Some((meter.clone(), rate)); } - if let Some(tier) = sources.priced_tier(usage.prompt_tokens) { - if let Some(rate) = tier.rate(prices, meter) { - return Some((meter.clone(), rate)); - } - if let Some(rate) = tier.rate(prices, &output) { - return Some((output, rate)); - } + if let Some(tier) = sources.priced_tier(usage.prompt_tokens) + && (tier.meters.contains(meter) || tier.meters.contains(&output)) + { + return tier + .rate(prices, meter) + .map(|rate| (meter.clone(), rate)) + .or_else(|| tier.rate(prices, &output).map(|rate| (output, rate))); } if let Some(rate) = sources.flat_rate(prices, meter, when.tier) { return Some((meter.clone(), rate)); @@ -62,22 +65,66 @@ impl SelectionPolicy<'_> { if when.tier != ServiceTier::Standard && sources.flat_rate(prices, &output, when.tier).is_some() { - return resolve(prices, &output, band, usage, when); + return self.resolve(prices, &output, band, usage, when); } sources .flat_rate(prices, meter, ServiceTier::Standard) .map(|rate| (meter.clone(), rate)) - .or_else(|| resolve(prices, &output, band, usage, when)) + .or_else(|| self.resolve(prices, &output, band, usage, when)) } Meter::Output(OutputUnit::Token(kind)) if *kind != TokenKind::Text => sources .flat_rate(prices, meter, ServiceTier::Standard) .map(|rate| (meter.clone(), rate)) - .or_else(|| resolve(prices, &output, band, usage, when)), - _ => resolve(prices, meter, band, usage, when), + .or_else(|| self.resolve(prices, &output, band, usage, when)), + Meter::Input(InputUnit::Token(_)) + | Meter::Output(OutputUnit::Token(_)) + | Meter::CacheRead { .. } + | Meter::CacheWrite { .. } => { + if let Some(tier) = sources.priced_tier(usage.prompt_tokens) + && matches!( + meter, + Meter::Input(InputUnit::Token(TokenKind::Text)) + | Meter::Output(OutputUnit::Token(TokenKind::Text)) + | Meter::CacheRead { + kind: TokenKind::Text, + .. + } + | Meter::CacheWrite { + kind: TokenKind::Text, + .. + } + ) + { + return tier.resolve(prices, meter, when); + } + overlay(prices, meter, when) + .or_else(|| prices.direct_rate(meter, when.channel, when.tier, band)) + .map(|rate| (meter.clone(), rate)) + .or_else(|| self.resolve(prices, &meter.fallback()?, band, usage, when)) + } + _ => resolve( + prices, + meter, + prices.all_source_band( + when.channel, + when.tier, + usage.prompt_tokens, + usage.inclusive_threshold, + ), + usage, + when, + ), } } } +fn overlay(prices: &Prices, meter: &Meter, when: &When) -> Option { + prices + .off_peak() + .filter(|off_peak| off_peak.schedule().contains(when.at)) + .and_then(|off_peak| off_peak.rates().get(meter)) +} + impl TokenPriceSources { fn flat_rate(&self, prices: &Prices, meter: &Meter, tier: ServiceTier) -> Option { let key = Price::online( @@ -104,17 +151,53 @@ impl TokenPriceSources { } impl TokenTier { + fn resolve(&self, prices: &Prices, meter: &Meter, when: &When) -> Option<(Meter, UnitPrice)> { + if matches!( + meter, + Meter::CacheWrite { + ttl: CacheTtl::OneHour | CacheTtl::TwelveHours, + .. + } + ) { + return self + .rate(prices, meter) + .map(|rate| (meter.clone(), rate)) + .or_else(|| self.resolve(prices, &meter.fallback()?, when)); + } + if let Some(rate) = overlay(prices, meter, when).or_else(|| self.rate(prices, meter)) { + return Some((meter.clone(), rate)); + } + match meter { + Meter::Output(OutputUnit::Token(TokenKind::Text)) if !self.meters.contains(meter) => { + prices + .get(&Price::online(meter.clone(), Default::default())) + .map(|rate| (meter.clone(), rate)) + } + Meter::CacheRead { + mode: CacheReadMode::Explicit, + .. + } => self.resolve(prices, &meter.fallback()?, when), + Meter::CacheRead { .. } | Meter::CacheWrite { .. } => self + .rate(prices, &Meter::TEXT_INPUT) + .map(|rate| (Meter::TEXT_INPUT, rate)), + _ => None, + } + } + fn rate(&self, prices: &Prices, meter: &Meter) -> Option { self.meters .contains(meter) .then(|| { - prices.get(&Price::online( - meter.clone(), - crate::price::When { - band: Band::over_prompt_tokens(self.range[0]), - ..Default::default() - }, - )) + prices.get_from( + &Price::online( + meter.clone(), + crate::price::When { + band: Band::over_prompt_tokens(self.range[0]), + ..Default::default() + }, + ), + PriceSource::TokenTier(self.range[0]), + ) }) .flatten() } @@ -132,6 +215,132 @@ mod tests { const OUTPUT: Meter = Meter::Output(OutputUnit::Token(TokenKind::Text)); const REASONING: Meter = Meter::Output(OutputUnit::ReasoningToken); + const INPUT: Meter = Meter::TEXT_INPUT; + const READ: Meter = Meter::CacheRead { + kind: TokenKind::Text, + mode: CacheReadMode::Implicit, + }; + const EXPLICIT: Meter = Meter::CacheRead { + kind: TokenKind::Text, + mode: CacheReadMode::Explicit, + }; + const WRITE: Meter = Meter::CacheWrite { + kind: TokenKind::Text, + ttl: CacheTtl::Default, + }; + const HOUR: Meter = Meter::CacheWrite { + kind: TokenKind::Text, + ttl: CacheTtl::OneHour, + }; + const TWELVE: Meter = Meter::CacheWrite { + kind: TokenKind::Text, + ttl: CacheTtl::TwelveHours, + }; + + #[fixture] + fn tier_prices() -> (Prices, TokenPriceSources) { + let flat = [INPUT, OUTPUT, READ, EXPLICIT, WRITE, HOUR, TWELVE] + .into_iter() + .map(|meter| rate(meter, ServiceTier::Standard, Band::Base, 9.0)); + let tier_rates = [ + (INPUT, 0, 1.0), + (OUTPUT, 0, 2.0), + (WRITE, 0, 3.0), + (INPUT, 100, 4.0), + (READ, 100, 0.0), + (WRITE, 100, 6.0), + (HOUR, 100, 0.0), + ] + .into_iter() + .map(|(meter, start, value)| { + let (price, rate) = rate( + meter, + ServiceTier::Standard, + Band::over_prompt_tokens(start), + value, + ); + ((price, PriceSource::TokenTier(start)), rate) + }); + let prices = Prices::from_sources( + flat.map(|(price, rate)| ((price, PriceSource::Flat), rate)) + .chain(tier_rates) + .collect(), + OffPeak::new( + Schedule { + windows: vec![Window { + hours: vec!["01:00-02:00".parse().unwrap()], + weekdays: None, + }], + weekday_timezone: None, + }, + OffPeakRates { + input: UnitPrice::new(7.0), + output: UnitPrice::new(8.0), + cache_write: UnitPrice::new(0.0), + ..Default::default() + }, + ), + ); + let sources = TokenPriceSources { + flat: prices.iter().map(|(price, _)| price.clone()).collect(), + tiers: vec![ + TokenTier { + range: [0, 100], + meters: [INPUT, OUTPUT, WRITE].into(), + }, + TokenTier { + range: [100, 200], + meters: [INPUT, READ, WRITE, HOUR].into(), + }, + ], + }; + (prices, sources) + } + + #[rstest] + #[case::input(INPUT, 10, 0, INPUT, 1.0)] + #[case::boundary(INPUT, 100, 0, INPUT, 1.0)] + #[case::next(INPUT, 101, 0, INPUT, 4.0)] + #[case::final_boundary(INPUT, 200, 0, INPUT, 4.0)] + #[case::above_last(INPUT, 201, 0, INPUT, 4.0)] + #[case::zero_prompt(INPUT, 0, 0, INPUT, 9.0)] + #[case::read_ignores_flat(READ, 10, 0, INPUT, 1.0)] + #[case::explicit_fallback(EXPLICIT, 10, 0, INPUT, 1.0)] + #[case::write_ignores_flat(WRITE, 10, 0, WRITE, 3.0)] + #[case::hour_ignores_flat(HOUR, 10, 0, WRITE, 3.0)] + #[case::twelve_ignores_flat(TWELVE, 10, 0, WRITE, 3.0)] + #[case::zero_read(READ, 101, 0, READ, 0.0)] + #[case::explicit_fallback_zero(EXPLICIT, 101, 0, READ, 0.0)] + #[case::zero_hour(HOUR, 101, 0, HOUR, 0.0)] + #[case::output_falls_back_flat_not_previous_tier(OUTPUT, 101, 0, OUTPUT, 9.0)] + #[case::input_offpeak(INPUT, 10, 3600, INPUT, 7.0)] + #[case::read_fallback_precedes_input_offpeak(READ, 10, 3600, INPUT, 1.0)] + #[case::default_write_offpeak(WRITE, 10, 3600, WRITE, 0.0)] + #[case::hour_follows_write_offpeak(HOUR, 10, 3600, WRITE, 0.0)] + #[case::twelve_follows_write_offpeak(TWELVE, 10, 3600, WRITE, 0.0)] + #[case::explicit_hour_isolated_offpeak(HOUR, 101, 3600, HOUR, 0.0)] + #[case::output_offpeak(OUTPUT, 10, 3600, OUTPUT, 8.0)] + #[case::offpeak_end_excluded(WRITE, 10, 7200, WRITE, 3.0)] + fn sdk_tier_cache_fallback_and_ttl_isolation( + tier_prices: (Prices, TokenPriceSources), + #[case] requested: Meter, + #[case] prompt: u64, + #[case] at: i64, + #[case] billed: Meter, + #[case] value: f64, + #[values(ServiceTier::Standard, ServiceTier::Priority)] tier: ServiceTier, + ) { + let (prices, sources) = tier_prices; + let usage = usage(requested.clone(), prompt, false); + let when = When { + tier, + channel: Channel::Online, + at: OffsetDateTime::from_unix_timestamp(at).unwrap(), + }; + let result = + calculate_with_policy(&prices, &usage, &when, SelectionPolicy::SdkTokens(&sources)); + assert_eq!(result, expected(billed, requested, value)); + } #[fixture] fn when() -> When { @@ -310,7 +519,7 @@ mod tests { ) { let (input_declared, output_declared) = declared; let (tier_reasoning, offpeak_reasoning) = reasoning; - let prices = Prices::new( + let prices = Prices::from_sources( [ rate(REASONING, ServiceTier::Standard, Band::Base, 5.0), rate(OUTPUT, ServiceTier::Standard, Band::Base, 3.0), @@ -330,6 +539,14 @@ mod tests { value, ) })) + .map(|(price, value)| { + let source = match (price.meter.clone(), price.when.band) { + (REASONING, Band::Base) => PriceSource::Flat, + (_, Band::Base) => PriceSource::TokenTier(0), + (_, Band::OverPromptTokens(start)) => PriceSource::TokenTier(start.get()), + }; + ((price, source), value) + }) .collect(), overlay(offpeak_reasoning, Some(1.0)), ); diff --git a/litellm-rust/crates/model-catalog/src/lower.rs b/litellm-rust/crates/model-catalog/src/lower.rs index 7a8f9d10ccf..cb39d5b155f 100644 --- a/litellm-rust/crates/model-catalog/src/lower.rs +++ b/litellm-rust/crates/model-catalog/src/lower.rs @@ -3,6 +3,7 @@ use std::collections::btree_map::Entry; use std::num::NonZeroU64; use litellm_cost::money::UnitPrice; +use litellm_cost::price::PriceSource; use litellm_cost::price::{ Adjustments, Band, CacheReadMode, CacheTtl, GuardrailUnit, InputUnit, Meter, OffPeak, OffPeakRates, OutputUnit, Price, Prices, Residency, SearchContextSize, TokenKind, Uplift, When, @@ -11,7 +12,7 @@ use litellm_cost::schedule::{Schedule, Window}; use litellm_cost::{TokenPriceSources, TokenTier}; use crate::error::{Error, Located, pointer_child, pointer_for_key}; -use crate::model::Model; +use crate::model::{Model, PriceLowering}; use crate::wire::{EntryWire, FlatPrice, OffPeakBlock, TierRow}; pub fn fatal(error: &Error) -> bool { @@ -70,21 +71,25 @@ impl TryFrom<&EntryWire> for Prices { type Error = Vec; fn try_from(wire: &EntryWire) -> Result { - let mut problems = Vec::new(); - let sourced = flat_prices(&wire.prices) - .chain(tier_prices(wire, &mut problems)) - .chain(search_context_prices(wire)) - .chain(guardrail_prices(wire)); - let rates = dedupe(sourced, &mut problems); - let off_peak = wire - .off_peak - .as_ref() - .and_then(|block| off_peak(block, &mut problems)); - if problems.is_empty() { - Ok(Prices::new(rates, off_peak)) - } else { - Err(problems) - } + lower_prices(wire, PriceLowering::Generic) + } +} + +fn lower_prices(wire: &EntryWire, policy: PriceLowering) -> Result> { + let mut problems = Vec::new(); + let sourced = flat_prices(&wire.prices) + .chain(tier_prices(wire, &mut problems)) + .chain(search_context_prices(wire)) + .chain(guardrail_prices(wire)); + let rates = dedupe(sourced, policy, &mut problems); + let off_peak = wire + .off_peak + .as_ref() + .and_then(|block| off_peak(block, &mut problems)); + if problems.is_empty() { + Ok(Prices::from_sources(rates, off_peak)) + } else { + Err(problems) } } @@ -119,6 +124,7 @@ impl From<&EntryWire> for TokenPriceSources { .prices .iter() .map(|flat| flat.flat.meter.clone()) + .chain(row.declared_token_selection.iter().cloned()) .collect(), }) }) @@ -131,7 +137,13 @@ impl TryFrom for Model { type Error = Vec; fn try_from(wire: EntryWire) -> Result { - let prices = Prices::try_from(&wire); + Self::lower(wire, PriceLowering::Generic) + } +} + +impl Model { + pub(crate) fn lower(wire: EntryWire, policy: PriceLowering) -> Result> { + let prices = lower_prices(&wire, policy); let adjustments = Adjustments::from(&wire); let token_price_sources = TokenPriceSources::from(&wire); let EntryWire { @@ -165,6 +177,7 @@ impl TryFrom for Model { struct Sourced { price: Price, + origin: PriceSource, rate: UnitPrice, source: String, path: String, @@ -174,6 +187,7 @@ fn flat_prices(prices: &[FlatPrice]) -> impl Iterator + '_ { prices.iter().map(|flat| { let (channel, when) = flat.flat.channel_and_when(); Sourced { + origin: PriceSource::Flat, price: Price { meter: flat.flat.meter.clone(), channel, @@ -188,17 +202,23 @@ fn flat_prices(prices: &[FlatPrice]) -> impl Iterator + '_ { fn dedupe( sourced: impl Iterator, + policy: PriceLowering, problems: &mut Vec, -) -> BTreeMap { - let mut seen: BTreeMap = BTreeMap::new(); +) -> BTreeMap<(Price, PriceSource), UnitPrice> { + let mut seen: BTreeMap<(Price, PriceSource), (UnitPrice, String, String)> = BTreeMap::new(); for Sourced { price, + origin, rate, source, path, } in sourced { - match seen.entry(price) { + let origin = match policy { + PriceLowering::Generic => PriceSource::Flat, + PriceLowering::SdkTokens => origin, + }; + match seen.entry((price, origin)) { Entry::Occupied(first) if first.get().0 == rate => {} Entry::Occupied(first) => problems.push(Located::new( path, @@ -339,6 +359,10 @@ fn tier_price(basis: TierBasis, start: u64, flat: &FlatPrice) -> Result PriceSource::TokenTier(start), + _ => PriceSource::Flat, + }, price: Price::online( meter, When { @@ -370,6 +394,7 @@ fn search_context_prices(wire: &EntryWire) -> impl Iterator + '_ .into_iter() .filter_map(|(size, name, rate)| { Some(Sourced { + origin: PriceSource::Flat, price: Price::online(Meter::WebSearch(size), When::default()), rate: rate?, source: format!("search_context_cost_per_query.search_context_size_{name}"), @@ -384,6 +409,7 @@ fn search_context_prices(wire: &EntryWire) -> impl Iterator + '_ fn guardrail_prices(wire: &EntryWire) -> impl Iterator + '_ { wire.guardrail.iter().flatten().map(|(unit, rate)| Sourced { + origin: PriceSource::Flat, price: Price::online(Meter::Guardrail(GuardrailUnit::new(unit)), When::default()), rate: *rate, source: format!("guardrail_cost_per_unit.{unit}"), @@ -505,35 +531,35 @@ mod tests { #[rstest] #[case::tier_output( serde_json::json!({"output_cost_per_reasoning_token":5,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":2,"output_cost_per_token":3},{"range":[100,1000],"input_cost_per_token":4,"output_cost_per_token":6}]}), - Meter::Output(OutputUnit::ReasoningToken), 101, 30.0 + Meter::Output(OutputUnit::ReasoningToken), 101, Some(30.0) )] #[case::unpriced_tier( serde_json::json!({"output_cost_per_reasoning_token":5,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":2,"output_cost_per_token":3},{"range":[100,1000],"output_cost_per_reasoning_token":9,"output_cost_per_token":6}]}), - Meter::Output(OutputUnit::ReasoningToken), 101, 25.0 + Meter::Output(OutputUnit::ReasoningToken), 101, Some(25.0) )] #[case::tier_modality_is_not_flat( serde_json::json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":2,"output_cost_per_audio_token":3}]}), - Meter::Output(OutputUnit::Token(TokenKind::Audio)), 10, 10.0 + Meter::Output(OutputUnit::Token(TokenKind::Audio)), 10, Some(10.0) )] #[case::tier_reasoning_is_not_flat( serde_json::json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":2,"output_cost_per_reasoning_token":3}]}), - Meter::Output(OutputUnit::ReasoningToken), 0, 10.0 + Meter::Output(OutputUnit::ReasoningToken), 0, None )] #[case::explicit_free_tier_output( serde_json::json!({"output_cost_per_reasoning_token":5,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":0,"output_cost_per_token":0}]}), - Meter::Output(OutputUnit::ReasoningToken), 10, 0.0 + Meter::Output(OutputUnit::ReasoningToken), 10, Some(0.0) )] fn lowering_retains_token_rate_origins( #[case] fields: Value, #[case] meter: Meter, #[case] prompt_tokens: u64, - #[case] total: f64, + #[case] total: Option, ) { let mut entry = wire(fields); entry.attributes.litellm_provider = Some("test".into()); - let model = Model::try_from(entry).unwrap(); + let model = Model::lower(entry, PriceLowering::SdkTokens).unwrap(); let usage = litellm_cost::Usage { - quantities: [(meter, 5)].into(), + quantities: [(meter.clone(), 5)].into(), prompt_tokens, ..Default::default() }; @@ -542,15 +568,23 @@ mod tests { channel: Default::default(), at: time::OffsetDateTime::UNIX_EPOCH, }; - let litellm_cost::Priced::Known(result) = litellm_cost::calculate_with_policy( + let result = litellm_cost::calculate_with_policy( &model.prices, &usage, &when, litellm_cost::SelectionPolicy::SdkTokens(&model.token_price_sources), - ) else { - panic!("expected priced tokens") - }; - assert_eq!(result.total.get(), total); + ); + match (result, total) { + (litellm_cost::Priced::Known(result), Some(total)) => { + assert_eq!(result.total.get(), total) + } + (litellm_cost::Priced::Unpriced { missing, partial }, None) => { + assert_eq!(missing, [meter]); + assert!(partial.lines.is_empty()); + assert_eq!(partial.total.get(), 0.0); + } + _ => panic!("unexpected pricing result"), + } } fn wire(entry: Value) -> EntryWire { @@ -562,6 +596,81 @@ mod tests { wire } + #[rstest] + #[case::flat_and_tier(json!({"input_cost_per_token":1,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":3}]}), Some("DuplicatePrice"), None)] + #[case::equal_sources(json!({"input_cost_per_token":1,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1}]}), None, None)] + #[case::equal_flat_alias(json!({"input_cost_per_token":1,"input_cost_per_token_above_0k_tokens":1}), None, None)] + #[case::conflicting_flat_alias(json!({"input_cost_per_token":1,"input_cost_per_token_above_0k_tokens":2}), Some("DuplicatePrice"), Some("DuplicatePrice"))] + #[case::overlap(json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1},{"range":[50,200],"input_cost_per_token":2}]}), Some("TierGap"), Some("TierGap"))] + #[case::repeated_range(json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1},{"range":[0,100],"input_cost_per_token":1}]}), Some("TierGap"), Some("TierGap"))] + #[case::non_token(json!({"input_cost_per_second":1,"tiered_pricing":[{"range":[0,100],"input_cost_per_second":2}]}), Some("DuplicatePrice"), Some("DuplicatePrice"))] + #[case::results(json!({"input_cost_per_query":1,"tiered_pricing":[{"max_results_range":[0,100],"input_cost_per_query":2}]}), Some("DuplicatePrice"), Some("DuplicatePrice"))] + #[case::suffix(json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token_priority":2}]}), Some("SuffixInsideBlock"), Some("SuffixInsideBlock"))] + #[case::two_band_sources(json!({"input_cost_per_token_above_100_tokens":1,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":2}]}), Some("BandsFromTwoSources"), Some("BandsFromTwoSources"))] + fn source_preserving_lowering_only_admits_distinct_token_sources( + #[case] fields: Value, + #[case] generic_error: Option<&str>, + #[case] sdk_error: Option<&str>, + #[values(PriceLowering::Generic, PriceLowering::SdkTokens)] policy: PriceLowering, + ) { + let expected = match policy { + PriceLowering::Generic => generic_error, + PriceLowering::SdkTokens => sdk_error, + }; + let result = lower_prices(&wire(fields), policy); + match (result, expected) { + (Ok(prices), None) => { + assert_eq!( + prices.get(&online(TEXT_INPUT, ServiceTier::Standard, Band::Base)), + UnitPrice::new(1.0) + ); + } + (Err(errors), Some(expected)) => assert_eq!(variant_name(&errors[0].error), expected), + _ => panic!("unexpected lowering result"), + } + } + + #[rstest] + #[case::below(99, false, 3.0)] + #[case::boundary(100, false, 3.0)] + #[case::inclusive(100, true, 5.0)] + #[case::above(101, false, 5.0)] + fn sdk_policy_preserves_mixed_tier_non_token_bands( + #[case] prompt: u64, + #[case] inclusive: bool, + #[case] rate: f64, + ) { + let fields = json!({"litellm_provider":"test","tiered_pricing":[ + {"range":[0,100],"input_cost_per_token":1,"input_cost_per_second":3}, + {"range":[100,200],"input_cost_per_token":4,"input_cost_per_second":5} + ]}); + let generic = Model::try_from(wire(fields.clone())).unwrap(); + let sdk = Model::lower(wire(fields), PriceLowering::SdkTokens).unwrap(); + let usage = litellm_cost::Usage { + quantities: [(Meter::Input(InputUnit::Second), 10)].into(), + prompt_tokens: prompt, + inclusive_threshold: inclusive, + ..Default::default() + }; + let when = litellm_cost::When { + tier: Default::default(), + channel: Default::default(), + at: time::OffsetDateTime::UNIX_EPOCH, + }; + let result = litellm_cost::calculate_with_policy( + &sdk.prices, + &usage, + &when, + litellm_cost::SelectionPolicy::SdkTokens(&sdk.token_price_sources), + ); + let generic = litellm_cost::calculate(&generic.prices, &usage, &when); + let litellm_cost::Priced::Known(ref priced) = generic else { + panic!("missing generic price") + }; + assert_eq!(priced.total.get(), 10.0 * rate); + assert_eq!(result, generic); + } + fn prices(entry: Value) -> Result> { Prices::try_from(&wire(entry)) } diff --git a/litellm-rust/crates/model-catalog/src/model.rs b/litellm-rust/crates/model-catalog/src/model.rs index 0a9fa64e04a..94017e5bf38 100644 --- a/litellm-rust/crates/model-catalog/src/model.rs +++ b/litellm-rust/crates/model-catalog/src/model.rs @@ -17,8 +17,22 @@ pub struct Model { pub unrecognized: Vec, } +#[derive(Clone, Copy, Default, strum::VariantArray)] +pub enum PriceLowering { + #[default] + Generic, + SdkTokens, +} + impl Model { pub fn from_fields(fields: &Fields) -> Result> { - Self::try_from(EntryWire::read(fields)) + Self::from_fields_with_policy(fields, PriceLowering::Generic) + } + + pub fn from_fields_with_policy( + fields: &Fields, + policy: PriceLowering, + ) -> Result> { + Self::lower(EntryWire::read(fields), policy) } } diff --git a/litellm-rust/crates/model-catalog/src/wire/blocks.rs b/litellm-rust/crates/model-catalog/src/wire/blocks.rs index 81dde65d631..dc0493235db 100644 --- a/litellm-rust/crates/model-catalog/src/wire/blocks.rs +++ b/litellm-rust/crates/model-catalog/src/wire/blocks.rs @@ -1,4 +1,7 @@ +use std::collections::BTreeSet; + use litellm_cost::money::UnitPrice; +use litellm_cost::price::{InputUnit, Meter, OutputUnit, TokenKind}; use litellm_cost::schedule::{UtcWindow, Weekday}; use serde::Deserialize; use serde::de::DeserializeOwned; @@ -24,6 +27,7 @@ pub struct TierRow { pub range: Option<[u64; 2]>, pub max_results_range: Option<[u64; 2]>, pub prices: Vec, + pub declared_token_selection: BTreeSet, } #[derive(Clone, Debug, Default, PartialEq)] @@ -142,6 +146,23 @@ impl Reader<'_> { let fields = self.object(&path, value)?; let mut row = TierRow { path: path.clone(), + declared_token_selection: [ + ( + "input_cost_per_token", + Meter::Input(InputUnit::Token(TokenKind::Text)), + ), + ( + "output_cost_per_token", + Meter::Output(OutputUnit::Token(TokenKind::Text)), + ), + ( + "output_cost_per_reasoning_token", + Meter::Output(OutputUnit::ReasoningToken), + ), + ] + .into_iter() + .filter_map(|(key, meter)| fields.contains_key(key).then_some(meter)) + .collect(), ..TierRow::default() }; for (name, value) in fields.iter().filter(|(_, value)| !value.is_null()) { diff --git a/litellm-rust/crates/python-bridge/src/lib.rs b/litellm-rust/crates/python-bridge/src/lib.rs index 28c2b4f5863..a62f1e727ca 100644 --- a/litellm-rust/crates/python-bridge/src/lib.rs +++ b/litellm-rust/crates/python-bridge/src/lib.rs @@ -33,10 +33,11 @@ mod _native { #[pymodule_export] use crate::model_registry::{ CatalogRefresher, FetchedRegistry, InvalidProvider, ModelCostLayers, ModelInfoView, - ModelNotFound, ModelRegistry, PriceLine, Priced, RegistrationTarget, RegistryNotModified, - RegistryUnavailable, ResolvedModel, RowError, RowErrors, Unpriced, UsageInput, WhenInput, - fetch_once, fetch_with_retry, invalidate_model_cost_index, model_info, model_row_errors, - price, registration_target, resolve_model, write_rows, + ModelNotFound, ModelRegistry, PriceEvaluation, PriceLine, Priced, RegistrationTarget, + RegistryNotModified, RegistryUnavailable, ResolvedModel, RowError, RowErrors, SelectedRate, + Unpriced, UsageInput, WhenInput, fetch_once, fetch_with_retry, has_token_prices, + invalidate_model_cost_index, model_info, model_row_errors, price, price_with_rates, + registration_target, resolve_model, write_rows, }; #[pymodule_export] use crate::routes::audio_transcription::{atranscription, transcription}; diff --git a/litellm-rust/crates/python-bridge/src/model_registry/live.rs b/litellm-rust/crates/python-bridge/src/model_registry/live.rs index 7fbdabb4381..d729d88ef26 100644 --- a/litellm-rust/crates/python-bridge/src/model_registry/live.rs +++ b/litellm-rust/crates/python-bridge/src/model_registry/live.rs @@ -8,10 +8,11 @@ use litellm_host_python::from_py; use litellm_model_catalog::wire::{Fields, FlatKey}; use litellm_model_catalog::{self as resolution, Keys, Query, Resolved}; use litellm_model_catalog::{Error, Located, Model}; +use pyo3::IntoPyObjectExt; use pyo3::class::gc::{PyTraverseError, PyVisit}; use pyo3::exceptions::{PyException, PyValueError}; use pyo3::prelude::*; -use pyo3::types::{PyAny, PyDict, PyModule, PySet, PyString}; +use pyo3::types::{PyAny, PyBool, PyDict, PyModule, PySet, PyString}; use time::OffsetDateTime; use super::{RowError, escape_pointer_segment, fields_to_dict, nonfinite_errors, row_error}; @@ -327,6 +328,14 @@ pub(crate) struct RowErrors { } fn lower_row(key: &str, row: &Bound<'_, PyAny>) -> Result<(Fields, Model), RowErrors> { + lower_row_with_policy(key, row, litellm_model_catalog::PriceLowering::Generic) +} + +fn lower_row_with_policy( + key: &str, + row: &Bound<'_, PyAny>, + policy: litellm_model_catalog::PriceLowering, +) -> Result<(Fields, Model), RowErrors> { let path = format!("/{}", escape_pointer_segment(key)); let located = |error| RowErrors { errors: vec![row_error(&Located::new(&path, error))], @@ -348,7 +357,7 @@ fn lower_row(key: &str, row: &Bound<'_, PyAny>) -> Result<(Fields, Model), RowEr }; valid.map_err(|_| invalid())?; let fields: Fields = from_py(row).map_err(|_| invalid())?; - let model = Model::from_fields(&fields).map_err(|errors| RowErrors { + let model = Model::from_fields_with_policy(&fields, policy).map_err(|errors| RowErrors { errors: errors .into_iter() .map(|error| row_error(&Located::new(format!("{path}{}", error.path), error.error))) @@ -594,7 +603,39 @@ pub(crate) enum PriceResult { Errors(RowErrors), } -#[derive(strum::EnumString, strum::VariantArray)] +#[pyclass( + frozen, + get_all, + skip_from_py_object, + module = "litellm.rust_bridge._native" +)] +#[derive(Clone)] +pub(crate) struct SelectedRate { + requested_meter: String, + source_meter: Option, + unit_price: Option, +} + +#[pyclass(frozen, get_all, module = "litellm.rust_bridge._native")] +pub(crate) struct PriceEvaluation { + pricing: Py, + rates: Vec, +} + +#[pymethods] +impl PriceEvaluation { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + visit.call(&self.pricing) + } +} + +#[derive(IntoPyObject)] +pub(crate) enum EvaluationResult { + Evaluated(PriceEvaluation), + Errors(RowErrors), +} + +#[derive(Clone, Copy, strum::EnumString, strum::VariantArray)] enum PricePolicy { #[strum(serialize = "generic")] Generic, @@ -602,6 +643,47 @@ enum PricePolicy { SdkTokens, } +impl PricePolicy { + fn selection(self, model: &Model) -> SelectionPolicy<'_> { + match self { + Self::Generic => SelectionPolicy::Generic, + Self::SdkTokens => SelectionPolicy::SdkTokens(&model.token_price_sources), + } + } + + fn lower(self, row: &Bound<'_, PyAny>, channel: Channel) -> Result { + let lowering = match (self, channel) { + (Self::SdkTokens, Channel::Online) => litellm_model_catalog::PriceLowering::SdkTokens, + _ => litellm_model_catalog::PriceLowering::Generic, + }; + lower_row_with_policy("", row, lowering).map(|(_, model)| model) + } +} + +fn pricing_policy(policy: &str) -> PyResult { + policy + .parse() + .map_err(|_| PyValueError::new_err("unknown pricing policy")) +} + +#[derive(IntoPyObject)] +pub(crate) enum TokenPricePresence { + Present(bool), + Errors(RowErrors), +} + +#[pyfunction] +#[pyo3(signature = (row, *, policy="generic"))] +pub(crate) fn has_token_prices( + row: &Bound<'_, PyAny>, + policy: &str, +) -> PyResult { + Ok(match pricing_policy(policy)?.lower(row, Channel::Online) { + Ok(model) => TokenPricePresence::Present(model.prices.has_token_prices()), + Err(errors) => TokenPricePresence::Errors(errors), + }) +} + #[pyfunction] #[pyo3(signature = (row, usage, when, *, policy="generic"))] pub(crate) fn price( @@ -610,30 +692,89 @@ pub(crate) fn price( when: &WhenInput, policy: &str, ) -> PyResult { - let policy = policy - .parse::() - .map_err(|_| PyValueError::new_err("unknown pricing policy"))?; - let model = match lower_row("", row) { - Ok((_, model)) => model, + let policy = pricing_policy(policy)?; + let model = match policy.lower(row, when.when.channel) { + Ok(model) => model, Err(errors) => return Ok(PriceResult::Errors(errors)), }; - let policy = match policy { - PricePolicy::Generic => SelectionPolicy::Generic, - PricePolicy::SdkTokens => SelectionPolicy::SdkTokens(&model.token_price_sources), - }; - Ok( - match litellm_cost::calculate_with_policy(&model.prices, &usage.usage, &when.when, policy) { - litellm_cost::Priced::Known(breakdown) => PriceResult::Priced(breakdown.into()), - litellm_cost::Priced::Unpriced { missing, partial } => { - PriceResult::Unpriced(Unpriced { - missing: missing.iter().map(meter_name).collect(), - partial: Py::new(row.py(), Priced::from(partial))?, - }) - } - }, + let policy = policy.selection(&model); + price_result( + row.py(), + litellm_cost::calculate_with_policy(&model.prices, &usage.usage, &when.when, policy), ) } +fn price_result(py: Python<'_>, priced: litellm_cost::Priced) -> PyResult { + Ok(match priced { + litellm_cost::Priced::Known(breakdown) => PriceResult::Priced(breakdown.into()), + litellm_cost::Priced::Unpriced { missing, partial } => PriceResult::Unpriced(Unpriced { + missing: missing.iter().map(meter_name).collect(), + partial: Py::new(py, Priced::from(partial))?, + }), + }) +} + +#[pyfunction] +#[pyo3( + signature = (row, usage, when, *, policy="generic", project=Vec::new(), factors=Vec::new()), + text_signature = "(row, usage, when, *, policy='generic', project=(), factors=())" +)] +pub(crate) fn price_with_rates( + row: &Bound<'_, PyAny>, + usage: &UsageInput, + when: &WhenInput, + policy: &str, + project: Vec, + factors: Vec>, +) -> PyResult { + let policy = pricing_policy(policy)?; + let project = project + .iter() + .map(|key| { + parse_meter(key) + .filter(Meter::is_token) + .ok_or_else(|| PyValueError::new_err("only token meters can be projected")) + }) + .collect::>>()?; + let factors = factors + .iter() + .map(|factor| { + if factor.is_instance_of::() { + return Err(PyValueError::new_err( + "factors must be finite non-negative numbers", + )); + } + litellm_cost::money::ScaleFactor::new(factor.extract()?) + .ok_or_else(|| PyValueError::new_err("factors must be finite non-negative numbers")) + }) + .collect::>>()?; + let model = match policy.lower(row, when.when.channel) { + Ok(model) => model, + Err(errors) => return Ok(EvaluationResult::Errors(errors)), + }; + let evaluation = litellm_cost::calculate_with_rates( + &model.prices, + &usage.usage, + &when.when, + policy.selection(&model), + &project, + &factors, + ) + .map_err(|error| PyValueError::new_err(error.to_string()))?; + Ok(EvaluationResult::Evaluated(PriceEvaluation { + pricing: price_result(row.py(), evaluation.pricing)?.into_py_any(row.py())?, + rates: evaluation + .rates + .into_iter() + .map(|rate| SelectedRate { + requested_meter: meter_name(&rate.requested_meter), + source_meter: rate.resolved.as_ref().map(|(meter, _)| meter_name(meter)), + unit_price: rate.resolved.map(|(_, price)| price.get()), + }) + .collect(), + })) +} + fn meter_name(meter: &Meter) -> String { use litellm_cost::price::*; let token = |kind: &TokenKind| match kind { @@ -1334,6 +1475,487 @@ assert n.model_info(models, "Model").input_cost_per_token == 2 }; assert_eq!(errors.errors[0].key, ""); assert_eq!(errors.errors[0].kind, kind); + let TokenPricePresence::Errors(errors) = has_token_prices(&row, policy).unwrap() else { + panic!("presence must retain validation errors") + }; + assert_eq!(errors.errors[0].kind, kind); + }); + } + + #[rstest] + #[case::metadata(json!({"mode":"chat"}), false)] + #[case::null(json!({"input_cost_per_token":null}), false)] + #[case::zero(json!({"input_cost_per_token":0}), true)] + #[case::output_only(json!({"output_cost_per_token":2}), true)] + #[case::read_only(json!({"cache_read_input_token_cost":0}), true)] + #[case::explicit_read(json!({"explicit_cache_read_input_token_cost":1}), true)] + #[case::write_only(json!({"cache_creation_input_token_cost_above_1hr":1}), true)] + #[case::twelve_hours(json!({"cache_creation_input_token_cost_above_12hr":1}), true)] + #[case::reasoning_only(json!({"output_cost_per_reasoning_token":1}), true)] + #[case::audio_only(json!({"output_cost_per_audio_token":1}), true)] + #[case::image_token_only(json!({"input_cost_per_image_token":1}), true)] + #[case::video_token_only(json!({"input_cost_per_video_token":1}), true)] + #[case::bounded_tier(json!({"tiered_pricing":[{"range":[0,1],"output_cost_per_token":0}]}), true)] + #[case::service_only(json!({"output_cost_per_token_priority":1}), true)] + #[case::band_only(json!({"input_cost_per_token_above_200k_tokens":1}), true)] + #[case::offpeak_only(json!({"off_peak_pricing":{"hours_utc":"01:00-02:00","cache_read_input_token_cost":0}}), true)] + #[case::batch_only(json!({"input_cost_per_token_batches":0}), true)] + #[case::decisions_only(json!({"output_cost_per_token_decisions":0}), true)] + #[case::seconds(json!({"input_cost_per_second":0}), false)] + #[case::images(json!({"output_cost_per_image":1}), false)] + #[case::query_tier(json!({"tiered_pricing":[{"max_results_range":[0,10],"input_cost_per_query":1}]}), false)] + fn explicit_token_presence_uses_validated_rates( + #[from(interpreter)] _interpreter: (), + #[case] fields: Value, + #[case] expected: bool, + #[values("generic", "sdk_tokens")] policy: &str, + ) { + Python::attach(|py| { + let row = dict(py, fields); + row.set_item("litellm_provider", "openai").unwrap(); + let before: Value = from_py(row.as_any()).unwrap(); + let TokenPricePresence::Present(present) = + has_token_prices(row.as_any(), policy).unwrap() + else { + panic!("expected valid row") + }; + assert_eq!(present, expected); + assert_eq!(from_py::(row.as_any()).unwrap(), before); + }); + } + + #[rstest] + fn presence_binding_is_live_keyword_only_and_source_aware( + #[from(interpreter)] _interpreter: (), + ) { + Python::attach(|py| { + let locals = PyDict::new(py); + locals.set_item("n", crate::native_module(py)).unwrap(); + py.run( + pyo3::ffi::c_str!( + r#" +import json +row = {"litellm_provider": "openai", "tiered_pricing": [{"range": [0, 1]}]} +assert n.has_token_prices(row) is False +assert n.has_token_prices(row, policy="sdk_tokens") is False +row["tiered_pricing"][0]["output_cost_per_token"] = 0 +before = json.dumps(row) +assert n.has_token_prices(row) is True +assert n.has_token_prices(row, policy="sdk_tokens") is True +assert json.dumps(row) == before +row["output_cost_per_token"] = 1 +assert isinstance(n.has_token_prices(row), n.RowErrors) +assert n.has_token_prices(row, policy="sdk_tokens") is True +row["tiered_pricing"][0]["output_cost_per_token"] = float("inf") +assert isinstance(n.has_token_prices(row, policy="sdk_tokens"), n.RowErrors) +row["tiered_pricing"][0]["output_cost_per_token"] = None +del row["output_cost_per_token"] +assert n.has_token_prices(row, policy="sdk_tokens") is False +try: + n.has_token_prices(row, policy="unknown") +except ValueError as error: + assert str(error) == "unknown pricing policy" +else: + raise AssertionError("unknown policy accepted") +try: + n.has_token_prices(row, "sdk_tokens") +except TypeError: + pass +else: + raise AssertionError("positional policy accepted") +"# + ), + Some(&locals), + None, + ) + .unwrap(); + }); + } + + #[rstest] + #[case::identity(vec![], 1.0)] + #[case::speed(vec![6.0], 6.0)] + #[case::combined(vec![2.0, 3.0], 6.0)] + #[case::regional(vec![1.1], 1.1)] + #[case::discount(vec![0.5], 0.5)] + #[case::zero(vec![0.0], 0.0)] + fn all_cached_usage_projects_unused_rates_without_fake_lines( + #[from(interpreter)] _interpreter: (), + #[case] factors: Vec, + #[case] factor: f64, + ) { + Python::attach(|py| { + let locals = PyDict::new(py); + locals.set_item("n", crate::native_module(py)).unwrap(); + locals.set_item("factors", factors).unwrap(); + locals.set_item("factor", factor).unwrap(); + py.run(pyo3::ffi::c_str!(r#" +import json +row = {"litellm_provider": "anthropic", "input_cost_per_token": 1, "output_cost_per_token": 2, + "cache_read_input_token_cost": 0.1, "cache_creation_input_token_cost": 1.25, + "provider_specific_entry": {"fast": 6}, "regional_processing_uplift_multiplier_eu": 1.1} +before = json.dumps(row) +meters = ("input_cost_per_token", "output_cost_per_token", "cache_read_input_token_cost", + "cache_creation_input_token_cost", "cache_creation_input_token_cost_above_1hr", + "cache_creation_input_token_cost_above_12hr", "output_cost_per_reasoning_token", + "cache_read_input_audio_token_cost") +usage = n.UsageInput({"cache_read_input_token_cost": 100, "input_cost_per_token": 0, "output_cost_per_token": 0}, prompt_tokens=100) +when = n.WhenInput(0) +evaluated = n.price_with_rates(row, usage, when, policy="sdk_tokens", project=meters, factors=factors) +assert isinstance(evaluated, n.PriceEvaluation) +assert isinstance(evaluated.pricing, n.Priced) +assert (evaluated.pricing.input, evaluated.pricing.output, evaluated.pricing.total) == (10 * factor, 0, 10 * factor) +assert len(evaluated.pricing.lines) == 1 +line = evaluated.pricing.lines[0] +assert (line.meter, line.quantity, line.unit_price, line.amount, line.fallback_from) == (meters[2], 100, 0.1 * factor, 10 * factor, None) +assert tuple(rate.requested_meter for rate in evaluated.rates) == meters +assert tuple(rate.source_meter for rate in evaluated.rates) == (meters[0], meters[1], meters[2], meters[3], meters[3], meters[3], meters[1], meters[2]) +assert tuple(rate.unit_price for rate in evaluated.rates) == (factor, 2 * factor, 0.1 * factor, 1.25 * factor, 1.25 * factor, 1.25 * factor, 2 * factor, 0.1 * factor) +default = n.price_with_rates(row, usage, when) +assert default.rates == [] +assert default.pricing.total == n.price(row, usage, when).total == 10 +assert json.dumps(row) == before +"#), Some(&locals), None).unwrap(); + }); + } + + #[rstest] + #[case::tier_read(json!({"cache_read_input_token_cost": 9, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 1, "output_cost_per_token": 2}]}), "cache_read_input_token_cost", (100, false, "standard", "online", 0), Some("input_cost_per_token"), Some(1.0))] + #[case::tier_hour(json!({"cache_creation_input_token_cost_above_1hr": 9, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 1, "output_cost_per_token": 2, "cache_creation_input_token_cost": 3}]}), "cache_creation_input_token_cost_above_1hr", (100, false, "standard", "online", 0), Some("cache_creation_input_token_cost"), Some(3.0))] + #[case::tier_twelve_hours(json!({"cache_creation_input_token_cost_above_12hr": 9, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 1, "output_cost_per_token": 2, "cache_creation_input_token_cost": 3}]}), "cache_creation_input_token_cost_above_12hr", (100, false, "standard", "online", 0), Some("cache_creation_input_token_cost"), Some(3.0))] + #[case::tier_reasoning(json!({"output_cost_per_reasoning_token": 5, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 2, "output_cost_per_token": 3}]}), "output_cost_per_reasoning_token", (100, false, "standard", "online", 0), Some("output_cost_per_token"), Some(3.0))] + #[case::priority_reasoning(json!({"input_cost_per_token": 1, "output_cost_per_token": 2, "output_cost_per_reasoning_token": 3, "output_cost_per_token_priority": 4}), "output_cost_per_reasoning_token", (100, false, "priority", "online", 0), Some("output_cost_per_token"), Some(4.0))] + #[case::priority_audio(json!({"input_cost_per_token": 1, "output_cost_per_token": 2, "output_cost_per_audio_token": 3, "output_cost_per_audio_token_priority": 4}), "output_cost_per_audio_token", (100, false, "priority", "online", 0), Some("output_cost_per_audio_token"), Some(3.0))] + #[case::offpeak_input(json!({"input_cost_per_token": 2, "output_cost_per_token": 4, "off_peak_pricing": {"hours_utc": "00:00-06:00", "input_cost_per_token": 1}}), "input_cost_per_token", (100, false, "standard", "online", 3600), Some("input_cost_per_token"), Some(1.0))] + #[case::peak_input(json!({"input_cost_per_token": 2, "output_cost_per_token": 4, "off_peak_pricing": {"hours_utc": "00:00-06:00", "input_cost_per_token": 1}}), "input_cost_per_token", (100, false, "standard", "online", 43200), Some("input_cost_per_token"), Some(2.0))] + #[case::offpeak_preserves_tier_read(json!({"tiered_pricing": [{"range": [0,100], "input_cost_per_token": 2, "output_cost_per_token": 3}], "off_peak_pricing": {"hours_utc": "00:00-06:00", "input_cost_per_token": 1}}), "cache_read_input_token_cost", (100, false, "standard", "online", 3600), Some("input_cost_per_token"), Some(2.0))] + #[case::inclusive_band(json!({"input_cost_per_token": 1, "output_cost_per_token": 2, "output_cost_per_token_above_200k_tokens": 4}), "output_cost_per_token", (200000, true, "standard", "online", 0), Some("output_cost_per_token"), Some(4.0))] + #[case::exclusive_band(json!({"input_cost_per_token": 1, "output_cost_per_token": 2, "output_cost_per_token_above_200k_tokens": 4}), "output_cost_per_token", (200000, false, "standard", "online", 0), Some("output_cost_per_token"), Some(2.0))] + #[case::batch(json!({"input_cost_per_token": 1, "output_cost_per_token": 2}), "output_cost_per_token", (100, false, "standard", "batch", 0), Some("output_cost_per_token"), Some(1.0))] + #[case::null_tier_output(json!({"input_cost_per_token": 1, "output_cost_per_token": 6, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 2, "output_cost_per_token": null}]}), "output_cost_per_token", (100, false, "standard", "online", 0), None, None)] + #[case::absent_tier_output(json!({"input_cost_per_token": 1, "output_cost_per_token": 6, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 2}]}), "output_cost_per_token", (100, false, "standard", "online", 0), Some("output_cost_per_token"), Some(6.0))] + #[case::zero_tier_output(json!({"input_cost_per_token": 1, "output_cost_per_token": 6, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 2, "output_cost_per_token": 0}]}), "output_cost_per_token", (100, false, "standard", "online", 0), Some("output_cost_per_token"), Some(0.0))] + fn projection_uses_the_actual_token_selector_and_context( + #[from(interpreter)] _interpreter: (), + #[case] fields: Value, + #[case] meter: &str, + #[case] context: (u64, bool, &str, &str, i64), + #[case] source: Option<&str>, + #[case] rate: Option, + ) { + let (prompt, inclusive, tier, channel, at) = context; + Python::attach(|py| { + let locals = PyDict::new(py); + locals.set_item("n", crate::native_module(py)).unwrap(); + let row = dict(py, fields); + row.set_item("litellm_provider", "openai").unwrap(); + locals.set_item("row", row).unwrap(); + locals.set_item("meter", meter).unwrap(); + locals.set_item("prompt", prompt).unwrap(); + locals.set_item("inclusive", inclusive).unwrap(); + locals.set_item("tier", tier).unwrap(); + locals.set_item("channel", channel).unwrap(); + locals.set_item("at", at).unwrap(); + locals.set_item("source", source).unwrap(); + locals.set_item("rate", rate).unwrap(); + py.run(pyo3::ffi::c_str!(r#" +import json +before = json.dumps(row) +when = n.WhenInput(at, tier=tier, channel=channel) +unused = n.price_with_rates(row, n.UsageInput({}, prompt_tokens=prompt, inclusive_threshold=inclusive), when, policy="sdk_tokens", project=[meter], factors=[2,3]) +assert isinstance(unused.pricing, n.Priced) +assert unused.pricing.total == 0 and unused.pricing.lines == [] +assert len(unused.rates) == 1 +selected = unused.rates[0] +assert (selected.requested_meter, selected.source_meter, selected.unit_price) == (meter, source, None if rate is None else rate * 6) +used = n.price_with_rates(row, n.UsageInput({meter: 1}, prompt_tokens=prompt, inclusive_threshold=inclusive), when, policy="sdk_tokens", project=[meter], factors=[2,3]) +if rate is None: + assert isinstance(used.pricing, n.Unpriced) + assert used.pricing.missing == [meter] and used.pricing.partial.total == 0 +else: + assert isinstance(used.pricing, n.Priced) + line = used.pricing.lines[0] + assert (line.meter, line.unit_price, line.amount, line.quantity, line.fallback_from) == (source, rate * 6, rate * 6, 1, None if meter == source else meter) + assert used.pricing.total == rate * 6 +assert json.dumps(row) == before +"#), Some(&locals), None).unwrap(); + }); + } + + #[rstest] + #[case::negative("[-1]")] + #[case::nan("[float('nan')]")] + #[case::infinite("[float('inf')]")] + #[case::zero_does_not_hide_invalid("[0, float('inf')]")] + #[case::boolean("[True]")] + #[case::string("['6']")] + #[case::not_sequence("6")] + #[case::null("None")] + #[case::overflow("[1e308, 1e308]")] + fn projection_binding_rejects_invalid_factors( + #[from(interpreter)] _interpreter: (), + #[case] factors: &str, + ) { + Python::attach(|py| { + let locals = PyDict::new(py); + locals.set_item("n", crate::native_module(py)).unwrap(); + locals.set_item("factors", factors).unwrap(); + py.run(pyo3::ffi::c_str!(r#" +try: + n.price_with_rates({"litellm_provider": "openai", "input_cost_per_token": 1}, n.UsageInput({"input_cost_per_token": 1}), n.WhenInput(0), factors=eval(factors)) +except (ValueError, TypeError): + pass +else: + raise AssertionError("invalid factors accepted") +"#), Some(&locals), None).unwrap(); + }); + } + + #[rstest] + #[case::absent(json!({}), None)] + #[case::null(json!({"output_cost_per_token": null}), None)] + #[case::zero(json!({"output_cost_per_token": 0}), Some(0.0))] + #[case::priced(json!({"output_cost_per_token": 2}), Some(2.0))] + fn unused_missing_projection_does_not_make_actual_cache_billing_unpriced( + #[from(interpreter)] _interpreter: (), + #[case] fields: Value, + #[case] expected: Option, + #[values(0.0, 1.0, 1.1)] factor: f64, + ) { + Python::attach(|py| { + let locals = PyDict::new(py); + locals.set_item("n", crate::native_module(py)).unwrap(); + let row = dict(py, fields); + row.set_item("litellm_provider", "openai").unwrap(); + row.set_item("input_cost_per_token", 1).unwrap(); + row.set_item("cache_read_input_token_cost", 0.1).unwrap(); + locals.set_item("row", row).unwrap(); + locals + .set_item("expected", expected.map(|rate| rate * factor)) + .unwrap(); + locals.set_item("factor", factor).unwrap(); + py.run(pyo3::ffi::c_str!(r#" +usage = n.UsageInput({"cache_read_input_token_cost": 100, "output_cost_per_token": 0}, prompt_tokens=100) +result = n.price_with_rates(row, usage, n.WhenInput(0), policy="sdk_tokens", project=["output_cost_per_token"], factors=[factor]) +assert isinstance(result.pricing, n.Priced) +assert result.pricing.total == 10 * factor +assert len(result.pricing.lines) == 1 +assert result.rates[0].unit_price == expected +assert result.rates[0].source_meter == (None if expected is None else "output_cost_per_token") +"#), Some(&locals), None).unwrap(); + }); + } + + #[rstest] + fn projected_rates_validate_live_rows_and_keyword_binding( + #[from(interpreter)] _interpreter: (), + ) { + Python::attach(|py| { + let locals = PyDict::new(py); + locals.set_item("n", crate::native_module(py)).unwrap(); + py.run(pyo3::ffi::c_str!(r#" +import inspect +import gc +signature = inspect.signature(n.price_with_rates) +assert signature.parameters['project'].default == () +assert signature.parameters['factors'].default == () +row = {"litellm_provider": "openai", "input_cost_per_token": 1, "output_cost_per_token": 2, "tiered_pricing": [{"range": [0,100], "input_cost_per_token": 3, "output_cost_per_token": 4}]} +usage = n.UsageInput({"input_cost_per_token": 10}, prompt_tokens=10) +when = n.WhenInput(0) +assert isinstance(n.price_with_rates(row, usage, when), n.RowErrors) +first = n.price_with_rates(row, usage, when, policy="sdk_tokens", project=["output_cost_per_token"]) +assert gc.get_referents(first) == [first.pricing] +assert first.pricing.total == 30 and first.rates[0].unit_price == 4 +row["tiered_pricing"][0]["output_cost_per_token"] = 0 +assert n.price_with_rates(row, usage, when, policy="sdk_tokens", project=["output_cost_per_token"]).rates[0].unit_price == 0 +row["tiered_pricing"][0]["input_cost_per_token"] = None +partial = n.price_with_rates(row, usage, when, policy="sdk_tokens", project=["input_cost_per_token", "output_cost_per_token"], factors=[0]) +assert isinstance(partial.pricing, n.Unpriced) +assert partial.pricing.missing == ["input_cost_per_token"] and partial.pricing.partial.total == 0 +assert partial.rates[0].unit_price is None and partial.rates[1].unit_price == 0 +row["tiered_pricing"][0]["output_cost_per_token"] = "bad" +assert isinstance(n.price_with_rates(row, usage, when, policy="sdk_tokens"), n.RowErrors) +try: + n.price_with_rates(row, usage, when, policy="unknown") +except ValueError as error: + assert str(error) == "unknown pricing policy" +else: + raise AssertionError("unknown policy accepted") +try: + n.price_with_rates(row, usage, when, "sdk_tokens") +except TypeError: + pass +else: + raise AssertionError("positional policy accepted") +try: + n.price_with_rates({}, usage, when, project=["input_cost_per_image"]) +except ValueError as error: + assert str(error) == "only token meters can be projected" +else: + raise AssertionError("non-token projection accepted") +"#), Some(&locals), None).unwrap(); + }); + } + + #[rstest] + #[case::online("online", "sdk_tokens", true)] + #[case::generic("online", "generic", false)] + #[case::batch("batch", "sdk_tokens", false)] + #[case::decisions("decisions", "sdk_tokens", false)] + fn conflicting_flat_and_token_tier_is_only_admitted_for_sdk_online( + #[from(interpreter)] _interpreter: (), + #[case] channel: &str, + #[case] policy: &str, + #[case] accepted: bool, + ) { + Python::attach(|py| { + let row = dict( + py, + json!({"litellm_provider":"openai","input_cost_per_token":1,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":3}]}), + ); + let usage = + UsageInput::new(&dict(py, json!({"input_cost_per_token":10})), 10, false, 0) + .unwrap(); + let result = price( + row.as_any(), + &usage, + &WhenInput::new(0, "standard", channel).unwrap(), + policy, + ) + .unwrap(); + match result { + PriceResult::Priced(priced) => { + assert!(accepted); + assert_eq!(priced.total, 30.0); + } + PriceResult::Errors(errors) => { + assert!(!accepted); + assert_eq!(errors.errors[0].kind, "duplicate_price"); + } + PriceResult::Unpriced(_) => panic!("unexpected missing price"), + } + }); + } + + #[rstest] + #[case::flat_and_tier("flat-and-tier", json!({"input_cost_per_token":1,"output_cost_per_token":2,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":3,"output_cost_per_token":4}]}), (10,json!({}),json!({"input_cost_per_token":10,"output_cost_per_token":10})), (30.0,40.0))] + #[case::tier_read("tier-read", json!({"cache_read_input_token_cost":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":2}]}), (100,json!({"cached_tokens":40}),json!({"input_cost_per_token":60,"cache_read_input_token_cost":40,"output_cost_per_token":10})), (100.0,20.0))] + #[case::tier_hour("tier-hour", json!({"cache_creation_input_token_cost_above_1hr":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":2,"cache_creation_input_token_cost":3}]}), (100,json!({"cache_creation_tokens":20,"cache_creation_token_details":{"ephemeral_5m_input_tokens":10,"ephemeral_1h_input_tokens":10}}),json!({"input_cost_per_token":80,"cache_creation_input_token_cost":10,"cache_creation_input_token_cost_above_1hr":10,"output_cost_per_token":10})), (140.0,20.0))] + #[case::zero_tier("zero-tier", json!({"input_cost_per_token":1,"output_cost_per_token":2,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":0,"output_cost_per_token":0}]}), (10,json!({}),json!({"input_cost_per_token":10,"output_cost_per_token":10})), (0.0,0.0))] + #[case::output_fallback("output-fallback", json!({"input_cost_per_token":1,"output_cost_per_token":2,"output_cost_per_token_priority":8,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":3}]}), (10,json!({}),json!({"input_cost_per_token":10,"output_cost_per_token":10})), (30.0,20.0))] + #[case::zero_prompt("zero-prompt", json!({"input_cost_per_token":1,"output_cost_per_token":2,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":3,"output_cost_per_token":4}]}), (0,json!({}),json!({"output_cost_per_token":10})), (0.0,20.0))] + #[case::no_input("no-input", json!({"input_cost_per_token":1,"output_cost_per_token":2,"tiered_pricing":[{"range":[0,100],"output_cost_per_token":4}]}), (10,json!({}),json!({"input_cost_per_token":10,"output_cost_per_token":10})), (10.0,20.0))] + #[case::offpeak_hour("offpeak-hour", json!({"cache_creation_input_token_cost_above_1hr":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":2,"cache_creation_input_token_cost":3}],"off_peak_pricing":{"hours_utc":"00:00-00:00","cache_creation_input_token_cost":0}}), (100,json!({"cache_creation_tokens":20,"cache_creation_token_details":{"ephemeral_5m_input_tokens":10,"ephemeral_1h_input_tokens":10}}),json!({"input_cost_per_token":80,"cache_creation_input_token_cost":10,"cache_creation_input_token_cost_above_1hr":10,"output_cost_per_token":10})), (80.0,20.0))] + #[case::explicit_hour("explicit-hour", json!({"cache_creation_input_token_cost_above_1hr":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":2,"cache_creation_input_token_cost":3,"cache_creation_input_token_cost_above_1hr":4}],"off_peak_pricing":{"hours_utc":"00:00-00:00","cache_creation_input_token_cost":0}}), (100,json!({"cache_creation_tokens":20,"cache_creation_token_details":{"ephemeral_5m_input_tokens":10,"ephemeral_1h_input_tokens":10}}),json!({"input_cost_per_token":80,"cache_creation_input_token_cost":10,"cache_creation_input_token_cost_above_1hr":10,"output_cost_per_token":10})), (120.0,20.0))] + fn sdk_tier_cache_matches_public_raw_and_shaped( + #[from(interpreter)] _interpreter: (), + #[case] name: &str, + #[case] fields: Value, + #[case] usage: (u64, Value, Value), + #[case] expected: (f64, f64), + #[values("standard", "priority")] tier: &str, + ) { + Python::attach(|py| { + let locals = PyDict::new(py); + locals.set_item("n", crate::native_module(py)).unwrap(); + let row = dict(py, fields); + row.set_item("litellm_provider", "openai").unwrap(); + row.set_item("mode", "chat").unwrap(); + locals.set_item("row", &row).unwrap(); + locals.set_item("name", name).unwrap(); + locals.set_item("tier", tier).unwrap(); + locals.set_item("prompt", usage.0).unwrap(); + locals.set_item("details", dict(py, usage.1)).unwrap(); + locals.set_item("quantities", dict(py, usage.2)).unwrap(); + locals.set_item("expected", expected).unwrap(); + py.run(pyo3::ffi::c_str!(r#" +import json +import litellm +before = json.dumps(row) +usage = n.UsageInput(quantities, prompt_tokens=prompt) +when = n.WhenInput(0, tier=tier) +raw = n.price(row, usage, when, policy="sdk_tokens") +assert isinstance(raw, n.Priced) +assert (raw.input, raw.output) == expected +model = f"openai/p2d-followup-{name}-{tier}" +litellm.model_cost[model] = row +try: + kwargs = dict(model=model, custom_llm_provider="openai", service_tier=tier) + public_usage = litellm.Usage(prompt_tokens=prompt, completion_tokens=10, prompt_tokens_details=details) + public = litellm.cost_per_token(prompt_tokens=prompt, completion_tokens=10, usage_object=public_usage, **kwargs) + assert public == expected, (public, expected) + assert litellm.completion_cost(completion_response=litellm.ModelResponse(model=model, usage=public_usage), **kwargs) == raw.total + info = litellm.get_model_info(model=model, custom_llm_provider="openai") + shaped = n.price(info, usage, when, policy="sdk_tokens") + assert isinstance(shaped, n.Priced) + assert (shaped.input, shaped.output, shaped.total) == (raw.input, raw.output, raw.total) + assert n.has_token_prices(info, policy="sdk_tokens") is True +finally: + del litellm.model_cost[model] +assert json.dumps(row) == before +"#), Some(&locals), None).unwrap(); + }); + } + + #[rstest] + #[case::null_input(json!({"input_cost_per_token":1,"output_cost_per_token":2,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":null,"output_cost_per_token":4}]}), json!({"input_cost_per_token":10,"output_cost_per_token":10}), &["input_cost_per_token"], (0.0,40.0), true)] + #[case::unused_null_input(json!({"input_cost_per_token":1,"output_cost_per_token":2,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":null,"output_cost_per_token":4}]}), json!({"input_cost_per_token":0,"output_cost_per_token":10}), &[], (0.0,40.0), true)] + #[case::null_only_not_free(json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":null}]}), json!({"input_cost_per_token":10}), &["input_cost_per_token"], (0.0,0.0), false)] + #[case::null_output_no_flat_fallback(json!({"output_cost_per_token":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":null}]}), json!({"input_cost_per_token":10,"output_cost_per_token":10}), &["output_cost_per_token"], (10.0,0.0), true)] + #[case::absent_output_uses_flat(json!({"output_cost_per_token":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1}]}), json!({"input_cost_per_token":10,"output_cost_per_token":10}), &[], (10.0,90.0), true)] + #[case::zero_output_is_free(json!({"output_cost_per_token":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":0}]}), json!({"input_cost_per_token":10,"output_cost_per_token":10}), &[], (10.0,0.0), true)] + #[case::null_read_falls_back_input(json!({"cache_read_input_token_cost":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"cache_read_input_token_cost":null}]}), json!({"cache_read_input_token_cost":10}), &[], (10.0,0.0), true)] + #[case::null_write_falls_back_input(json!({"cache_creation_input_token_cost":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"cache_creation_input_token_cost":null}]}), json!({"cache_creation_input_token_cost":10}), &[], (10.0,0.0), true)] + #[case::null_ttl_falls_back_write(json!({"cache_creation_input_token_cost_above_1hr":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"cache_creation_input_token_cost":3,"cache_creation_input_token_cost_above_1hr":null}]}), json!({"cache_creation_input_token_cost_above_1hr":10}), &[], (30.0,0.0), true)] + #[case::null_ttl_falls_back_offpeak_write(json!({"cache_creation_input_token_cost_above_12hr":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"cache_creation_input_token_cost":3,"cache_creation_input_token_cost_above_12hr":null}],"off_peak_pricing":{"hours_utc":"00:00-01:00","cache_creation_input_token_cost":0}}), json!({"cache_creation_input_token_cost_above_12hr":10}), &[], (0.0,0.0), true)] + #[case::null_reasoning_uses_tier_output(json!({"output_cost_per_reasoning_token":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":2,"output_cost_per_reasoning_token":null}]}), json!({"output_cost_per_reasoning_token":10}), &[], (0.0,20.0), true)] + #[case::null_reasoning_without_tier_output_is_unknown(json!({"output_cost_per_token":8,"output_cost_per_reasoning_token":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_reasoning_token":null}]}), json!({"output_cost_per_reasoning_token":10}), &["output_cost_per_reasoning_token"], (0.0,0.0), true)] + #[case::null_output_for_reasoning_is_unknown(json!({"output_cost_per_token":8,"output_cost_per_reasoning_token":9,"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":null}]}), json!({"output_cost_per_reasoning_token":10}), &["output_cost_per_reasoning_token"], (0.0,0.0), true)] + #[case::null_cache_input_does_not_use_offpeak_input(json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":null}],"off_peak_pricing":{"hours_utc":"00:00-01:00","input_cost_per_token":2}}), json!({"cache_read_input_token_cost":10}), &["cache_read_input_token_cost"], (0.0,0.0), true)] + #[case::offpeak_supplies_null_input(json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":null}],"off_peak_pricing":{"hours_utc":"00:00-01:00","input_cost_per_token":2}}), json!({"input_cost_per_token":10}), &[], (20.0,0.0), true)] + #[case::offpeak_supplies_null_output(json!({"tiered_pricing":[{"range":[0,100],"input_cost_per_token":1,"output_cost_per_token":null}],"off_peak_pricing":{"hours_utc":"00:00-01:00","output_cost_per_token":2}}), json!({"output_cost_per_token":10}), &[], (0.0,20.0), true)] + fn sdk_nullable_tiers_preserve_unknown_and_fallback_boundaries( + #[from(interpreter)] _interpreter: (), + #[case] fields: Value, + #[case] quantities: Value, + #[case] missing: &[&str], + #[case] amounts: (f64, f64), + #[case] present: bool, + ) { + Python::attach(|py| { + let row = dict(py, fields); + row.set_item("litellm_provider", "openai").unwrap(); + let before: Value = from_py(row.as_any()).unwrap(); + let usage = UsageInput::new(&dict(py, quantities), 10, false, 0).unwrap(); + let result = price( + row.as_any(), + &usage, + &WhenInput::new(0, "standard", "online").unwrap(), + "sdk_tokens", + ) + .unwrap(); + let priced = match result { + PriceResult::Unpriced(unpriced) => { + assert!(!missing.is_empty()); + assert_eq!(unpriced.missing, missing); + unpriced.partial + } + PriceResult::Priced(priced) => { + assert!(missing.is_empty()); + Py::new(py, priced).unwrap() + } + PriceResult::Errors(_) => panic!("nullable fields must not reject valid rows"), + }; + let priced = priced.borrow(py); + assert_eq!((priced.input, priced.output), amounts); + assert_eq!(priced.total, amounts.0 + amounts.1); + let TokenPricePresence::Present(has_prices) = + has_token_prices(row.as_any(), "sdk_tokens").unwrap() + else { + panic!("invalid presence result") + }; + assert_eq!(has_prices, present); + assert_eq!(from_py::(row.as_any()).unwrap(), before); }); } diff --git a/litellm/rust_bridge/_native.pyi b/litellm/rust_bridge/_native.pyi index ebfa010c237..97771758180 100644 --- a/litellm/rust_bridge/_native.pyi +++ b/litellm/rust_bridge/_native.pyi @@ -248,6 +248,22 @@ class Unpriced: @property def partial(self) -> Priced: ... +@final +class SelectedRate: + @property + def requested_meter(self) -> str: ... + @property + def source_meter(self) -> str | None: ... + @property + def unit_price(self) -> float | None: ... + +@final +class PriceEvaluation: + @property + def pricing(self) -> Priced | Unpriced: ... + @property + def rates(self) -> list[SelectedRate]: ... + @overload def resolve_model( model_cost: dict[str, object], @@ -275,6 +291,9 @@ def registration_target( ) -> RegistrationTarget: ... def invalidate_model_cost_index() -> None: ... def model_info(model_cost: dict[str, object], key: str) -> ModelInfoView | RowErrors: ... +def has_token_prices( + row: dict[str, object], *, policy: Literal["generic", "sdk_tokens"] = "generic" +) -> bool | RowErrors: ... def price( row: dict[str, object], usage: UsageInput, @@ -282,6 +301,15 @@ def price( *, policy: Literal["generic", "sdk_tokens"] = "generic", ) -> Priced | Unpriced | RowErrors: ... +def price_with_rates( + row: dict[str, object], + usage: UsageInput, + when: WhenInput, + *, + policy: Literal["generic", "sdk_tokens"] = "generic", + project: Sequence[str] = (), + factors: Sequence[float] = (), +) -> PriceEvaluation | RowErrors: ... def trace_encode_error(message: str) -> bytes: ... @final @@ -484,6 +512,7 @@ __all__ = [ "NativeClickHouseSpendConfig", "NativeClickHouseSpendStorage", "NativeDiagnosticProcessor", + "PriceEvaluation", "PriceLine", "Priced", "ProcessReservedForForking", @@ -497,6 +526,7 @@ __all__ = [ "RowErrors", "RustBridgeDeclined", "RustUpstreamError", + "SelectedRate", "TokenCounter", "Tokenizer", "Unpriced", @@ -513,6 +543,7 @@ __all__ = [ "fetch_once", "fetch_with_retry", "gil_stats", + "has_token_prices", "invalidate_model_cost_index", "messages", "model_info", @@ -521,6 +552,7 @@ __all__ = [ "ocr_health_check_document", "ocr_passthrough_response", "price", + "price_with_rates", "process_state_started", "registration_target", "reserve_process_for_forking",