Skip to main content

rig_core/catalog/
mod.rs

1//! Model facts by provider and model id: limits, input modalities, reasoning, caching, prices.
2//!
3//! A catalog is built in layers, each sharing the rows it does not change:
4//! 1. [`Catalog::builtin`]: generated from models.dev by `cargo xtask catalog sync`, its main
5//!    providers reviewed by hand;
6//! 2. a newer models.dev copy ([`Catalog::from_models_dev`], lenient; laid on with
7//!    [`Catalog::with_models_dev`], which keeps the hand-reviewed fields);
8//! 3. the user's overrides ([`Catalog::from_overrides`], strict, with a close alternative for
9//!    every mistake; laid on with [`Catalog::with_overrides`]).
10//!
11//! A model connected earlier keeps the facts it was connected with.
12//!
13//! ```no_run
14//! use std::path::Path;
15//! use rig_core::catalog::Catalog;
16//!
17//! fn catalog(cache: &Path, config: &Path) -> Result<Catalog, Box<dyn std::error::Error>> {
18//!     let mut catalog = Catalog::builtin().clone();
19//!     let fetched = cache.join("models-dev.json");
20//!     if std::fs::metadata(&fetched)
21//!         .and_then(|file| file.modified())
22//!         .is_ok_and(|fetched_at| fetched_at > Catalog::generated_at())
23//!     {
24//!         let (models_dev, _skipped) = Catalog::from_models_dev(&std::fs::read_to_string(&fetched)?)?;
25//!         catalog = catalog.with_models_dev(&models_dev);
26//!     }
27//!     if let Ok(json) = std::fs::read_to_string(config.join("models.json")) {
28//!         catalog = catalog.with_overrides(&Catalog::from_overrides(&json, &catalog)?);
29//!     }
30//!     Ok(catalog)
31//! }
32//! ```
33//!
34//! [`Catalog::connect`] builds a model from `vendor/model` with the key from the environment; it
35//! encodes and prices with the [`ModelFacts`] it was connected with. [`ModelSpec::validate`]
36//! checks a request's options before anything is sent:
37//!
38//! ```
39//! use rig_core::catalog::Catalog;
40//! use rig_core::completion::{Effort, GenerationOptions};
41//!
42//! let haiku = Catalog::builtin().resolve("anthropic/claude-haiku-4-5")?.spec;
43//! let options = GenerationOptions::default().reasoning(Effort::High);
44//! assert!(haiku.validate(&options).is_err(), "Haiku 4.5 takes a budget");
45//! # Ok::<(), rig_core::catalog::NotFound>(())
46//! ```
47
48mod connector;
49mod details;
50mod facts;
51mod lookup;
52mod read;
53mod row;
54mod spec;
55
56use std::sync::{Arc, OnceLock};
57use std::time::{Duration, SystemTime, UNIX_EPOCH};
58
59use crate::providers::registry::{Format, ProviderId};
60use row::Row;
61
62pub use connector::{Connector, ModelStatus, Provide, SignIn, Transport};
63pub use details::{
64    CostDetails, CostTier, Interleaved, Mode, ModelDetails, ProviderOverride, Rates, Tier,
65};
66pub use facts::ModelFacts;
67pub use lookup::{Matched, NotFound, Resolved, closest_name, edit_distance};
68pub use read::{OverrideError, OverrideErrorKind, OverrideErrors, SkipReason, Skipped};
69pub use spec::{
70    CacheSupport, ChatTools, Compat, Modalities, ModelSpec, Pricing, ReasoningChoice,
71    ReasoningSupport, Sampling, UnknownReasoning,
72};
73
74/// The checked-in catalog data, generated by `cargo xtask catalog sync`.
75const BUILTIN: &str = include_str!("models.json");
76
77/// Model facts by provider and model id. Cloning is cheap: the rows are
78/// shared, and a change copies only the list of handles to them.
79#[derive(Clone, Debug, Default)]
80pub struct Catalog {
81    /// Sorted by vendor, then model id.
82    entries: Arc<Vec<Entry>>,
83}
84
85/// One model: its spec, and the row it was built from, which
86/// [`Catalog::with_overrides`] lays an override on.
87#[derive(Clone, Debug)]
88struct Entry {
89    row: Arc<Row>,
90    spec: Arc<ModelSpec>,
91}
92
93/// Why catalog data did not load.
94#[non_exhaustive]
95#[derive(Debug, thiserror::Error)]
96pub enum CatalogError {
97    /// The text is not a JSON object.
98    #[error("not a models.dev-style catalog: {0}")]
99    Json(#[from] serde_json::Error),
100}
101
102/// The models.dev provider keys whose rig vendor name differs. Any other key
103/// is read as a rig vendor name.
104const KEYS: [(&str, &str); 9] = [
105    ("azure", "azure.openai"),
106    ("google", "gcp.gemini"),
107    ("google-vertex", "vertexai"),
108    ("amazon-bedrock", "aws_bedrock"),
109    ("togetherai", "together"),
110    ("moonshotai", "moonshot"),
111    ("xiaomi", "xiaomimimo"),
112    ("ollama-cloud", "ollama"),
113    ("github-copilot", "copilot"),
114];
115
116impl Catalog {
117    /// The catalog this build ships.
118    ///
119    /// # Panics
120    ///
121    /// Panics on first use if the data compiled into this build does not
122    /// parse whole. The data is checked in and a unit test parses it, so a build
123    /// that passed its tests never panics here.
124    pub fn builtin() -> &'static Catalog {
125        static BUILTIN_CATALOG: OnceLock<Catalog> = OnceLock::new();
126        BUILTIN_CATALOG.get_or_init(|| match Catalog::from_models_dev(BUILTIN) {
127            Ok((catalog, skipped)) if skipped.is_empty() => catalog,
128            // A missing row would silently drop that model's facts, and an
129            // empty catalog every model's, so a bad build fails loudly
130            // instead. `the_checked_in_catalog_loads_whole` keeps these
131            // branches unreachable in a tested build.
132            #[allow(clippy::panic)]
133            Ok((_, skipped)) => panic!(
134                "rig-core's built-in catalog data skips {}: {:?}",
135                skipped.len(),
136                skipped.first()
137            ),
138            #[allow(clippy::panic)]
139            Err(error) => panic!("rig-core's built-in catalog data does not parse: {error}"),
140        })
141    }
142
143    /// When the models.dev data behind [`Self::builtin`] was read. Lay a
144    /// fetched copy on only when it is newer, so an old cache never hides
145    /// what this rig shipped. `cargo xtask catalog sync` writes the time
146    /// as RFC 3339 UTC; a file that does not parse reads as the Unix epoch,
147    /// so any fetched copy is newer.
148    pub fn generated_at() -> SystemTime {
149        crate::error::rfc3339(include_str!("generated_at").trim_ascii_end())
150            .and_then(|nanos| u64::try_from(nanos).ok())
151            .map_or(UNIX_EPOCH, |nanos| UNIX_EPOCH + Duration::from_nanos(nanos))
152    }
153
154    /// The model `provider` serves as `model`, by the one rule every
155    /// lookup in rig follows: the id as listed, or else the longest listed
156    /// id that `model` extends with `-20` and a year, a dated snapshot of it
157    /// (`claude-sonnet-4-5-20250929`, `gpt-5-2025-08-07`,
158    /// `claude-opus-5-5-20260601-v1:0`). Any selection of a vendor finds
159    /// that vendor's models.
160    pub fn get(&self, provider: ProviderId, model: &str) -> Option<Resolved<'_>> {
161        self.get_vendor(provider.vendor(), model)
162    }
163
164    /// The model `provider` lists as exactly `model`, for a caller that
165    /// must not read a snapshot as its base model.
166    pub fn get_exact(&self, provider: ProviderId, model: &str) -> Option<&ModelSpec> {
167        self.exact(provider.vendor(), model)
168    }
169
170    /// The model a reference names, by [`Self::get`]'s rule. A reference is
171    /// `vendor/model`, split at the first `/`, so the model id keeps any
172    /// `/` and `:` of its own (`openrouter/anthropic/claude-sonnet-4.5`,
173    /// `ollama/qwen3:4b`). The older `vendor/format:model` spelling is still
174    /// read; its format plays no part in the lookup.
175    ///
176    /// # Errors
177    ///
178    /// [`NotFound`] when the reference names no listed model, with up to
179    /// five close references to models that are not deprecated, or else
180    /// the closest ones of its vendor.
181    pub fn resolve(&self, reference: &str) -> Result<Resolved<'_>, NotFound> {
182        Reference::parse(reference)
183            .and_then(|parsed| self.get_vendor(parsed.vendor, parsed.model))
184            .ok_or_else(|| self.not_found(reference))
185    }
186
187    /// The miss [`Self::resolve`] reports for `reference`.
188    pub(crate) fn not_found(&self, reference: &str) -> NotFound {
189        let mut suggestions = lookup::suggestions(reference, self.iter());
190        if suggestions.is_empty() {
191            suggestions = lookup::vendor_models(reference, self.iter());
192        }
193        NotFound {
194            reference: reference.to_owned(),
195            suggestions,
196        }
197    }
198
199    /// Every model, by vendor then id.
200    pub fn iter(&self) -> impl Iterator<Item = &ModelSpec> {
201        self.entries.iter().map(|entry| &*entry.spec)
202    }
203
204    /// This catalog with `overrides` laid over it, field by field. A model in
205    /// both keeps every field the override leaves out; a model only in
206    /// `overrides` is added. `self` is unchanged, and the result shares every
207    /// row the override does not touch.
208    ///
209    /// Every field the override sets wins, including the facts rig reviewed
210    /// by hand, so lay a fetched copy of models.dev on with
211    /// [`Self::with_models_dev`] instead.
212    pub fn with_overrides(&self, overrides: &Catalog) -> Catalog {
213        let mut catalog = self.clone();
214        for entry in overrides.entries.iter() {
215            catalog.put(
216                entry.spec.provider,
217                &entry.spec.id,
218                Row::clone(&entry.row),
219                Row::overlay,
220            );
221        }
222        catalog
223    }
224
225    /// This catalog with `fetched`, a newer copy of models.dev read with
226    /// [`Self::from_models_dev`], laid over it as [`Self::with_overrides`]
227    /// lays an override, except for the fields of a row that rig's own data
228    /// pins. The built-in data pins the fields rig reviewed by hand and the
229    /// ones its generator joins from another row (a gateway's Claude row
230    /// takes Anthropic's reasoning options), so a refresh updates prices and
231    /// limits models.dev changes but keeps those. A model only in `fetched`
232    /// is added as models.dev lists it.
233    pub fn with_models_dev(&self, fetched: &Catalog) -> Catalog {
234        let mut catalog = self.clone();
235        for entry in fetched.entries.iter() {
236            let (provider, id) = (entry.spec.provider, entry.spec.id.as_str());
237            let row = Row::clone(&entry.row);
238            let row = match catalog.position(provider.vendor(), id) {
239                Ok(index) => match catalog.entries.get(index) {
240                    Some(base) => row.without(base.row.pinned()),
241                    None => row,
242                },
243                Err(_) => row,
244            };
245            catalog.put(provider, id, row, Row::refresh);
246        }
247        catalog
248    }
249
250    /// Add `spec`, replacing any model of the same vendor and id whole. A
251    /// later [`Self::with_overrides`] lays an override on it field by field,
252    /// as on any other row.
253    pub fn insert(&mut self, spec: ModelSpec) {
254        let position = self.position(spec.provider.vendor(), &spec.id);
255        let entry = Entry {
256            row: Arc::new(Row::from_spec(&spec)),
257            spec: Arc::new(spec),
258        };
259        let entries = Arc::make_mut(&mut self.entries);
260        match position {
261            Ok(index) => {
262                if let Some(slot) = entries.get_mut(index) {
263                    *slot = entry;
264                }
265            }
266            Err(index) => entries.insert(index, entry),
267        }
268    }
269
270    /// [`Self::get`] by vendor name.
271    pub(crate) fn get_vendor(&self, vendor: &str, model: &str) -> Option<Resolved<'_>> {
272        if let Some(shared) = self.entry(vendor, model) {
273            return Some(Resolved {
274                spec: shared,
275                matched: Matched::Exact,
276                shared,
277            });
278        }
279        lookup::snapshot_bases(model).find_map(|base| {
280            self.entry(vendor, base).map(|shared| Resolved {
281                spec: shared,
282                matched: Matched::SnapshotOf(shared.id.clone()),
283                shared,
284            })
285        })
286    }
287
288    fn exact(&self, vendor: &str, model: &str) -> Option<&ModelSpec> {
289        self.entry(vendor, model).map(|spec| &**spec)
290    }
291
292    fn entry(&self, vendor: &str, model: &str) -> Option<&Arc<ModelSpec>> {
293        self.position(vendor, model)
294            .ok()
295            .and_then(|index| self.entries.get(index))
296            .map(|entry| &entry.spec)
297    }
298
299    fn position(&self, vendor: &str, model: &str) -> Result<usize, usize> {
300        self.entries.binary_search_by(|entry| {
301            (entry.spec.provider.vendor(), entry.spec.id.as_str()).cmp(&(vendor, model))
302        })
303    }
304
305    /// Add `row` for `provider`'s `id`, laid over any row already there.
306    fn put(&mut self, provider: ProviderId, id: &str, row: Row, merge: fn(Row, Row) -> Row) {
307        let position = self.position(provider.vendor(), id);
308        let entries = Arc::make_mut(&mut self.entries);
309        match position {
310            Ok(index) => {
311                if let Some(entry) = entries.get_mut(index) {
312                    let row = merge(Row::clone(&entry.row), row);
313                    entry.spec = Arc::new(row.spec(entry.spec.provider, id));
314                    entry.row = Arc::new(row);
315                }
316            }
317            Err(index) => {
318                let spec = Arc::new(row.spec(provider, id));
319                entries.insert(
320                    index,
321                    Entry {
322                        row: Arc::new(row),
323                        spec,
324                    },
325                );
326            }
327        }
328    }
329}
330
331/// The rig vendor a models.dev provider key names.
332fn vendor_of(key: &str) -> &str {
333    KEYS.iter()
334        .find_map(|(models_dev, vendor)| (*models_dev == key).then_some(*vendor))
335        .unwrap_or(key)
336}
337
338/// A model reference as text spells it: `vendor/model`, or the older
339/// `vendor/format:model`, which also names a protocol family. Every reader
340/// of a reference string in rig parses it here.
341#[derive(Clone, Copy, Debug, PartialEq, Eq)]
342pub(crate) struct Reference<'a> {
343    /// The text before the first `/`.
344    pub(crate) vendor: &'a str,
345    /// The provider's model id.
346    pub(crate) model: &'a str,
347    /// The family the older spelling names, if it was used.
348    pub(crate) format: Option<Format>,
349}
350
351impl<'a> Reference<'a> {
352    /// `text` split at its first `/`, or `None` when either side is empty.
353    /// The rest is read as `format:model` only when the text before its
354    /// first `:` is a [`Format`]'s name.
355    pub(crate) fn parse(text: &'a str) -> Option<Self> {
356        let (vendor, rest) = text.split_once('/')?;
357        if vendor.is_empty() || rest.is_empty() {
358            return None;
359        }
360        if let Some((format, model)) = rest.split_once(':')
361            && let Some(format) = Format::named(format)
362        {
363            return (!model.is_empty()).then_some(Self {
364                vendor,
365                model,
366                format: Some(format),
367            });
368        }
369        Some(Self {
370            vendor,
371            model: rest,
372            format: None,
373        })
374    }
375}
376
377#[cfg(test)]
378mod tests;