返回 CodeWhale
hand_pricing.rs
根目录 / crates / models / src / hand_pricing.rs
1 use chrono::{DateTime, Datelike, FixedOffset, TimeZone, Timelike, Utc, Weekday};
2 use codewhale_config::ProviderKind;
3 use codewhale_config::pricing::{Currency, OfferingPricing, PricingProvenance};
4
5 /// How a hand-sourced row bills cache-creation (cache-write) tokens.
6 ///
7 /// The distinction matters because "no separate write rate published" and
8 /// "documented to cost the same as ordinary input" are different facts that used
9 /// to collapse onto the same `None`. Folding the unknown case into the input
10 /// rate invents a price; this enum keeps the invention impossible (#4318).
11 #[derive(Debug, Clone, Copy, PartialEq)]
12 pub enum CacheWritePolicy {
13 /// The provider publishes a distinct cache-creation rate (per million).
14 Rate(f64),
15 /// Provider documentation states that cache creation carries **no separate
16 /// charge** beyond the ordinary cache-miss input rate, so the miss rate is
17 /// the published write rate rather than a substitute for a missing one.
18 ///
19 /// The `&'static str` is the documentation receipt this claim rests on, so
20 /// the policy is auditable instead of asserted.
21 DocumentedAsInputRate(&'static str),
22 /// No published cache-write rate was found for this row. A turn that
23 /// actually wrote to cache fails closed rather than being billed at a rate
24 /// CodeWhale made up.
25 Unpublished,
26 }
27
28 /// DeepSeek's context-caching docs: tokens that miss the cache are billed once
29 /// at the cache-miss rate and writing them into the cache costs nothing extra.
30 /// <https://api-docs.deepseek.com/guides/kv_cache>
31 pub const DEEPSEEK_CACHE_WRITE_IS_FREE: &str = "deepseek-kv-cache-no-write-charge";
32
33 impl CacheWritePolicy {
34 /// The rate to bill cache-write tokens at, given the row's input rate.
35 ///
36 /// `None` means the row cannot price cache-write tokens at all.
37 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 /// Per-million-token pricing for a model.
47 #[derive(Debug, Clone, Copy)]
48 pub 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 /// How cache-creation tokens are billed on this row.
53 pub cache_write: CacheWritePolicy,
54 }
55
56 /// Per-million-token pricing for a model.
57 #[derive(Debug, Clone, Copy)]
58 pub struct ModelPricing {
59 pub usd: CurrencyPricing,
60 pub cny: Option<CurrencyPricing>,
61 }
62
63 pub 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 // NVIDIA NIM-hosted DeepSeek uses NVIDIA's catalog/account terms, not
67 // DeepSeek Platform pricing. Avoid showing misleading DeepSeek costs.
68 return None;
69 }
70 if lower == "claude-sonnet-5" {
71 // Resolved ahead of the catalog through the recorded-time helper so
72 // the first-party Anthropic override path (`hand_priced_audit`)
73 // and this metadata lookup stay one contract (see
74 // `claude_sonnet_5_pricing`).
75 return Some(claude_sonnet_5_pricing(now));
76 }
77 if let Some(pricing) = known_pricing_for_model(&lower) {
78 return Some(pricing);
79 }
80 // A new or expiring model ID does not inherit a neighboring model's
81 // rates. Keep this metadata lookup as exact as the billing route owner.
82 deepseek_time_aware_pricing(&lower, now)
83 }
84
85 pub 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
96 fn 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
116 /// A USD row whose provider publishes input/cache-read/output rates but **no**
117 /// cache-creation rate. Cache-write tokens on such a row are unpriced, not free
118 /// and not silently charged at the input rate (#4318).
119 pub 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
132 fn 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
146 pub 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
163 pub const MINIMAX_M3_LONG_CONTEXT_THRESHOLD: u32 = 512_000;
164
165 pub const GROK_4_6_LONG_CONTEXT_THRESHOLD: u32 = 200_000;
166
167 pub 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
175 pub 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
182 /// xAI Grok standard-tier rates (cache-read, input, output per 1M) and the
183 /// doubled tier once a prompt reaches 200K tokens. Verified 2026-08-17 against
184 /// the model pages, whose embedded price tables carry both the standard and
185 /// `LongContext` columns at exactly 2x:
186 /// - <https://docs.x.ai/docs/models/grok-4.7>: 0.50 / 2.00 / 6.00 (verified
187 /// 2026-09-23: $4.00 / $1.00 / $12.00 at or above 200K)
188 /// - <https://docs.x.ai/docs/models/grok-4.6>: 0.50 / 2.00 / 6.00
189 /// - <https://docs.x.ai/docs/models/grok-4.5>: 0.30 / 2.00 / 6.00
190 /// - <https://docs.x.ai/docs/models/grok-4.3>: 0.20 / 1.25 / 2.50
191 pub 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
206 pub 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
213 /// Claude Sonnet 5 pricing (<https://platform.claude.com/docs/en/about-claude/pricing>,
214 /// re-verified 2026-08-17): 2.00 / 10.00 (cache-read 0.20, 5m cache-write
215 /// 2.50) is now the standard price. Anthropic's pricing page states the
216 /// previously scheduled increase to 3.00 / 15.00 on 2026-09-01 "will not
217 /// occur" (release notes, 2026-08-10), so the former time-windowed flip is
218 /// gone; the recorded-time signature is kept so callers that price turns at
219 /// their recorded time (usage aggregation) keep one contract for
220 /// every first-party time-aware row.
221 fn claude_sonnet_5_pricing(_now: DateTime<Utc>) -> ModelPricing {
222 usd_pricing_with_write(0.20, 2.00, 10.00, 2.50)
223 }
224
225 /// DeepSeek publishes only cache-hit and cache-miss input rates *because* its
226 /// context cache charges nothing extra to write: a token that misses the cache
227 /// is billed once at the miss rate and is cached as a side effect. That makes
228 /// the miss rate the documented write rate, not a stand-in for a missing one.
229 ///
230 /// Peak/off-peak tiers (verified against
231 /// <https://api-docs.deepseek.com/quick_start/pricing> on 2026-08-17):
232 /// off-peak rates are half the peak rates, and peak hours are 01:00–04:00
233 /// and 06:00–10:00 UTC (half-open). From 00:00 Beijing time on 2026-08-23 the
234 /// whole of Saturday and Sunday bills off-peak, peak hours included. Each turn
235 /// resolves its tier from its own recorded time, mirroring
236 /// `claude_sonnet_5_pricing`'s time-aware precedent.
237 fn deepseek_peak_hour(hour_utc: u32) -> bool {
238 (1..4).contains(&hour_utc) || (6..10).contains(&hour_utc)
239 }
240
241 /// Beijing time, the zone DeepSeek states its weekend rule in. China has run a
242 /// fixed UTC+08:00 with no daylight saving since 1991, so a fixed offset is
243 /// exact here and needs no tzdata on the host.
244 fn deepseek_billing_offset() -> FixedOffset {
245 FixedOffset::east_opt(8 * 3600).expect("+08:00 is a valid UTC offset")
246 }
247
248 /// The instant the weekend-wide off-peak rule takes effect: 00:00 Beijing time
249 /// on Sunday 2026-08-23, which is 2026-08-22T16:00Z.
250 fn 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
258 /// Whether `now` falls on a Beijing-time Saturday or Sunday with the weekend-wide
259 /// off-peak rule already in force.
260 ///
261 /// The weekend is bounded in Beijing time, so it runs 16:00Z Friday to 16:00Z
262 /// Sunday; `now.weekday()` taken in UTC covers a different 48 hours. Both
263 /// spellings agree on today's tiers, because the peak windows sit entirely
264 /// outside the 16 hours they disagree over. This one keeps agreeing if the
265 /// windows move.
266 fn 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
274 /// Whether a turn recorded at `now` is billed at DeepSeek's peak tier.
275 pub fn deepseek_is_peak(now: DateTime<Utc>) -> bool {
276 !deepseek_weekend_off_peak(now) && deepseek_peak_hour(now.hour())
277 }
278
279 fn deepseek_v4_pro_pricing(now: DateTime<Utc>) -> ModelPricing {
280 // September 11 vendor reversal: Pro remains available at its own rates.
281 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
308 /// DeepSeek V4.1 Flash, shipped as the unversioned id `deepseek-flash`.
309 ///
310 /// Rates and effective time are the vendor's own 2026-09-10 notice, not a
311 /// relay: cache hit $0.003, cache miss $0.15, output $0.60 per 1M off-peak,
312 /// doubling at peak, effective 04:00 UTC on 2026-09-10.
313 /// V4 Pro remains available at its own rates after the September 11 reversal.
314 ///
315 /// CNY rates are the vendor's own Chinese-language notice: cache hit 0.02 元,
316 /// cache miss 1 元, output 4 元 off-peak, doubling at peak. Taken from the
317 /// published table rather than converted from USD — a converted rate would be
318 /// a receipt the vendor never issued.
319 ///
320 /// That notice states the peak windows in Beijing time (Mon-Fri 09:00-12:00 and
321 /// 14:00-18:00), which is UTC+8 and therefore exactly the 01:00-04:00 and
322 /// 06:00-10:00 UTC the English notice gives. Both agree, so `deepseek_is_peak`
323 /// needs no change.
324 fn 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
352 pub 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
358 fn 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
389 pub 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
466 pub 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 // Hosted Fireworks / OpenCode Zen rates are provider-owned docs rows, not
473 // first-party DeepSeek's $0.0028 cache-hit card and not Models.dev.
474 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 // `deepseek-flash` is V4.1 Flash on the first-party API. Only the
483 // first-party family gains it: third-party hosts below keep their
484 // own published tables and must not be assumed to serve a model
485 // just because DeepSeek does.
486 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 // GLM-5.3 is deliberately absent: this allowlist declares that Z.ai
522 // owns a *hand-written price row* for the model, and no GLM-5.3 rate
523 // has been published. An absent price is honest; an owned-but-empty
524 // row is not. See `glm_5_3_has_no_hardcoded_price` below.
525 // GLM-5.3-Flash *does* have a published USD list (2026-08-26).
526 ProviderKind::Zai => matches!(
527 model_lower.as_str(),
528 "glm-5.1" | "glm-5.2" | "glm-5.3-flash" | "glm-5-turbo"
529 ),
530 // `k3` (Kimi Code membership) is deliberately absent: it is quota
531 // billed and must never inherit the direct-platform kimi-k3 rate.
532 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 // Every Muse tier owns a hand-written row the same way 1.1 does (see
556 // `pricing_for_model_at`), so `DEFAULT_META_MODEL` (1.3) always has a
557 // provider-owned fallback row.
558 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 // Deployment-style ids (Fireworks account prefix, OpenCode Zen
568 // gateway) have no Models.dev cost fields. When the live control
569 // plane 503s, these bundled family rates keep the session priced
570 // instead of `unverified_live_pricing` forever (#5241).
571 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
598 /// Fireworks serverless Standard rates (2026-08-15 audit).
599 /// <https://docs.fireworks.ai/serverless/pricing>
600 ///
601 /// Cache-write is unpublished on that table. Do not inherit first-party
602 /// DeepSeek's $0.0028 cache-hit card — Fireworks publishes $0.028.
603 fn 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 // kimi-k3 stays unpriced until Fireworks publishes a rate for it
610 // (see `fireworks_and_zen_flash_use_bundled_family_rates`).
611 _ => None,
612 }
613 }
614
615 fn 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
622 /// OpenCode Zen PAYG rates (2026-08-15 audit).
623 /// <https://opencode.ai/docs/zen/>
624 ///
625 /// Cached write is unpublished (`-` on the Zen table). Flash cache-read is
626 /// $0.028, not first-party DeepSeek's $0.0028.
627 fn 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
636 fn hosted_deepseek_v4_flash_standard_pricing() -> ModelPricing {
637 usd_only_pricing(0.028, 0.14, 0.28)
638 }
639
640 fn hosted_deepseek_v4_pro_standard_pricing() -> ModelPricing {
641 usd_only_pricing(0.145, 1.74, 3.48)
642 }
643
644 pub 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)]
659 mod 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 // All four instants are off-peak by the hour, so `deepseek_is_peak`
673 // cannot tell them apart today. Pinning the predicate keeps the 16:00Z
674 // edges right if the peak windows ever move.
675 let cases = [
676 (Utc.with_ymd_and_hms(2026, 8, 28, 15, 0, 0).unwrap(), false), // Fri 23:00 Beijing
677 (Utc.with_ymd_and_hms(2026, 8, 28, 16, 0, 0).unwrap(), true), // Sat 00:00 Beijing
678 (Utc.with_ymd_and_hms(2026, 8, 30, 15, 0, 0).unwrap(), true), // Sun 23:00 Beijing
679 (Utc.with_ymd_and_hms(2026, 8, 30, 16, 0, 0).unwrap(), false), // Mon 00:00 Beijing
680 ];
681 for (at, weekend) in cases {
682 assert_eq!(deepseek_weekend_off_peak(at), weekend, "weekend at {at}");
683 }
684 }
685 }
686
686 lines RUST