Skip to main content

mars_schema/
models.rs

1//! The models.dev catalog row and the pure alias resolver over it.
2//!
3//! Rows are the shape Mars snapshots and the shape Meridian Flow holds, so both resolve
4//! aliases and read a model's reasoning the same way.
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9/// One models.dev model.
10#[derive(Debug, Clone, Default, Serialize, Deserialize)]
11pub struct CachedModel {
12    pub id: String,
13    /// Display name ("Anthropic", "xAI").
14    pub provider: String,
15    /// models.dev's own provider key ("anthropic", "meta-llama"). `meta` and `meta-llama`
16    /// both display as "Meta", so the key is what tells providers apart. Snapshots written
17    /// before it existed lack it; readers fill it with [`provider_key_from_display`].
18    #[serde(default)]
19    pub provider_key: String,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub release_date: Option<String>,
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub description: Option<String>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub context_window: Option<u64>,
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub max_output: Option<u64>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub cost_input: Option<f64>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub cost_output: Option<f64>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub cost_cache_read: Option<f64>,
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub cost_cache_write: Option<f64>,
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub cost_reasoning: Option<f64>,
38    /// `None` when models.dev says nothing about reasoning (rows from older snapshots).
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub reasoning: Option<ModelReasoningRow>,
41}
42
43/// models.dev's `reasoning` and `reasoning_options` for one model, in its own shape.
44#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
45pub struct ModelReasoningRow {
46    pub reasoning: bool,
47    #[serde(default, skip_serializing_if = "Vec::is_empty")]
48    pub options: Vec<ReasoningOption>,
49}
50
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52#[serde(tag = "type", rename_all = "snake_case")]
53pub enum ReasoningOption {
54    Effort {
55        values: Vec<String>,
56    },
57    Toggle,
58    BudgetTokens {
59        #[serde(default, skip_serializing_if = "Option::is_none")]
60        min: Option<u64>,
61    },
62    /// An option kind this build does not know.
63    #[serde(other)]
64    Other,
65}
66
67impl ModelReasoningRow {
68    /// Decodes a models.dev model object. `None` when it has no `reasoning` field.
69    pub fn from_models_dev(model: &Value) -> Option<Self> {
70        let reasoning = model.get("reasoning")?.as_bool()?;
71        let options = model
72            .get("reasoning_options")
73            .and_then(Value::as_array)
74            .map(|options| {
75                options
76                    .iter()
77                    .filter_map(|option| serde_json::from_value(option.clone()).ok())
78                    .collect()
79            })
80            .unwrap_or_default();
81        Some(Self { reasoning, options })
82    }
83}
84
85/// models.dev provider key as `catalog_providers` and alias `provider` fields spell it, with
86/// the spellings models.dev has used for one provider folded together.
87pub fn catalog_provider_canonical(key: &str) -> String {
88    match key.trim().to_ascii_lowercase().as_str() {
89        "meta-llama" => "meta".to_string(),
90        "mistralai" => "mistral".to_string(),
91        other => other.to_string(),
92    }
93}
94
95/// The providers a project reads when it sets no `catalog_providers`.
96pub const DEFAULT_CATALOG_PROVIDERS: &[&str] = &[
97    "anthropic",
98    "openai",
99    "google",
100    "meta",
101    "deepseek",
102    "xai",
103    "openrouter",
104];
105
106/// Whether a provider key is one of the project's `catalog_providers`: the rule that narrows
107/// models.dev to the rows aliases resolve over. `*` allows every provider; a key compares by
108/// [`catalog_provider_canonical`].
109pub fn provider_filter(allowlist: &[String]) -> impl Fn(&str) -> bool {
110    let all = allowlist.iter().any(|provider| provider.trim() == "*");
111    let allowed: Vec<String> = allowlist
112        .iter()
113        .map(|provider| catalog_provider_canonical(provider))
114        .collect();
115    move |key| all || allowed.contains(&catalog_provider_canonical(key))
116}
117
118/// The display name of a models.dev provider key.
119pub fn normalize_provider(key: &str) -> String {
120    match key {
121        "anthropic" => "Anthropic".to_string(),
122        "openai" => "OpenAI".to_string(),
123        "google" => "Google".to_string(),
124        "meta-llama" | "meta" => "Meta".to_string(),
125        "mistralai" | "mistral" => "Mistral".to_string(),
126        "deepseek" => "DeepSeek".to_string(),
127        "cohere" => "Cohere".to_string(),
128        "xai" => "xAI".to_string(),
129        "openrouter" => "OpenRouter".to_string(),
130        _ => key.to_string(),
131    }
132}
133
134/// The key of a row that only has a display name. Holds for every default catalog provider.
135pub fn provider_key_from_display(display: &str) -> String {
136    display.to_ascii_lowercase()
137}
138
139/// The provider a model id's prefix names, for ids no alias or row gives one for.
140pub fn infer_provider_from_model_id(model_id: &str) -> Option<&'static str> {
141    let id = model_id.to_lowercase();
142    if id.starts_with("claude-") {
143        return Some("anthropic");
144    }
145    if id.starts_with("gpt-")
146        || id.starts_with("o1")
147        || id.starts_with("o3")
148        || id.starts_with("o4")
149        || id.starts_with("codex-")
150    {
151        return Some("openai");
152    }
153    if id.starts_with("gemini") {
154        return Some("google");
155    }
156    if id.starts_with("llama") {
157        return Some("meta");
158    }
159    if id.starts_with("mistral") || id.starts_with("codestral") {
160        return Some("mistral");
161    }
162    if id.starts_with("deepseek") {
163        return Some("deepseek");
164    }
165    if id.starts_with("command") {
166        return Some("cohere");
167    }
168    None
169}
170
171/// `*` globs over a whole string; no other metacharacter.
172pub fn glob_match(pattern: &str, text: &str) -> bool {
173    let segments: Vec<&str> = pattern.split('*').collect();
174
175    if segments.len() == 1 {
176        return pattern == text;
177    }
178
179    let mut pos = 0;
180
181    if let Some(first) = segments.first()
182        && !first.is_empty()
183    {
184        if !text.starts_with(first) {
185            return false;
186        }
187        pos = first.len();
188    }
189
190    if let Some(last) = segments.last()
191        && !last.is_empty()
192        && !text[pos..].ends_with(last)
193    {
194        return false;
195    }
196
197    let end = if let Some(last) = segments.last() {
198        if !last.is_empty() {
199            text.len() - last.len()
200        } else {
201            text.len()
202        }
203    } else {
204        text.len()
205    };
206
207    for segment in &segments[1..segments.len().saturating_sub(1)] {
208        if segment.is_empty() {
209            continue;
210        }
211        if let Some(idx) = text[pos..end].find(segment) {
212            pos += idx + segment.len();
213        } else {
214            return false;
215        }
216    }
217
218    pos <= end
219}
220
221/// Every row an `auto` alias selects, best first: all `match` globs hit, no `exclude` glob
222/// hits, the provider (when set) matches by canonical key, `-latest` ids are skipped, newest
223/// `release_date` first (a row with none sorts last), then the shorter id, then alphabetical.
224pub fn auto_resolve_all<'a>(
225    provider: Option<&str>,
226    match_patterns: &[String],
227    exclude_patterns: &[String],
228    models: &'a [CachedModel],
229) -> Vec<&'a CachedModel> {
230    let provider = provider.map(catalog_provider_canonical);
231    let mut candidates: Vec<&CachedModel> = models
232        .iter()
233        .filter(|m| {
234            provider
235                .as_deref()
236                .is_none_or(|p| catalog_provider_canonical(&m.provider_key) == p)
237        })
238        .filter(|m| !m.id.ends_with("-latest"))
239        .filter(|m| match_patterns.iter().all(|p| glob_match(p, &m.id)))
240        .filter(|m| !exclude_patterns.iter().any(|p| glob_match(p, &m.id)))
241        .collect();
242    sort_best_first(&mut candidates);
243    candidates
244}
245
246pub fn sort_best_first(candidates: &mut [&CachedModel]) {
247    candidates.sort_by(|a, b| {
248        let date_cmp = b
249            .release_date
250            .as_deref()
251            .unwrap_or("")
252            .cmp(a.release_date.as_deref().unwrap_or(""));
253        date_cmp
254            .then_with(|| a.id.len().cmp(&b.id.len()))
255            .then_with(|| a.id.cmp(&b.id))
256    });
257}