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 display name of a models.dev provider key.
96pub fn normalize_provider(key: &str) -> String {
97    match key {
98        "anthropic" => "Anthropic".to_string(),
99        "openai" => "OpenAI".to_string(),
100        "google" => "Google".to_string(),
101        "meta-llama" | "meta" => "Meta".to_string(),
102        "mistralai" | "mistral" => "Mistral".to_string(),
103        "deepseek" => "DeepSeek".to_string(),
104        "cohere" => "Cohere".to_string(),
105        "xai" => "xAI".to_string(),
106        "openrouter" => "OpenRouter".to_string(),
107        _ => key.to_string(),
108    }
109}
110
111/// The key of a row that only has a display name. Holds for every default catalog provider.
112pub fn provider_key_from_display(display: &str) -> String {
113    display.to_ascii_lowercase()
114}
115
116/// `*` globs over a whole string; no other metacharacter.
117pub fn glob_match(pattern: &str, text: &str) -> bool {
118    let segments: Vec<&str> = pattern.split('*').collect();
119
120    if segments.len() == 1 {
121        return pattern == text;
122    }
123
124    let mut pos = 0;
125
126    if let Some(first) = segments.first()
127        && !first.is_empty()
128    {
129        if !text.starts_with(first) {
130            return false;
131        }
132        pos = first.len();
133    }
134
135    if let Some(last) = segments.last()
136        && !last.is_empty()
137        && !text[pos..].ends_with(last)
138    {
139        return false;
140    }
141
142    let end = if let Some(last) = segments.last() {
143        if !last.is_empty() {
144            text.len() - last.len()
145        } else {
146            text.len()
147        }
148    } else {
149        text.len()
150    };
151
152    for segment in &segments[1..segments.len().saturating_sub(1)] {
153        if segment.is_empty() {
154            continue;
155        }
156        if let Some(idx) = text[pos..end].find(segment) {
157            pos += idx + segment.len();
158        } else {
159            return false;
160        }
161    }
162
163    pos <= end
164}
165
166/// Every row an `auto` alias selects, best first: all `match` globs hit, no `exclude` glob
167/// hits, the provider (when set) matches by canonical key, `-latest` ids are skipped, newest
168/// `release_date` first (a row with none sorts last), then the shorter id, then alphabetical.
169pub fn auto_resolve_all<'a>(
170    provider: Option<&str>,
171    match_patterns: &[String],
172    exclude_patterns: &[String],
173    models: &'a [CachedModel],
174) -> Vec<&'a CachedModel> {
175    let provider = provider.map(catalog_provider_canonical);
176    let mut candidates: Vec<&CachedModel> = models
177        .iter()
178        .filter(|m| {
179            provider
180                .as_deref()
181                .is_none_or(|p| catalog_provider_canonical(&m.provider_key) == p)
182        })
183        .filter(|m| !m.id.ends_with("-latest"))
184        .filter(|m| match_patterns.iter().all(|p| glob_match(p, &m.id)))
185        .filter(|m| !exclude_patterns.iter().any(|p| glob_match(p, &m.id)))
186        .collect();
187    sort_best_first(&mut candidates);
188    candidates
189}
190
191pub fn sort_best_first(candidates: &mut [&CachedModel]) {
192    candidates.sort_by(|a, b| {
193        let date_cmp = b
194            .release_date
195            .as_deref()
196            .unwrap_or("")
197            .cmp(a.release_date.as_deref().unwrap_or(""));
198        date_cmp
199            .then_with(|| a.id.len().cmp(&b.id.len()))
200            .then_with(|| a.id.cmp(&b.id))
201    });
202}