Skip to main content

lean_ctx/core/gain/
model_pricing.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
5pub struct ModelCost {
6    pub input_per_m: f64,
7    pub output_per_m: f64,
8    pub cache_write_per_m: f64,
9    pub cache_read_per_m: f64,
10}
11
12impl ModelCost {
13    pub fn estimate_usd(&self, input: u64, output: u64, cache_write: u64, cache_read: u64) -> f64 {
14        (input as f64 / 1_000_000.0 * self.input_per_m)
15            + (output as f64 / 1_000_000.0 * self.output_per_m)
16            + (cache_write as f64 / 1_000_000.0 * self.cache_write_per_m)
17            + (cache_read as f64 / 1_000_000.0 * self.cache_read_per_m)
18    }
19}
20
21#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
22pub enum PricingMatchKind {
23    Exact,
24    Alias,
25    Heuristic,
26    Fallback,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct ModelQuote {
31    pub model_key: String,
32    pub cost: ModelCost,
33    pub match_kind: PricingMatchKind,
34}
35
36#[derive(Debug, Clone)]
37pub struct ModelPricing {
38    models: HashMap<String, ModelCost>,
39}
40
41impl ModelPricing {
42    pub fn load() -> Self {
43        let mut p = Self::embedded();
44        p.apply_env_override();
45        p
46    }
47
48    pub fn embedded() -> Self {
49        let mut models: HashMap<String, ModelCost> = HashMap::new();
50
51        // Anthropic pricing — source: https://platform.claude.com/docs/en/about-claude/pricing
52        // (June 2026). One entry per price tier; the 4.5 keys cover the whole
53        // 4.5–4.8 generation since Anthropic prices them identically.
54        models.insert(
55            "claude-fable-5".to_string(),
56            ModelCost {
57                input_per_m: 10.00,
58                output_per_m: 50.00,
59                cache_write_per_m: 12.50,
60                cache_read_per_m: 1.00,
61            },
62        );
63        models.insert(
64            "claude-opus-4.5".to_string(),
65            ModelCost {
66                input_per_m: 5.00,
67                output_per_m: 25.00,
68                cache_write_per_m: 6.25,
69                cache_read_per_m: 0.50,
70            },
71        );
72        models.insert(
73            "claude-sonnet-4.5".to_string(),
74            ModelCost {
75                input_per_m: 3.00,
76                output_per_m: 15.00,
77                cache_write_per_m: 3.75,
78                cache_read_per_m: 0.30,
79            },
80        );
81        models.insert(
82            "claude-haiku-4.5".to_string(),
83            ModelCost {
84                input_per_m: 1.00,
85                output_per_m: 5.00,
86                cache_write_per_m: 1.25,
87                cache_read_per_m: 0.10,
88            },
89        );
90        // Legacy Claude 3.x tiers (still seen in older configs/logs).
91        models.insert(
92            "claude-3.5-sonnet".to_string(),
93            ModelCost {
94                input_per_m: 3.00,
95                output_per_m: 15.00,
96                cache_write_per_m: 3.75,
97                cache_read_per_m: 0.30,
98            },
99        );
100        models.insert(
101            "claude-3-opus".to_string(),
102            ModelCost {
103                input_per_m: 15.00,
104                output_per_m: 75.00,
105                cache_write_per_m: 18.75,
106                cache_read_per_m: 1.50,
107            },
108        );
109        models.insert(
110            "claude-3-haiku".to_string(),
111            ModelCost {
112                input_per_m: 0.25,
113                output_per_m: 1.25,
114                cache_write_per_m: 0.30,
115                cache_read_per_m: 0.03,
116            },
117        );
118
119        // OpenAI API pricing (Flagship) — source: https://openai.com/api/pricing/
120        models.insert(
121            "gpt-5.4".to_string(),
122            ModelCost {
123                input_per_m: 2.50,
124                output_per_m: 15.00,
125                cache_write_per_m: 2.50,
126                cache_read_per_m: 0.25,
127            },
128        );
129        models.insert(
130            "gpt-5.4-mini".to_string(),
131            ModelCost {
132                input_per_m: 0.75,
133                output_per_m: 4.50,
134                cache_write_per_m: 0.75,
135                cache_read_per_m: 0.075,
136            },
137        );
138        models.insert(
139            "gpt-5.4-nano".to_string(),
140            ModelCost {
141                input_per_m: 0.20,
142                output_per_m: 1.25,
143                cache_write_per_m: 0.20,
144                cache_read_per_m: 0.02,
145            },
146        );
147
148        // Google Gemini API pricing — source: https://ai.google.dev/pricing
149        // (No separate cache pricing published → treat cache read/write as input.)
150        models.insert(
151            "gemini-2.5-pro".to_string(),
152            ModelCost {
153                input_per_m: 1.25,
154                output_per_m: 10.00,
155                cache_write_per_m: 1.25,
156                cache_read_per_m: 1.25,
157            },
158        );
159        models.insert(
160            "gemini-2.5-flash".to_string(),
161            ModelCost {
162                input_per_m: 0.30,
163                output_per_m: 2.50,
164                cache_write_per_m: 0.30,
165                cache_read_per_m: 0.30,
166            },
167        );
168        models.insert(
169            "gemini-2.5-flash-lite".to_string(),
170            ModelCost {
171                input_per_m: 0.10,
172                output_per_m: 0.40,
173                cache_write_per_m: 0.10,
174                cache_read_per_m: 0.10,
175            },
176        );
177
178        // Conservative blended fallback (used by legacy stats output).
179        models.insert(
180            "fallback-blended".to_string(),
181            ModelCost {
182                input_per_m: 2.50,
183                output_per_m: 10.00,
184                cache_write_per_m: 2.50,
185                cache_read_per_m: 2.50,
186            },
187        );
188
189        Self { models }
190    }
191
192    pub fn quote(&self, model: Option<&str>) -> ModelQuote {
193        let raw = model.unwrap_or_default();
194        if let Some(k) = Self::infer_model_key(raw) {
195            if let Some(cost) = self.models.get(&k).copied() {
196                return ModelQuote {
197                    model_key: k,
198                    cost,
199                    match_kind: PricingMatchKind::Exact,
200                };
201            }
202        }
203
204        if let Some((k, kind)) = Self::heuristic_key(raw) {
205            if let Some(cost) = self.models.get(&k).copied() {
206                return ModelQuote {
207                    model_key: k,
208                    cost,
209                    match_kind: kind,
210                };
211            }
212        }
213
214        let cost = self
215            .models
216            .get("fallback-blended")
217            .copied()
218            .unwrap_or(ModelCost {
219                input_per_m: 2.50,
220                output_per_m: 10.00,
221                cache_write_per_m: 2.50,
222                cache_read_per_m: 2.50,
223            });
224        ModelQuote {
225            model_key: "fallback-blended".to_string(),
226            cost,
227            match_kind: PricingMatchKind::Fallback,
228        }
229    }
230
231    pub fn quote_from_env_or_agent_type(&self, agent_type: &str) -> ModelQuote {
232        let env_model = std::env::var("LEAN_CTX_MODEL")
233            .or_else(|_| std::env::var("LCTX_MODEL"))
234            .ok();
235        self.quote(env_model.as_deref().or(Some(agent_type)))
236    }
237
238    pub fn infer_model_key(model: &str) -> Option<String> {
239        let m = normalize(model);
240        if m.is_empty() {
241            return None;
242        }
243
244        let exact_keys = [
245            "claude-fable-5",
246            "claude-opus-4.5",
247            "claude-sonnet-4.5",
248            "claude-haiku-4.5",
249            "claude-3.5-sonnet",
250            "claude-3-opus",
251            "claude-3-haiku",
252            "gpt-5.4",
253            "gpt-5.4-mini",
254            "gpt-5.4-nano",
255            "gemini-2.5-pro",
256            "gemini-2.5-flash",
257            "gemini-2.5-flash-lite",
258            "fallback-blended",
259        ];
260        for k in exact_keys {
261            if m == k {
262                return Some(k.to_string());
263            }
264        }
265        None
266    }
267
268    fn heuristic_key(model: &str) -> Option<(String, PricingMatchKind)> {
269        let m = normalize(model);
270        if m.is_empty() {
271            return None;
272        }
273
274        // Claude family: accept loose naming (e.g. "claude sonnet", "claude-4.6-sonnet").
275        // 3.x names map to legacy tiers; everything else gets the current
276        // generation's price — defaulting to 3.x would overstate Opus cost 3×.
277        if m.contains("claude") || m.contains("fable") || m.contains("mythos") {
278            let legacy = m.contains("claude-3");
279            if m.contains("fable") || m.contains("mythos") {
280                return Some(("claude-fable-5".to_string(), PricingMatchKind::Heuristic));
281            }
282            if m.contains("sonnet") {
283                return Some(if legacy {
284                    ("claude-3.5-sonnet".to_string(), PricingMatchKind::Heuristic)
285                } else {
286                    ("claude-sonnet-4.5".to_string(), PricingMatchKind::Heuristic)
287                });
288            }
289            if m.contains("opus") {
290                return Some(if legacy {
291                    ("claude-3-opus".to_string(), PricingMatchKind::Heuristic)
292                } else {
293                    ("claude-opus-4.5".to_string(), PricingMatchKind::Heuristic)
294                });
295            }
296            if m.contains("haiku") {
297                return Some(if legacy {
298                    ("claude-3-haiku".to_string(), PricingMatchKind::Heuristic)
299                } else {
300                    ("claude-haiku-4.5".to_string(), PricingMatchKind::Heuristic)
301                });
302            }
303        }
304
305        if m.contains("gemini") {
306            if m.contains("2.5") && m.contains("pro") {
307                return Some(("gemini-2.5-pro".to_string(), PricingMatchKind::Heuristic));
308            }
309            if m.contains("2.5") && m.contains("flash-lite") {
310                return Some((
311                    "gemini-2.5-flash-lite".to_string(),
312                    PricingMatchKind::Heuristic,
313                ));
314            }
315            if m.contains("2.5") && m.contains("flash") {
316                return Some(("gemini-2.5-flash".to_string(), PricingMatchKind::Heuristic));
317            }
318        }
319
320        // OpenAI family: accept "gpt-5.4" variants and legacy "gpt-4o" as alias to blended fallback.
321        if m.contains("gpt-5.4") && m.contains("mini") {
322            return Some(("gpt-5.4-mini".to_string(), PricingMatchKind::Alias));
323        }
324        if m.contains("gpt-5.4") && m.contains("nano") {
325            return Some(("gpt-5.4-nano".to_string(), PricingMatchKind::Alias));
326        }
327        if m.contains("gpt-5.4") {
328            return Some(("gpt-5.4".to_string(), PricingMatchKind::Alias));
329        }
330        if m.contains("gpt-4o") {
331            return Some(("fallback-blended".to_string(), PricingMatchKind::Heuristic));
332        }
333
334        None
335    }
336
337    fn apply_env_override(&mut self) {
338        let raw = std::env::var("LEAN_CTX_MODEL_PRICING_JSON")
339            .or_else(|_| std::env::var("LCTX_MODEL_PRICING_JSON"))
340            .ok();
341        let Some(raw) = raw else { return };
342
343        let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) else {
344            return;
345        };
346        let Some(models) = v.get("models").and_then(|m| m.as_object()) else {
347            return;
348        };
349        for (k, vv) in models {
350            let Some(obj) = vv.as_object() else { continue };
351            let input_per_m = obj.get("input_per_m").and_then(serde_json::Value::as_f64);
352            let output_per_m = obj.get("output_per_m").and_then(serde_json::Value::as_f64);
353            if input_per_m.is_none() && output_per_m.is_none() {
354                continue;
355            }
356
357            let key_norm = normalize(k);
358            let base = self.models.get(&key_norm).copied().unwrap_or_else(|| {
359                self.models
360                    .get("fallback-blended")
361                    .copied()
362                    .unwrap_or(ModelCost {
363                        input_per_m: 2.50,
364                        output_per_m: 10.00,
365                        cache_write_per_m: 2.50,
366                        cache_read_per_m: 2.50,
367                    })
368            });
369
370            let merged = ModelCost {
371                input_per_m: input_per_m.unwrap_or(base.input_per_m),
372                output_per_m: output_per_m.unwrap_or(base.output_per_m),
373                cache_write_per_m: obj
374                    .get("cache_write_per_m")
375                    .and_then(serde_json::Value::as_f64)
376                    .unwrap_or(base.cache_write_per_m),
377                cache_read_per_m: obj
378                    .get("cache_read_per_m")
379                    .and_then(serde_json::Value::as_f64)
380                    .unwrap_or(base.cache_read_per_m),
381            };
382            self.models.insert(key_norm, merged);
383        }
384    }
385}
386
387fn normalize(s: &str) -> String {
388    s.trim().to_lowercase().replace(' ', "-")
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    #[test]
396    fn quote_falls_back() {
397        let p = ModelPricing::embedded();
398        let q = p.quote(Some("unknown-model"));
399        assert_eq!(q.match_kind, PricingMatchKind::Fallback);
400    }
401
402    #[test]
403    fn claude_sonnet_heuristic_maps_to_current_generation() {
404        let p = ModelPricing::embedded();
405        let q = p.quote(Some("claude-4.6-sonnet"));
406        assert!(matches!(
407            q.match_kind,
408            PricingMatchKind::Heuristic | PricingMatchKind::Alias
409        ));
410        assert_eq!(q.model_key, "claude-sonnet-4.5");
411        assert!((q.cost.input_per_m - 3.00).abs() < f64::EPSILON);
412    }
413
414    #[test]
415    fn claude_legacy_names_keep_legacy_pricing() {
416        let p = ModelPricing::embedded();
417        let q = p.quote(Some("claude-3-opus"));
418        assert_eq!(q.model_key, "claude-3-opus");
419        assert!((q.cost.input_per_m - 15.00).abs() < f64::EPSILON);
420    }
421
422    #[test]
423    fn claude_opus_current_generation_is_5_per_m() {
424        let p = ModelPricing::embedded();
425        for name in ["claude-opus-4.8", "claude-4.7-opus", "claude opus"] {
426            let q = p.quote(Some(name));
427            assert_eq!(q.model_key, "claude-opus-4.5", "for {name}");
428            assert!((q.cost.input_per_m - 5.00).abs() < f64::EPSILON);
429            assert!((q.cost.output_per_m - 25.00).abs() < f64::EPSILON);
430        }
431    }
432
433    #[test]
434    fn claude_fable_matches_frontier_tier() {
435        let p = ModelPricing::embedded();
436        let q = p.quote(Some("claude-fable-5-thinking-high"));
437        assert_eq!(q.model_key, "claude-fable-5");
438        assert!((q.cost.input_per_m - 10.00).abs() < f64::EPSILON);
439    }
440}