1use chrono::{DateTime, Datelike, FixedOffset, TimeZone, Timelike, Utc, Weekday};
2use codewhale_config::ProviderKind;
3use codewhale_config::pricing::{Currency, OfferingPricing, PricingProvenance};
4
5#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum CacheWritePolicy {
13 Rate(f64),
15 DocumentedAsInputRate(&'static str),
22 Unpublished,
26}
27
28pub const DEEPSEEK_CACHE_WRITE_IS_FREE: &str = "deepseek-kv-cache-no-write-charge";
32
33impl CacheWritePolicy {
34 pub fn rate(self, input_cache_miss_per_million: f64) -> Option<f64> {
38 match self {
39 Self::Rate(rate) => Some(rate),
40 Self::DocumentedAsInputRate(_) => Some(input_cache_miss_per_million),
41 Self::Unpublished => None,
42 }
43 }
44}
45
46#[derive(Debug, Clone, Copy)]
48pub struct CurrencyPricing {
49 pub input_cache_hit_per_million: f64,
50 pub input_cache_miss_per_million: f64,
51 pub output_per_million: f64,
52 pub cache_write: CacheWritePolicy,
54}
55
56#[derive(Debug, Clone, Copy)]
58pub struct ModelPricing {
59 pub usd: CurrencyPricing,
60 pub cny: Option<CurrencyPricing>,
61}
62
63pub fn pricing_for_model_at(model: &str, now: DateTime<Utc>) -> Option<ModelPricing> {
64 let lower = model.to_lowercase();
65 if lower.starts_with("deepseek-ai/") {
66 return None;
69 }
70 if lower == "claude-sonnet-5" {
71 return Some(claude_sonnet_5_pricing(now));
76 }
77 if let Some(pricing) = known_pricing_for_model(&lower) {
78 return Some(pricing);
79 }
80 deepseek_time_aware_pricing(&lower, now)
83}
84
85pub fn deepseek_time_aware_pricing(model_lower: &str, now: DateTime<Utc>) -> Option<ModelPricing> {
86 match model_lower {
87 "deepseek-v4-pro" => Some(deepseek_v4_pro_pricing(now)),
88 "deepseek-v4-flash" | "deepseek-flash" => Some(deepseek_v4_flash_pricing(now)),
89 "deepseek-v4-flash-vision-exp" => {
90 (now >= deepseek_flash_effective_from()).then(|| deepseek_flash_pricing(now))
91 }
92 _ => None,
93 }
94}
95
96fn known_pricing_for_model(model_lower: &str) -> Option<ModelPricing> {
97 let reviewed = codewhale_config::catalog::reviewed::bundled_reviewed();
98 if let Some(policy) = reviewed.reference_price_policies.get(model_lower) {
99 return match policy.as_str() {
100 "grok" => grok_tiered_pricing(model_lower, false),
101 "minimax_m3" => Some(minimax_m3_standard_pricing(false)),
102 _ => None,
103 };
104 }
105 reviewed.reference_prices.get(model_lower).map(|row| {
106 usd_pricing(
107 row.cache_read,
108 row.input,
109 row.output,
110 row.cache_write
111 .map_or(CacheWritePolicy::Unpublished, CacheWritePolicy::Rate),
112 )
113 })
114}
115
116pub fn usd_only_pricing(
120 input_cache_hit_per_million: f64,
121 input_cache_miss_per_million: f64,
122 output_per_million: f64,
123) -> ModelPricing {
124 usd_pricing(
125 input_cache_hit_per_million,
126 input_cache_miss_per_million,
127 output_per_million,
128 CacheWritePolicy::Unpublished,
129 )
130}
131
132fn usd_pricing_with_write(
133 input_cache_hit_per_million: f64,
134 input_cache_miss_per_million: f64,
135 output_per_million: f64,
136 cache_write_per_million: f64,
137) -> ModelPricing {
138 usd_pricing(
139 input_cache_hit_per_million,
140 input_cache_miss_per_million,
141 output_per_million,
142 CacheWritePolicy::Rate(cache_write_per_million),
143 )
144}
145
146pub fn usd_pricing(
147 input_cache_hit_per_million: f64,
148 input_cache_miss_per_million: f64,
149 output_per_million: f64,
150 cache_write: CacheWritePolicy,
151) -> ModelPricing {
152 ModelPricing {
153 usd: CurrencyPricing {
154 input_cache_hit_per_million,
155 input_cache_miss_per_million,
156 output_per_million,
157 cache_write,
158 },
159 cny: None,
160 }
161}
162
163pub const MINIMAX_M3_LONG_CONTEXT_THRESHOLD: u32 = 512_000;
164
165pub const GROK_4_6_LONG_CONTEXT_THRESHOLD: u32 = 200_000;
166
167pub fn minimax_m3_standard_pricing(long_context: bool) -> ModelPricing {
168 if long_context {
169 usd_only_pricing(0.12, 0.60, 2.40)
170 } else {
171 usd_only_pricing(0.06, 0.30, 1.20)
172 }
173}
174
175pub fn is_minimax_m3(model: &str) -> bool {
176 matches!(
177 model.trim().to_ascii_lowercase().as_str(),
178 "minimax-m3" | "minimax/minimax-m3"
179 )
180}
181
182pub fn grok_tiered_pricing(model_lower: &str, long_context: bool) -> Option<ModelPricing> {
192 let (cache_read, input, output) = match model_lower {
193 "grok-4.7" | "grok-4.6" => (0.50, 2.00, 6.00),
194 "grok-4.5" => (0.30, 2.00, 6.00),
195 "grok-4.3" => (0.20, 1.25, 2.50),
196 _ => return None,
197 };
198 let multiplier = if long_context { 2.0 } else { 1.0 };
199 Some(usd_only_pricing(
200 cache_read * multiplier,
201 input * multiplier,
202 output * multiplier,
203 ))
204}
205
206pub fn is_grok_tiered(model: &str) -> bool {
207 matches!(
208 model.trim().to_ascii_lowercase().as_str(),
209 "grok-4.7" | "grok-4.6" | "grok-4.5" | "grok-4.3"
210 )
211}
212
213fn claude_sonnet_5_pricing(_now: DateTime<Utc>) -> ModelPricing {
222 usd_pricing_with_write(0.20, 2.00, 10.00, 2.50)
223}
224
225fn deepseek_peak_hour(hour_utc: u32) -> bool {
238 (1..4).contains(&hour_utc) || (6..10).contains(&hour_utc)
239}
240
241fn deepseek_billing_offset() -> FixedOffset {
245 FixedOffset::east_opt(8 * 3600).expect("+08:00 is a valid UTC offset")
246}
247
248fn deepseek_weekend_off_peak_from() -> DateTime<Utc> {
251 deepseek_billing_offset()
252 .with_ymd_and_hms(2026, 8, 23, 0, 0, 0)
253 .single()
254 .expect("2026-08-23 00:00 exists in a fixed offset")
255 .with_timezone(&Utc)
256}
257
258fn deepseek_weekend_off_peak(now: DateTime<Utc>) -> bool {
267 now >= deepseek_weekend_off_peak_from()
268 && matches!(
269 now.with_timezone(&deepseek_billing_offset()).weekday(),
270 Weekday::Sat | Weekday::Sun
271 )
272}
273
274pub fn deepseek_is_peak(now: DateTime<Utc>) -> bool {
276 !deepseek_weekend_off_peak(now) && deepseek_peak_hour(now.hour())
277}
278
279fn deepseek_v4_pro_pricing(now: DateTime<Utc>) -> ModelPricing {
280 let peak = deepseek_is_peak(now);
282 let (hit, miss, out) = if peak {
283 (0.044, 1.32, 3.96)
284 } else {
285 (0.022, 0.66, 1.98)
286 };
287 let (cny_hit, cny_miss, cny_out) = if peak {
288 (0.30, 9.0, 27.0)
289 } else {
290 (0.15, 4.5, 13.5)
291 };
292 ModelPricing {
293 usd: CurrencyPricing {
294 input_cache_hit_per_million: hit,
295 input_cache_miss_per_million: miss,
296 output_per_million: out,
297 cache_write: CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE),
298 },
299 cny: Some(CurrencyPricing {
300 input_cache_hit_per_million: cny_hit,
301 input_cache_miss_per_million: cny_miss,
302 output_per_million: cny_out,
303 cache_write: CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE),
304 }),
305 }
306}
307
308fn deepseek_flash_pricing(now: DateTime<Utc>) -> ModelPricing {
325 let peak = deepseek_is_peak(now);
326 let (hit, miss, out) = if peak {
327 (0.006, 0.30, 1.20)
328 } else {
329 (0.003, 0.15, 0.60)
330 };
331 let (cny_hit, cny_miss, cny_out) = if peak {
332 (0.04, 2.0, 8.0)
333 } else {
334 (0.02, 1.0, 4.0)
335 };
336 ModelPricing {
337 usd: CurrencyPricing {
338 input_cache_hit_per_million: hit,
339 input_cache_miss_per_million: miss,
340 output_per_million: out,
341 cache_write: CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE),
342 },
343 cny: Some(CurrencyPricing {
344 input_cache_hit_per_million: cny_hit,
345 input_cache_miss_per_million: cny_miss,
346 output_per_million: cny_out,
347 cache_write: CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE),
348 }),
349 }
350}
351
352pub fn deepseek_flash_effective_from() -> DateTime<Utc> {
353 Utc.with_ymd_and_hms(2026, 9, 10, 4, 0, 0)
354 .single()
355 .expect("2026-09-10T04:00Z is a valid UTC instant")
356}
357
358fn deepseek_v4_flash_pricing(now: DateTime<Utc>) -> ModelPricing {
359 if now >= deepseek_flash_effective_from() {
360 return deepseek_flash_pricing(now);
361 }
362 let peak = deepseek_is_peak(now);
363 let (hit, miss, out) = if peak {
364 (0.014, 0.44, 1.32)
365 } else {
366 (0.007, 0.22, 0.66)
367 };
368 let (cny_hit, cny_miss, cny_out) = if peak {
369 (0.10, 3.0, 9.0)
370 } else {
371 (0.05, 1.5, 4.5)
372 };
373 ModelPricing {
374 usd: CurrencyPricing {
375 input_cache_hit_per_million: hit,
376 input_cache_miss_per_million: miss,
377 output_per_million: out,
378 cache_write: CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE),
379 },
380 cny: Some(CurrencyPricing {
381 input_cache_hit_per_million: cny_hit,
382 input_cache_miss_per_million: cny_miss,
383 output_per_million: cny_out,
384 cache_write: CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE),
385 }),
386 }
387}
388
389pub fn provider_owned_hand_quote_rows(
390 provider: ProviderKind,
391 model: &str,
392 recorded_at: DateTime<Utc>,
393) -> Option<(OfferingPricing, Option<OfferingPricing>)> {
394 let pricing = provider_owned_hand_pricing_at(provider, model, recorded_at)?;
395 let mut primary = currency_offering_pricing(pricing.usd, Currency::Usd);
396 let mut secondary = pricing
397 .cny
398 .map(|row| currency_offering_pricing(row, Currency::Cny));
399 let tier = if provider == ProviderKind::Xai && is_grok_tiered(model) {
400 Some((
401 u64::from(GROK_4_6_LONG_CONTEXT_THRESHOLD),
402 true,
403 grok_tiered_pricing(&model.to_ascii_lowercase(), true)?,
404 ))
405 } else if matches!(
406 provider,
407 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
408 ) && is_minimax_m3(model)
409 {
410 Some((
411 u64::from(MINIMAX_M3_LONG_CONTEXT_THRESHOLD),
412 false,
413 minimax_m3_standard_pricing(true),
414 ))
415 } else {
416 None
417 };
418 if let Some((size, inclusive, higher)) = tier {
419 primary
420 .context_tiers
421 .push(codewhale_config::models_dev::ModelsDevCostTier {
422 tier: codewhale_config::models_dev::ModelsDevContextTier {
423 kind: "context".into(),
424 size,
425 },
426 cost: currency_offering_pricing(higher.usd, Currency::Usd).cost_structure(),
427 });
428 primary.context_tiers_inclusive = inclusive;
429 if let Some(row) = secondary.as_mut()
430 && let Some(higher) = higher.cny
431 {
432 row.context_tiers
433 .push(codewhale_config::models_dev::ModelsDevCostTier {
434 tier: codewhale_config::models_dev::ModelsDevContextTier {
435 kind: "context".into(),
436 size,
437 },
438 cost: currency_offering_pricing(higher, Currency::Cny).cost_structure(),
439 });
440 row.context_tiers_inclusive = inclusive;
441 }
442 }
443 for row in std::iter::once(&mut primary).chain(secondary.iter_mut()) {
444 row.provider = provider.as_str().into();
445 row.wire_model_id = model.into();
446 row.source_ref = Some(
447 match provider {
448 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic => {
449 "https://api-docs.deepseek.com/quick_start/pricing"
450 }
451 ProviderKind::Xai => "https://docs.x.ai/docs/models",
452 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic => {
453 "https://platform.minimax.io/docs/guides/pricing-paygo"
454 }
455 ProviderKind::Anthropic => {
456 "https://platform.claude.com/docs/en/about-claude/pricing"
457 }
458 _ => "codewhale:reviewed-provider-price",
459 }
460 .into(),
461 );
462 }
463 Some((primary, secondary))
464}
465
466pub fn provider_owned_hand_pricing_at(
467 provider: ProviderKind,
468 model: &str,
469 recorded_at: DateTime<Utc>,
470) -> Option<ModelPricing> {
471 let model_lower = model.trim().to_ascii_lowercase();
472 if provider == ProviderKind::Fireworks {
475 return fireworks_bundled_fallback_pricing(&model_lower);
476 }
477 if provider == ProviderKind::OpencodeZen {
478 return opencode_zen_bundled_fallback_pricing(&model_lower);
479 }
480 let provider_owns_row = match provider {
481 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic => {
482 matches!(
487 model_lower.as_str(),
488 "deepseek-v4-pro"
489 | "deepseek-v4-flash"
490 | "deepseek-v4-flash-vision-exp"
491 | "deepseek-flash"
492 )
493 }
494 ProviderKind::Openai => matches!(
495 model_lower.as_str(),
496 "gpt-5-codex"
497 | "gpt-5.3-codex"
498 | "gpt-5.5"
499 | "gpt-5.5-pro"
500 | "gpt-5.6"
501 | "gpt-5.6-sol"
502 | "gpt-5.6-terra"
503 | "gpt-5.6-luna"
504 | "gpt-6-sol"
505 | "gpt-6.1-sol"
506 | "gpt-6-luna"
507 ),
508 ProviderKind::Anthropic => matches!(
509 model_lower.as_str(),
510 "claude-opus-4-8"
511 | "claude-sonnet-4-6"
512 | "claude-haiku-4-5"
513 | "claude-fable-5"
514 | "claude-sonnet-5"
515 | "claude-opus-5"
516 | "claude-opus-5-5"
517 | "claude-sonnet-5-5"
518 | "claude-fable-5-1"
519 ),
520 ProviderKind::Xai => is_grok_tiered(&model_lower),
521 ProviderKind::Zai => matches!(
527 model_lower.as_str(),
528 "glm-5.1" | "glm-5.2" | "glm-5.3-flash" | "glm-5-turbo"
529 ),
530 ProviderKind::Moonshot => matches!(
533 model_lower.as_str(),
534 "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k2.7-code-highspeed" | "kimi-k3"
535 ),
536 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic => matches!(
537 model_lower.as_str(),
538 "minimax-m3" | "minimax-m2.7" | "minimax-m2.7-highspeed"
539 ),
540 ProviderKind::Mistral => matches!(
541 model_lower.as_str(),
542 "mistral-medium-latest"
543 | "mistral-medium-3-5"
544 | "mistral-medium-3.5"
545 | "mistral-medium-2604"
546 | "mistral-large-latest"
547 | "mistral-large-2512"
548 | "mistral-small-latest"
549 | "mistral-small-2603"
550 | "mistral-code-latest"
551 | "codestral-latest"
552 | "codestral"
553 ),
554 ProviderKind::Arcee => model_lower == "trinity-large-thinking",
555 ProviderKind::Meta => matches!(
559 model_lower.as_str(),
560 "muse-spark-1.1"
561 | "muse-spark-1.2"
562 | "muse-spark-1.2-contributor"
563 | "muse-spark-1.3"
564 | "muse-spark-1.3-contributor"
565 | "muse-wonder-1.0"
566 ),
567 ProviderKind::Fireworks => {
572 let bare = model_lower
573 .strip_prefix("accounts/fireworks/models/")
574 .unwrap_or(model_lower.as_str());
575 matches!(bare, "deepseek-v4-flash" | "deepseek-v4-pro")
576 }
577 ProviderKind::OpencodeZen => {
578 matches!(
579 model_lower.as_str(),
580 "deepseek-v4-flash" | "deepseek-v4-pro"
581 )
582 }
583 _ => false,
584 };
585 let lookup = if provider == ProviderKind::Fireworks {
586 model_lower
587 .strip_prefix("accounts/fireworks/models/")
588 .unwrap_or(model_lower.as_str())
589 .to_string()
590 } else {
591 model_lower
592 };
593 provider_owns_row
594 .then(|| pricing_for_model_at(&lookup, recorded_at))
595 .flatten()
596}
597
598fn fireworks_bundled_fallback_pricing(model_lower: &str) -> Option<ModelPricing> {
604 match fireworks_deployment_id(model_lower) {
605 "deepseek-flash" | "deepseek-v4-flash" | "deepseek-v4-flash-0731" => {
606 Some(hosted_deepseek_v4_flash_standard_pricing())
607 }
608 "deepseek-v4-pro" => Some(hosted_deepseek_v4_pro_standard_pricing()),
609 _ => None,
612 }
613}
614
615fn fireworks_deployment_id(model_lower: &str) -> &str {
616 model_lower
617 .strip_prefix("accounts/fireworks/models/")
618 .or_else(|| model_lower.strip_prefix("accounts/fireworks/routers/"))
619 .unwrap_or(model_lower)
620}
621
622fn opencode_zen_bundled_fallback_pricing(model_lower: &str) -> Option<ModelPricing> {
628 match model_lower {
629 "deepseek-v4-flash" | "deepseek-v4-flash-0731" => {
630 Some(hosted_deepseek_v4_flash_standard_pricing())
631 }
632 _ => None,
633 }
634}
635
636fn hosted_deepseek_v4_flash_standard_pricing() -> ModelPricing {
637 usd_only_pricing(0.028, 0.14, 0.28)
638}
639
640fn hosted_deepseek_v4_pro_standard_pricing() -> ModelPricing {
641 usd_only_pricing(0.145, 1.74, 3.48)
642}
643
644pub fn currency_offering_pricing(pricing: CurrencyPricing, currency: Currency) -> OfferingPricing {
645 OfferingPricing {
646 currency,
647 input_per_million: Some(pricing.input_cache_miss_per_million),
648 output_per_million: Some(pricing.output_per_million),
649 cache_read_per_million: Some(pricing.input_cache_hit_per_million),
650 cache_write_per_million: pricing
651 .cache_write
652 .rate(pricing.input_cache_miss_per_million),
653 provenance: PricingProvenance::ProviderDocs,
654 ..Default::default()
655 }
656}
657
658#[cfg(test)]
659mod tests {
660 use super::*;
661
662 #[test]
663 fn deepseek_peak_window_is_half_open_on_utc_hours() {
664 for hour in 0..24 {
665 let expected = matches!(hour, 1..=3 | 6..=9);
666 assert_eq!(deepseek_peak_hour(hour), expected, "hour {hour}");
667 }
668 }
669
670 #[test]
671 fn deepseek_weekend_edges_are_bounded_in_beijing_time_not_utc() {
672 let cases = [
676 (Utc.with_ymd_and_hms(2026, 8, 28, 15, 0, 0).unwrap(), false), (Utc.with_ymd_and_hms(2026, 8, 28, 16, 0, 0).unwrap(), true), (Utc.with_ymd_and_hms(2026, 8, 30, 15, 0, 0).unwrap(), true), (Utc.with_ymd_and_hms(2026, 8, 30, 16, 0, 0).unwrap(), false), ];
681 for (at, weekend) in cases {
682 assert_eq!(deepseek_weekend_off_peak(at), weekend, "weekend at {at}");
683 }
684 }
685}