返回 CodeWhale
model_reference.rs
根目录 / crates / config / src / model_reference.rs
1 //! Factual model reference database (#3205, #2300).
2 //!
3 //! A browsable, read-only projection of the compiled catalog into per-offering
4 //! "fact cards": the model id as-is, the serving provider and its kind, the
5 //! context window, the price, and the modality (text vs multimodal). It exists
6 //! to answer "what are this model's stated attributes?", nothing more.
7 //!
8 //! This layer is **labels only**. It performs no selection, routing, tiering,
9 //! or ranking — it never decides which model to use, and it carries no
10 //! `strong`/`balanced`/`fast` or role concept. It is a superset-free view over
11 //! [`crate::catalog::CatalogOffering`] rows.
12 //!
13 //! Honesty rule (shared with #2608 / #3085): an attribute the catalog layer did
14 //! not state is reported as **unknown**, never guessed. A local/custom endpoint
15 //! with no catalog facts yields `Unknown` modality, `None` context window, and
16 //! an unknown price — its model id is still preserved verbatim. Nothing here is
17 //! inferred from a model-id prefix.
18
19 use std::collections::{BTreeMap, BTreeSet};
20
21 use serde::{Deserialize, Serialize};
22
23 use crate::ProviderKind;
24 use crate::catalog::{CatalogOffering, CatalogSnapshot, CatalogSource, bundled_catalog_offerings};
25 use crate::models_dev::ModelsDevModalities;
26 use crate::pricing::{Currency, OfferingPricing};
27
28 /// Coarse, factual input/output modality label for a model.
29 ///
30 /// `text` vs `multimodal` is derived from the union of stated input/output
31 /// modalities. Absent modality metadata is [`Modality::Unknown`], distinct from
32 /// a stated text-only model — "we were not told" is not "text only".
33 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
34 #[serde(rename_all = "snake_case")]
35 pub enum Modality {
36 /// Every stated modality is text.
37 Text,
38 /// At least one stated modality is non-text (image/audio/video/…).
39 Multimodal,
40 /// No modality metadata was stated for this row.
41 #[default]
42 Unknown,
43 }
44
45 impl Modality {
46 /// Classify the modality from a Models.dev-shaped modality block.
47 ///
48 /// Returns [`Modality::Unknown`] for absent metadata or an empty list,
49 /// [`Modality::Multimodal`] when any stated input/output modality is not
50 /// `text`, and [`Modality::Text`] when the only stated modalities are text.
51 #[must_use]
52 pub fn from_modalities(modalities: Option<&ModelsDevModalities>) -> Self {
53 let Some(modalities) = modalities else {
54 return Self::Unknown;
55 };
56 let mut saw_any = false;
57 for modality in modalities.input.iter().chain(modalities.output.iter()) {
58 let trimmed = modality.trim();
59 if trimmed.is_empty() {
60 continue;
61 }
62 saw_any = true;
63 if !trimmed.eq_ignore_ascii_case("text") {
64 return Self::Multimodal;
65 }
66 }
67 if saw_any { Self::Text } else { Self::Unknown }
68 }
69
70 /// Stable lowercase label.
71 #[must_use]
72 pub fn as_str(self) -> &'static str {
73 match self {
74 Self::Text => "text",
75 Self::Multimodal => "multimodal",
76 Self::Unknown => "unknown",
77 }
78 }
79 }
80
81 /// A factual reference card for one provider offering.
82 ///
83 /// Every field is either a stated fact or an explicit unknown. This is a
84 /// labels-only projection: it carries no routing, tier, or selection concept.
85 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86 pub struct ModelReferenceCard {
87 /// Provider id serving this offering, exactly as the catalog row states it.
88 pub provider: String,
89 /// Resolved built-in provider kind, when the provider id maps to one.
90 ///
91 /// `None` for an unrecognized / user-named custom provider — an unknown
92 /// kind, not a guess.
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub provider_kind: Option<ProviderKind>,
95 /// The provider wire model id, verbatim. Never normalized or prefixed.
96 pub model_id: String,
97 /// Canonical model identity, only when the row carried an explicit join.
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub canonical_model: Option<String>,
100 /// Model family / series, when stated.
101 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub family: Option<String>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub display_name: Option<String>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub description: Option<String>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub max_input: Option<u64>,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub last_updated: Option<String>,
111 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
112 pub fact_sources: std::collections::BTreeMap<String, CatalogSource>,
113 /// Context-window tokens, when stated.
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub context_window: Option<u64>,
116 /// Max-output tokens, when stated.
117 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub max_output: Option<u64>,
119 /// Text vs multimodal, or unknown.
120 pub modality: Modality,
121 /// Per-token pricing facts, when priced. `None` is unknown, never free.
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub pricing: Option<OfferingPricing>,
124 /// Provenance of the underlying catalog row (bundled / live / override).
125 pub source: CatalogSource,
126 }
127
128 impl ModelReferenceCard {
129 /// Project a catalog offering into its factual reference card.
130 #[must_use]
131 pub fn from_offering(offering: &CatalogOffering) -> Self {
132 Self {
133 provider: offering.provider.clone(),
134 provider_kind: ProviderKind::parse(&offering.provider),
135 model_id: offering.wire_model_id.clone(),
136 canonical_model: offering.canonical_model.clone(),
137 family: offering.family.clone(),
138 display_name: offering.name.clone(),
139 description: offering.description.clone(),
140 max_input: offering.limit.as_ref().and_then(|limit| limit.input),
141 last_updated: offering.last_updated.clone(),
142 fact_sources: offering.fact_sources.clone(),
143 context_window: offering.limit.as_ref().and_then(|limit| limit.context),
144 max_output: offering.limit.as_ref().and_then(|limit| limit.output),
145 modality: Modality::from_modalities(offering.modalities.as_ref()),
146 pricing: OfferingPricing::from_catalog_offering(offering),
147 source: offering.source.clone(),
148 }
149 }
150
151 /// Label for the resolved provider kind, or `"unknown"`.
152 #[must_use]
153 pub fn provider_kind_label(&self) -> &'static str {
154 self.provider_kind.map_or("unknown", ProviderKind::as_str)
155 }
156
157 /// Human context-window label such as `"1M"`, `"131K"`, `"512"`, or
158 /// `"unknown"`. The exact token count remains on [`Self::context_window`].
159 #[must_use]
160 pub fn context_window_label(&self) -> String {
161 humanize_tokens(self.context_window)
162 }
163
164 /// Human max-output label, same shape as [`Self::context_window_label`].
165 #[must_use]
166 pub fn max_output_label(&self) -> String {
167 humanize_tokens(self.max_output)
168 }
169
170 /// Short factual price label, e.g. `"$0.30 / $1.20 per Mtok"`, or
171 /// `"unknown"` when no per-token input/output rate is sourced.
172 ///
173 /// A `?` in one slot means that single rate is unknown while the other is
174 /// stated; a fully unknown price collapses to `"unknown"` rather than a
175 /// fabricated zero.
176 #[must_use]
177 pub fn price_label(&self) -> String {
178 let Some(pricing) = self.pricing.as_ref() else {
179 return "unknown".to_string();
180 };
181 if matches!(
182 pricing.status_label_at(crate::catalog::now_unix()),
183 "stale" | "unverified" | "unavailable"
184 ) || (pricing.input_per_million.is_none() && pricing.output_per_million.is_none())
185 {
186 return "unknown".to_string();
187 }
188 let symbol = currency_symbol(&pricing.currency);
189 let render = |value: Option<f64>| match value {
190 Some(rate) => {
191 let rounded = format!("{rate:.2}");
192 if rounded.parse::<f64>().ok() == Some(rate) {
193 format!("{symbol}{rounded}")
194 } else {
195 format!("{symbol}{rate}")
196 }
197 }
198 None => "?".to_string(),
199 };
200 let suffix = currency_suffix(&pricing.currency);
201 format!(
202 "{} / {} per Mtok{suffix}",
203 render(pricing.input_per_million),
204 render(pricing.output_per_million),
205 )
206 }
207 }
208
209 /// A browsable, read-only factual reference database of model offerings.
210 ///
211 /// Cards are sorted by `(provider, model id)` and de-duplicated on that
212 /// identity, so the database is deterministic regardless of input order.
213 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
214 pub struct ModelReferenceDatabase {
215 cards: Vec<ModelReferenceCard>,
216 }
217
218 impl ModelReferenceDatabase {
219 /// Build from raw catalog offerings.
220 ///
221 /// Rows are keyed by `(provider, model id)`; a later row with the same
222 /// identity replaces an earlier one, matching catalog merge semantics.
223 #[must_use]
224 pub fn from_offerings(offerings: &[CatalogOffering]) -> Self {
225 let mut by_identity: BTreeMap<(String, String), ModelReferenceCard> = BTreeMap::new();
226 for offering in offerings {
227 let card = ModelReferenceCard::from_offering(offering);
228 by_identity.insert((card.provider.clone(), card.model_id.clone()), card);
229 }
230 Self {
231 cards: by_identity.into_values().collect(),
232 }
233 }
234
235 /// Build from a compiled catalog snapshot (bundled < live < overrides).
236 #[must_use]
237 pub fn from_snapshot(snapshot: &CatalogSnapshot) -> Self {
238 Self::from_offerings(&snapshot.offerings)
239 }
240
241 /// Build from CodeWhale's offline/stale bundled catalog snapshot (#4188).
242 ///
243 /// Prefer a live/compiled [`CatalogSnapshot`] when available. The bundled
244 /// set needs no credentials or network and remains the offline fallback
245 /// every install carries.
246 #[must_use]
247 pub fn bundled() -> Self {
248 Self::from_offerings(&bundled_catalog_offerings())
249 }
250
251 /// All cards, in stable `(provider, model id)` order.
252 #[must_use]
253 pub fn cards(&self) -> &[ModelReferenceCard] {
254 &self.cards
255 }
256
257 /// Number of cards.
258 #[must_use]
259 pub fn len(&self) -> usize {
260 self.cards.len()
261 }
262
263 /// Whether the database is empty.
264 #[must_use]
265 pub fn is_empty(&self) -> bool {
266 self.cards.is_empty()
267 }
268
269 /// Distinct provider ids present, sorted.
270 #[must_use]
271 pub fn providers(&self) -> Vec<&str> {
272 self.cards
273 .iter()
274 .map(|card| card.provider.as_str())
275 .collect::<BTreeSet<_>>()
276 .into_iter()
277 .collect()
278 }
279
280 /// All cards served by one provider id.
281 #[must_use]
282 pub fn for_provider(&self, provider: &str) -> Vec<&ModelReferenceCard> {
283 self.cards
284 .iter()
285 .filter(|card| card.provider == provider)
286 .collect()
287 }
288
289 /// Find a card by `(provider, model id)`.
290 #[must_use]
291 pub fn find(&self, provider: &str, model_id: &str) -> Option<&ModelReferenceCard> {
292 self.cards
293 .iter()
294 .find(|card| card.provider == provider && card.model_id == model_id)
295 }
296 }
297
298 /// Round a token count to a short human label (`"1M"`, `"203K"`, `"512"`), or
299 /// `"unknown"` for an absent count. Used for display only; callers needing the
300 /// exact value read the `Option<u64>` field directly.
301 fn humanize_tokens(tokens: Option<u64>) -> String {
302 let Some(tokens) = tokens else {
303 return "unknown".to_string();
304 };
305 if tokens >= 1_000_000 {
306 let millions = tokens as f64 / 1_000_000.0;
307 let rendered = format!("{millions:.2}");
308 let trimmed = rendered.trim_end_matches('0').trim_end_matches('.');
309 format!("{trimmed}M")
310 } else if tokens >= 1_000 {
311 format!("{}K", (tokens as f64 / 1_000.0).round() as u64)
312 } else {
313 tokens.to_string()
314 }
315 }
316
317 fn currency_symbol(currency: &Currency) -> &'static str {
318 match currency {
319 Currency::Usd => "$",
320 Currency::Cny => "¥",
321 Currency::Other(_) => "",
322 }
323 }
324
325 fn currency_suffix(currency: &Currency) -> String {
326 match currency {
327 Currency::Usd | Currency::Cny => String::new(),
328 Currency::Other(code) => format!(" {code}"),
329 }
330 }
331
332 #[cfg(test)]
333 mod tests {
334 use super::*;
335 use crate::models_dev::{ModelsDevCost, ModelsDevLimit};
336
337 fn offering(provider: &str, wire: &str) -> CatalogOffering {
338 CatalogOffering {
339 provider: provider.to_string(),
340 wire_model_id: wire.to_string(),
341 endpoint_key: "chat".to_string(),
342 source: CatalogSource::Bundled,
343 ..Default::default()
344 }
345 }
346
347 #[test]
348 fn modality_text_multimodal_and_unknown() {
349 assert_eq!(Modality::from_modalities(None), Modality::Unknown);
350 assert_eq!(
351 Modality::from_modalities(Some(&ModelsDevModalities::default())),
352 Modality::Unknown,
353 "an empty modality block is unknown, not text-only"
354 );
355 assert_eq!(
356 Modality::from_modalities(Some(&ModelsDevModalities {
357 input: vec!["text".to_string()],
358 output: vec!["text".to_string()],
359 })),
360 Modality::Text
361 );
362 assert_eq!(
363 Modality::from_modalities(Some(&ModelsDevModalities {
364 input: vec!["text".to_string(), "image".to_string()],
365 output: vec!["text".to_string()],
366 })),
367 Modality::Multimodal
368 );
369 // Case-insensitive and tolerant of an output-only non-text modality.
370 assert_eq!(
371 Modality::from_modalities(Some(&ModelsDevModalities {
372 input: vec!["TEXT".to_string()],
373 output: vec!["Audio".to_string()],
374 })),
375 Modality::Multimodal
376 );
377 }
378
379 #[test]
380 fn card_projects_stated_facts() {
381 let row = CatalogOffering {
382 family: Some("deepseek".to_string()),
383 limit: Some(ModelsDevLimit {
384 context: Some(1_000_000),
385 input: None,
386 output: Some(384_000),
387 }),
388 cost: Some(ModelsDevCost {
389 input: Some(0.3),
390 output: Some(1.2),
391 cache_read: Some(0.06),
392 cache_write: None,
393 ..Default::default()
394 }),
395 modalities: Some(ModelsDevModalities {
396 input: vec!["text".to_string()],
397 output: vec!["text".to_string()],
398 }),
399 ..offering("deepseek", "deepseek-v4-pro")
400 };
401 let card = ModelReferenceCard::from_offering(&row);
402
403 assert_eq!(card.provider, "deepseek");
404 assert_eq!(card.provider_kind, Some(ProviderKind::Deepseek));
405 assert_eq!(card.provider_kind_label(), "deepseek");
406 assert_eq!(card.model_id, "deepseek-v4-pro");
407 assert_eq!(card.family.as_deref(), Some("deepseek"));
408 assert_eq!(card.context_window, Some(1_000_000));
409 assert_eq!(card.context_window_label(), "1M");
410 assert_eq!(card.max_output, Some(384_000));
411 assert_eq!(card.max_output_label(), "384K");
412 assert_eq!(card.modality, Modality::Text);
413 assert_eq!(card.price_label(), "$0.30 / $1.20 per Mtok");
414 }
415
416 #[test]
417 fn custom_local_row_is_all_unknown_but_keeps_model_id_verbatim() {
418 // A user-named custom endpoint with no catalog facts: provider kind,
419 // context window, modality, and price are all unknown — never guessed —
420 // and the model id is preserved exactly.
421 let row = CatalogOffering {
422 source: CatalogSource::UserOverride,
423 ..offering("my-local-llm", "Vendor/Custom-Model_v1")
424 };
425 let card = ModelReferenceCard::from_offering(&row);
426
427 assert_eq!(card.provider_kind, None);
428 assert_eq!(card.provider_kind_label(), "unknown");
429 assert_eq!(card.model_id, "Vendor/Custom-Model_v1");
430 assert_eq!(card.context_window, None);
431 assert_eq!(card.context_window_label(), "unknown");
432 assert_eq!(card.max_output_label(), "unknown");
433 assert_eq!(card.modality, Modality::Unknown);
434 assert_eq!(card.price_label(), "unknown");
435 }
436
437 #[test]
438 fn unpriced_and_cache_only_rows_report_unknown_price_never_zero() {
439 // No cost block at all.
440 let unpriced = ModelReferenceCard::from_offering(&offering("deepseek", "deepseek-v4-pro"));
441 assert_eq!(unpriced.price_label(), "unknown");
442 assert!(unpriced.pricing.is_none());
443
444 // A cost object priced only on cache classes is still unknown for the
445 // headline input/output rate label.
446 let cache_only = CatalogOffering {
447 cost: Some(ModelsDevCost {
448 input: None,
449 output: None,
450 cache_read: Some(0.05),
451 cache_write: None,
452 ..Default::default()
453 }),
454 ..offering("acme", "house-model")
455 };
456 assert_eq!(
457 ModelReferenceCard::from_offering(&cache_only).price_label(),
458 "unknown"
459 );
460 }
461
462 #[test]
463 fn partial_price_renders_known_rate_and_marks_the_other_unknown() {
464 let row = CatalogOffering {
465 cost: Some(ModelsDevCost {
466 input: Some(5.0),
467 output: None,
468 cache_read: None,
469 cache_write: None,
470 ..Default::default()
471 }),
472 ..offering("openai", "gpt-5.5")
473 };
474 assert_eq!(
475 ModelReferenceCard::from_offering(&row).price_label(),
476 "$5.00 / ? per Mtok"
477 );
478 }
479
480 #[test]
481 fn database_is_sorted_deduped_and_queryable() {
482 let rows = vec![
483 CatalogOffering {
484 limit: Some(ModelsDevLimit {
485 context: Some(1),
486 input: None,
487 output: None,
488 }),
489 ..offering("zai", "GLM-5.2")
490 },
491 offering("deepseek", "deepseek-v4-pro"),
492 // Duplicate identity with a higher context wins (last-write).
493 CatalogOffering {
494 limit: Some(ModelsDevLimit {
495 context: Some(1_000_000),
496 input: None,
497 output: None,
498 }),
499 ..offering("zai", "GLM-5.2")
500 },
501 ];
502 let db = ModelReferenceDatabase::from_offerings(&rows);
503
504 assert_eq!(db.len(), 2, "duplicate (provider, model) collapses to one");
505 // Sorted by (provider, model id): deepseek before zai.
506 assert_eq!(db.cards()[0].provider, "deepseek");
507 assert_eq!(db.cards()[1].provider, "zai");
508 assert_eq!(db.providers(), vec!["deepseek", "zai"]);
509 assert_eq!(db.for_provider("zai").len(), 1);
510 assert_eq!(
511 db.find("zai", "GLM-5.2")
512 .and_then(|card| card.context_window),
513 Some(1_000_000),
514 "last-write-wins kept the richer row"
515 );
516 assert!(db.find("zai", "missing").is_none());
517 }
518
519 #[test]
520 fn bundled_database_is_nonempty_and_honest() {
521 let db = ModelReferenceDatabase::bundled();
522 assert!(!db.is_empty());
523 assert!(
524 db.len() >= 20,
525 "bundled offline snapshot should carry seed offerings, got {}",
526 db.len()
527 );
528
529 // Every card preserves a non-empty model id and resolves a known kind
530 // for the bundled (first-class) providers.
531 for card in db.cards() {
532 assert!(!card.model_id.is_empty());
533 assert!(
534 card.provider_kind.is_some(),
535 "bundled provider {} should map to a known kind",
536 card.provider
537 );
538 }
539
540 // A DeepSeek-native row: context window known, price honestly unknown
541 // (the bundled snapshot omits DeepSeek-native per-token pricing).
542 let deepseek = db
543 .find("deepseek", "deepseek-v4-pro")
544 .expect("bundled deepseek row");
545 assert_eq!(deepseek.context_window, Some(1_048_576));
546 assert_eq!(deepseek.modality, Modality::Text);
547 assert_eq!(deepseek.price_label(), "unknown");
548
549 // A priced row surfaces its stated per-token rate.
550 let minimax = db
551 .find("minimax", "MiniMax-M2.7")
552 .expect("bundled minimax row");
553 assert_eq!(minimax.price_label(), "$0.30 / $1.20 per Mtok");
554
555 // MiniMax-M3 carries its own base rate and a context tier.
556 let minimax_m3 = db
557 .find("minimax", "MiniMax-M3")
558 .expect("bundled minimax m3 row");
559 assert_eq!(minimax_m3.price_label(), "$0.30 / $1.20 per Mtok");
560 assert_eq!(minimax_m3.pricing.as_ref().unwrap().context_tiers.len(), 1);
561 }
562
563 #[test]
564 fn humanize_tokens_shapes() {
565 assert_eq!(humanize_tokens(None), "unknown");
566 assert_eq!(humanize_tokens(Some(512)), "512");
567 assert_eq!(humanize_tokens(Some(131_072)), "131K");
568 assert_eq!(humanize_tokens(Some(1_000_000)), "1M");
569 assert_eq!(humanize_tokens(Some(1_050_000)), "1.05M");
570 }
571 }
572
572 lines RUST