Skip to main content

troupekit_local/
catalog.rs

1use crate::error::LocalError;
2use serde::Deserialize;
3use std::collections::HashSet;
4use std::sync::OnceLock;
5
6const BUILTIN: &str = include_str!("../catalog/local.toml");
7
8const ID_MAX_BYTES: usize = 64;
9const URL_MAX_BYTES: usize = 2_048;
10const ROWS_MAX: usize = 256;
11
12/// The device a catalog row targets: `Phone`, `Pi` (single-board
13/// computers) or `Desktop`. `pick` filters by it.
14/// Default `Desktop`.
15#[non_exhaustive]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum DeviceClass {
19    Phone,
20    Pi,
21    #[default]
22    Desktop,
23}
24
25/// One downloadable model: id, https URL, SHA-256, size in bytes,
26/// resident RAM estimate, context, device class, licence, embedding
27/// support and the recommended flag. Checked by `new`; `with_*` setters.
28#[non_exhaustive]
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct LocalSpec {
31    id: String,
32    url: String,
33    sha256: String,
34    bytes: u64,
35    ram_bytes: u64,
36    context: usize,
37    class: DeviceClass,
38    licence: String,
39    embeddings: bool,
40    recommended: bool,
41}
42
43impl LocalSpec {
44    /// Checks and builds a row. Rules: id of lowercase letters, digits,
45    /// `-`, `_`, `.` (1 to 64 bytes, no leading dot); `https://` URL; 64
46    /// lowercase hex chars; size above 0. Output: the row, or `Catalog`.
47    pub fn new(id: &str, url: &str, sha256: &str, bytes: u64) -> Result<Self, LocalError> {
48        let id_ok = !id.is_empty()
49            && id.len() <= ID_MAX_BYTES
50            && !id.starts_with('.')
51            && id.bytes().all(|b| {
52                b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_' | b'.')
53            });
54        if !id_ok {
55            return Err(LocalError::Catalog(format!(
56                "model id {id:?} is not a valid id"
57            )));
58        }
59        let url_ok = url.len() <= URL_MAX_BYTES
60            && url.len() > "https://".len()
61            && url.starts_with("https://")
62            && !url.bytes().any(|b| b.is_ascii_control() || b == b' ');
63        if !url_ok {
64            return Err(LocalError::Catalog(format!(
65                "model {id}: url must be an https URL"
66            )));
67        }
68        let hash_ok = sha256.len() == 64
69            && sha256
70                .bytes()
71                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
72        if !hash_ok {
73            return Err(LocalError::Catalog(format!(
74                "model {id}: sha256 must be 64 lowercase hex characters"
75            )));
76        }
77        if bytes == 0 {
78            return Err(LocalError::Catalog(format!(
79                "model {id}: bytes must be above 0"
80            )));
81        }
82        Ok(Self {
83            id: id.to_string(),
84            url: url.to_string(),
85            sha256: sha256.to_string(),
86            bytes,
87            ram_bytes: bytes,
88            context: 4_096,
89            class: DeviceClass::default(),
90            licence: String::new(),
91            embeddings: false,
92            recommended: false,
93        })
94    }
95
96    /// Sets the resident memory estimate at the default context.
97    /// `pick` compares it with the app's RAM budget.
98    /// Default the file size.
99    pub fn with_ram_bytes(mut self, ram_bytes: u64) -> Self {
100        self.ram_bytes = ram_bytes;
101        self
102    }
103
104    /// Sets the context length the row is meant to run with.
105    /// Informational; `LlamaSettings` sets the real one.
106    /// Default 4 096.
107    pub fn with_context(mut self, context: usize) -> Self {
108        self.context = context;
109        self
110    }
111
112    /// Sets the device class.
113    /// `pick` only returns rows of the asked class.
114    /// Default `Desktop`.
115    pub fn with_class(mut self, class: DeviceClass) -> Self {
116        self.class = class;
117        self
118    }
119
120    /// Sets the licence name, such as `apache-2.0`.
121    /// The owner confirms licences before a release.
122    /// Default empty.
123    pub fn with_licence(mut self, licence: impl Into<String>) -> Self {
124        self.licence = licence.into();
125        self
126    }
127
128    /// Marks the model as able to embed.
129    /// Load it with `LlamaSettings::with_embeddings(true)` to use it.
130    /// Default false.
131    pub fn with_embeddings(mut self, embeddings: bool) -> Self {
132        self.embeddings = embeddings;
133        self
134    }
135
136    /// Marks the row as the recommended one for its class.
137    /// `LocalCatalog::new` allows at most one per class.
138    /// Default false.
139    pub fn with_recommended(mut self, recommended: bool) -> Self {
140        self.recommended = recommended;
141        self
142    }
143
144    /// Returns the model id, also its cache file name stem.
145    /// Input: none.
146    /// Output: the id.
147    pub fn id(&self) -> &str {
148        &self.id
149    }
150
151    /// Returns the https download URL.
152    /// Input: none.
153    /// Output: the URL.
154    pub fn url(&self) -> &str {
155        &self.url
156    }
157
158    /// Returns the expected SHA-256 in lowercase hex.
159    /// Input: none.
160    /// Output: 64 hex characters.
161    pub fn sha256(&self) -> &str {
162        &self.sha256
163    }
164
165    /// Returns the exact file size in bytes.
166    /// Input: none.
167    /// Output: above 0.
168    pub fn bytes(&self) -> u64 {
169        self.bytes
170    }
171
172    /// Returns the resident memory estimate in bytes.
173    /// Input: none.
174    /// Default the file size.
175    pub fn ram_bytes(&self) -> u64 {
176        self.ram_bytes
177    }
178
179    /// Returns the intended context length.
180    /// Input: none.
181    /// Default 4 096.
182    pub fn context(&self) -> usize {
183        self.context
184    }
185
186    /// Returns the device class.
187    /// Input: none.
188    /// Default `Desktop`.
189    pub fn class(&self) -> DeviceClass {
190        self.class
191    }
192
193    /// Returns the licence name.
194    /// Input: none.
195    /// Default empty.
196    pub fn licence(&self) -> &str {
197        &self.licence
198    }
199
200    /// Returns whether the model can embed.
201    /// Input: none.
202    /// Default false.
203    pub fn embeddings(&self) -> bool {
204        self.embeddings
205    }
206
207    /// Returns whether the row is recommended for its class.
208    /// Input: none.
209    /// Default false.
210    pub fn recommended(&self) -> bool {
211        self.recommended
212    }
213}
214
215/// A checked list of downloadable models: unique ids, at most one
216/// recommended row per class, at most 256 rows. `get` finds a row and
217/// `pick` chooses one for a device class and RAM budget.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct LocalCatalog {
220    rows: Vec<LocalSpec>,
221}
222
223#[derive(Deserialize)]
224#[serde(deny_unknown_fields)]
225struct File {
226    #[serde(default)]
227    model: Vec<Row>,
228}
229
230#[derive(Deserialize)]
231#[serde(deny_unknown_fields)]
232struct Row {
233    id: String,
234    url: String,
235    sha256: String,
236    bytes: u64,
237    ram_bytes: Option<u64>,
238    context: Option<usize>,
239    class: Option<DeviceClass>,
240    licence: Option<String>,
241    embeddings: Option<bool>,
242    recommended: Option<bool>,
243}
244
245impl LocalCatalog {
246    /// The largest catalog text `load` accepts, in bytes.
247    /// Setting S34 of the 0.3 plan bounds policy files the same way.
248    /// 64 KiB.
249    pub const MAX_BYTES: usize = 64 * 1024;
250
251    /// Parses catalog TOML: `[[model]]` tables with `id`, `url`,
252    /// `sha256`, `bytes` and optional `ram_bytes`, `context`, `class`,
253    /// `licence`, `embeddings`, `recommended`. Unknown keys are refused.
254    pub fn load(text: &str) -> Result<Self, LocalError> {
255        if text.len() > Self::MAX_BYTES {
256            return Err(LocalError::Catalog(format!(
257                "catalog is {} bytes, limit {}",
258                text.len(),
259                Self::MAX_BYTES
260            )));
261        }
262        let file: File =
263            toml::from_str(text).map_err(|e| LocalError::Catalog(e.message().to_string()))?;
264        let rows = file
265            .model
266            .into_iter()
267            .map(|r| {
268                let mut spec = LocalSpec::new(&r.id, &r.url, &r.sha256, r.bytes)?;
269                if let Some(v) = r.ram_bytes {
270                    spec = spec.with_ram_bytes(v);
271                }
272                if let Some(v) = r.context {
273                    spec = spec.with_context(v);
274                }
275                if let Some(v) = r.class {
276                    spec = spec.with_class(v);
277                }
278                if let Some(v) = r.licence {
279                    spec = spec.with_licence(v);
280                }
281                Ok(spec
282                    .with_embeddings(r.embeddings.unwrap_or(false))
283                    .with_recommended(r.recommended.unwrap_or(false)))
284            })
285            .collect::<Result<Vec<_>, LocalError>>()?;
286        Self::new(rows)
287    }
288
289    /// Returns the catalog shipped with the crate (`catalog/local.toml`),
290    /// parsed once. Input: none.
291    /// Panics only if the shipped file is invalid, which a test guards.
292    pub fn builtin() -> &'static LocalCatalog {
293        static CATALOG: OnceLock<LocalCatalog> = OnceLock::new();
294        CATALOG
295            .get_or_init(|| Self::load(BUILTIN).expect("the shipped catalog/local.toml is valid"))
296    }
297
298    /// Builds a catalog from rows.
299    /// Input: rows from `LocalSpec::new`. Output: the catalog, or
300    /// `Catalog` on a duplicate id, two recommended rows or over 256 rows.
301    pub fn new(rows: Vec<LocalSpec>) -> Result<Self, LocalError> {
302        if rows.len() > ROWS_MAX {
303            return Err(LocalError::Catalog(format!(
304                "{} rows, limit {ROWS_MAX}",
305                rows.len()
306            )));
307        }
308        let mut ids = HashSet::new();
309        let mut recommended = HashSet::new();
310        for row in &rows {
311            if !ids.insert(row.id.as_str()) {
312                return Err(LocalError::Catalog(format!(
313                    "model id {} appears twice",
314                    row.id
315                )));
316            }
317            if row.recommended && !recommended.insert(row.class) {
318                return Err(LocalError::Catalog(format!(
319                    "two recommended rows for class {:?}",
320                    row.class
321                )));
322            }
323        }
324        Ok(Self { rows })
325    }
326
327    /// Finds a row by id.
328    /// Input: the id.
329    /// Output: the row, or `None`.
330    pub fn get(&self, id: &str) -> Option<&LocalSpec> {
331        self.rows.iter().find(|r| r.id == id)
332    }
333
334    /// Returns every row in file order.
335    /// Input: none.
336    /// Output: the rows.
337    pub fn rows(&self) -> &[LocalSpec] {
338        &self.rows
339    }
340
341    /// Chooses a model for a device: the recommended row of `class` if
342    /// its RAM estimate fits `ram_budget_bytes`, else the fitting row with
343    /// the largest estimate. Output: the row, or `None` when none fits.
344    pub fn pick(&self, class: DeviceClass, ram_budget_bytes: u64) -> Option<&LocalSpec> {
345        let fitting: Vec<&LocalSpec> = self
346            .rows
347            .iter()
348            .filter(|r| r.class == class && r.ram_bytes <= ram_budget_bytes)
349            .collect();
350        fitting
351            .iter()
352            .find(|r| r.recommended)
353            .or_else(|| fitting.iter().max_by_key(|r| (r.ram_bytes, r.bytes)))
354            .copied()
355    }
356}