Skip to main content

token_manager/
prices.rs

1use crate::provider::Provider;
2use anyhow::{Context, Result, ensure};
3use reqwest::{blocking::Client, redirect::Policy};
4use rust_decimal::Decimal;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::{io::Read, str::FromStr, time::Duration};
8
9#[derive(Clone, Deserialize, Serialize)]
10#[serde(deny_unknown_fields)]
11pub struct PricingMap {
12    pub path: String,
13    pub source: String,
14    pub rows: String,
15    pub id: String,
16    pub name: String,
17    pub input: String,
18    pub output: String,
19}
20impl PricingMap {
21    pub fn validate(&self, provider: &Provider, local: bool) -> Result<()> {
22        let mut catalog = provider.clone();
23        catalog.path = self.path.clone();
24        catalog.endpoint(local)?;
25        for pointer in [&self.rows, &self.id, &self.name, &self.input, &self.output] {
26            ensure!(
27                pointer.starts_with('/'),
28                "pricing mappings require JSON pointers"
29            );
30        }
31        let source = reqwest::Url::parse(&self.source)?;
32        ensure!(
33            source.scheme() == "https"
34                && source.username().is_empty()
35                && source.password().is_none(),
36            "pricing source must be HTTPS without credentials"
37        );
38        Ok(())
39    }
40}
41#[derive(Clone, Copy, clap::ValueEnum, Serialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Sort {
44    Input,
45    Output,
46}
47#[derive(Serialize)]
48pub struct ModelPrice {
49    pub id: String,
50    pub name: String,
51    pub input_per_million: Option<String>,
52    pub output_per_million: Option<String>,
53}
54#[derive(Serialize)]
55pub struct Report {
56    pub provider: String,
57    pub source: String,
58    pub observed_at: u64,
59    pub currency: &'static str,
60    pub sort: Sort,
61    pub models: Vec<ModelPrice>,
62}
63fn rate(row: &Value, pointer: &str) -> Option<String> {
64    let value = row.pointer(pointer)?;
65    let text = match value {
66        Value::String(s) => s.clone(),
67        Value::Number(n) => n.to_string(),
68        _ => return None,
69    };
70    let rate = Decimal::from_str(&text).ok()?;
71    if rate.is_sign_negative() {
72        return None;
73    }
74    Some(
75        rate.checked_mul(Decimal::from(1_000_000))?
76            .normalize()
77            .to_string(),
78    )
79}
80fn normalized(s: &str) -> String {
81    s.to_lowercase()
82        .chars()
83        .filter(|c| c.is_alphanumeric())
84        .collect()
85}
86fn text(row: &Value, pointer: &str) -> Result<String> {
87    let s = row
88        .pointer(pointer)
89        .and_then(Value::as_str)
90        .context("Catalog model identity missing")?;
91    ensure!(
92        !s.is_empty() && s.len() <= 512 && !s.chars().any(char::is_control),
93        "Invalid catalog model identity"
94    );
95    Ok(s.to_owned())
96}
97pub fn extract(
98    value: &Value,
99    map: &PricingMap,
100    query: &str,
101    sort: Sort,
102) -> Result<Vec<ModelPrice>> {
103    let query = normalized(query);
104    ensure!(!query.is_empty(), "Enter a model or family name");
105    let rows = value
106        .pointer(&map.rows)
107        .and_then(Value::as_array)
108        .context("Catalog response does not match pricing mapping")?;
109    let mut models = Vec::new();
110    for row in rows {
111        let id = text(row, &map.id)?;
112        let name = text(row, &map.name)?;
113        if normalized(&id).contains(&query) || normalized(&name).contains(&query) {
114            models.push(ModelPrice {
115                id,
116                name,
117                input_per_million: rate(row, &map.input),
118                output_per_million: rate(row, &map.output),
119            });
120        }
121    }
122    // An exact model ID, short slug, or display name takes precedence over family matching.
123    let exact = |m: &ModelPrice| {
124        normalized(&m.id) == query
125            || normalized(m.id.rsplit('/').next().unwrap_or(&m.id)) == query
126            || normalized(&m.name) == query
127    };
128    if models.iter().any(exact) {
129        models.retain(exact);
130    }
131    let key = |m: &ModelPrice| {
132        match sort {
133            Sort::Input => &m.input_per_million,
134            Sort::Output => &m.output_per_million,
135        }
136        .as_ref()
137        .and_then(|s| Decimal::from_str(s).ok())
138    };
139    models.sort_by(|a, b| key(b).cmp(&key(a)).then_with(|| a.id.cmp(&b.id)));
140    ensure!(
141        !models.is_empty(),
142        "No models matched; try a family name or catalog model ID"
143    );
144    Ok(models)
145}
146pub fn fetch(provider: &Provider, query: &str, sort: Sort, local: bool) -> Result<Report> {
147    ensure!(
148        !normalized(query).is_empty(),
149        "Enter a model or family name"
150    );
151    let map = provider
152        .pricing
153        .as_ref()
154        .context("This provider has no public pricing catalog mapping")?;
155    map.validate(provider, local)?;
156    let mut catalog = provider.clone();
157    catalog.path = map.path.clone();
158    let client = Client::builder()
159        .timeout(Duration::from_secs(15))
160        .connect_timeout(Duration::from_secs(3))
161        .redirect(Policy::none())
162        .build()?;
163    let response = client
164        .get(catalog.endpoint(local)?)
165        .send()
166        .map_err(|_| anyhow::anyhow!("Pricing catalog request failed or timed out"))?;
167    ensure!(
168        response.status().is_success(),
169        "Pricing catalog returned HTTP {}",
170        response.status().as_u16()
171    );
172    let mut body = Vec::new();
173    response
174        .take(8 * 1024 * 1024 + 1)
175        .read_to_end(&mut body)
176        .context("Could not read pricing catalog")?;
177    ensure!(
178        body.len() <= 8 * 1024 * 1024,
179        "Pricing catalog exceeds size limit"
180    );
181    let value = serde_json::from_slice(&body)
182        .map_err(|_| anyhow::anyhow!("Pricing catalog did not return valid JSON"))?;
183    Ok(Report {
184        provider: provider.id.clone(),
185        source: map.source.clone(),
186        observed_at: crate::state::now(),
187        currency: "USD",
188        sort,
189        models: extract(&value, map, query, sort)?,
190    })
191}
192pub fn table(report: &Report) -> String {
193    let sort = match report.sort {
194        Sort::Input => "input",
195        Sort::Output => "output",
196    };
197    let mut out = format!(
198        "{} catalog — USD / 1M tokens; highest {sort} price first\n",
199        report.provider
200    );
201    out.push_str(&format!(
202        "{:<55} {:>16} {:>16}\n",
203        "MODEL", "INPUT", "OUTPUT"
204    ));
205    for m in &report.models {
206        out.push_str(&format!(
207            "{:<55} {:>16} {:>16}\n",
208            m.id,
209            m.input_per_million.as_deref().unwrap_or("not available"),
210            m.output_per_million.as_deref().unwrap_or("not available")
211        ));
212    }
213    out.push_str(&format!("\nSource: {}\nBase catalog token rates; caching, context tiers and other charges may differ.\n", report.source));
214    out
215}