| 1 | //! Models.dev catalog schema and helpers. |
| 2 | //! |
| 3 | //! Models.dev is the upstream taxonomy CodeWhale should use for model facts, |
| 4 | //! provider offerings, pricing, limits, and capabilities. This module is |
| 5 | //! intentionally network-free: callers provide JSON from a bundled snapshot, |
| 6 | //! live refresh, or tests. Runtime fetch/cache policy belongs above this layer. |
| 7 | //! |
| 8 | //! The important boundary is the same one Models.dev uses: |
| 9 | //! - `models` are provider-agnostic model facts. |
| 10 | //! - `providers.*.models` are provider-scoped wire offerings. |
| 11 | //! |
| 12 | //! A provider row may inline inherited facts without exposing a canonical |
| 13 | //! `canonical_model_id` or legacy `base_model` link. CodeWhale must preserve that |
| 14 | //! distinction instead of inferring canonical ownership from wire IDs or prefixes. |
| 15 | |
| 16 | use std::collections::BTreeMap; |
| 17 | |
| 18 | use serde::{Deserialize, Serialize}; |
| 19 | |
| 20 | use crate::route::{ |
| 21 | CapabilityState, ModelId, ProviderId, ProviderModelOffering, RouteCapabilities, RouteLimits, |
| 22 | WireModelId, |
| 23 | }; |
| 24 | |
| 25 | /// Combined `{ models, providers }` endpoint used by Models.dev. |
| 26 | pub const MODELS_DEV_CATALOG_URL: &str = "https://models.dev/catalog.json"; |
| 27 | |
| 28 | /// Combined Models.dev catalog payload. |
| 29 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] |
| 30 | pub struct ModelsDevCatalog { |
| 31 | /// Reviewed presentation/transport facts, filled only from `catalog_corrections.json`; external documents cannot affect the compiled owner. |
| 32 | #[serde(skip)] |
| 33 | pub reviewed: crate::catalog::reviewed::ReviewedCatalog, |
| 34 | #[serde(default, rename = "_meta")] |
| 35 | pub meta: BTreeMap<String, serde_json::Value>, |
| 36 | /// Provider-agnostic model facts, keyed by canonical model id. |
| 37 | #[serde(default)] |
| 38 | pub models: BTreeMap<String, ModelsDevModel>, |
| 39 | /// Provider-scoped catalogs, keyed by provider id. |
| 40 | #[serde(default)] |
| 41 | pub providers: BTreeMap<String, ModelsDevProvider>, |
| 42 | } |
| 43 | |
| 44 | impl ModelsDevCatalog { |
| 45 | /// Parse a Models.dev combined catalog JSON payload. |
| 46 | /// |
| 47 | /// # Errors |
| 48 | /// Returns a serde error when the input is not valid Models.dev JSON. |
| 49 | pub fn parse_json(raw: &str) -> serde_json::Result<Self> { |
| 50 | let catalog: Self = serde_json::from_str(raw)?; |
| 51 | for provider in catalog.providers.values() { |
| 52 | for model in provider.models.values() { |
| 53 | if model.canonical_model_id.is_some() |
| 54 | && model.base_model.is_some() |
| 55 | && model.canonical_model_id.as_deref().map(str::trim) |
| 56 | != model.base_model.as_deref().map(str::trim) |
| 57 | { |
| 58 | return Err(<serde_json::Error as serde::de::Error>::custom( |
| 59 | "conflicting canonical_model_id and base_model", |
| 60 | )); |
| 61 | } |
| 62 | if let Some(cost) = &model.cost { |
| 63 | cost.validate()?; |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | Ok(catalog) |
| 68 | } |
| 69 | |
| 70 | /// Look up provider-agnostic model facts by canonical model id. |
| 71 | #[must_use] |
| 72 | pub fn model(&self, model_id: &str) -> Option<&ModelsDevModel> { |
| 73 | self.models.get(model_id.trim()) |
| 74 | } |
| 75 | |
| 76 | /// Look up a provider catalog by provider id. |
| 77 | #[must_use] |
| 78 | pub fn provider(&self, provider_id: &str) -> Option<&ModelsDevProvider> { |
| 79 | self.providers.get(provider_id.trim()) |
| 80 | } |
| 81 | |
| 82 | /// Look up a provider-scoped wire model row. |
| 83 | #[must_use] |
| 84 | pub fn provider_model( |
| 85 | &self, |
| 86 | provider_id: &str, |
| 87 | wire_model_id: &str, |
| 88 | ) -> Option<&ModelsDevProviderModel> { |
| 89 | self.provider(provider_id)?.models.get(wire_model_id.trim()) |
| 90 | } |
| 91 | |
| 92 | /// Resolve an intrinsic reasoning fact from canonical data or a |
| 93 | /// conflict-free explicit canonical join. A provider wire spelling |
| 94 | /// without that join never becomes an unscoped capability (#6032). |
| 95 | /// Missing and conflicting facts remain unknown. |
| 96 | #[must_use] |
| 97 | pub fn reasoning_support(&self, model_id: &str) -> Option<bool> { |
| 98 | crate::catalog::reviewed::intrinsic_model_in(self, model_id).and_then(|row| row.reasoning) |
| 99 | } |
| 100 | |
| 101 | /// Build a route offering from a provider-scoped Models.dev row. |
| 102 | /// |
| 103 | /// The canonical model is set only when the row carries an explicit |
| 104 | /// `canonical_model_id` or legacy `base_model` id; callers never guess a |
| 105 | /// canonical relationship from a prefix. |
| 106 | #[must_use] |
| 107 | pub fn provider_offering( |
| 108 | &self, |
| 109 | provider_id: &str, |
| 110 | wire_model_id: &str, |
| 111 | ) -> Option<ProviderModelOffering> { |
| 112 | let provider_key = provider_id.trim(); |
| 113 | let provider = self.provider(provider_key)?; |
| 114 | let model = provider.models.get(wire_model_id.trim())?; |
| 115 | let provider_id = provider.effective_id(provider_key); |
| 116 | Some(ProviderModelOffering { |
| 117 | provider: ProviderId::from(provider_id.clone()), |
| 118 | canonical_model: model.canonical_id().map(ModelId::from), |
| 119 | wire_model_id: WireModelId::from(model.id.clone()), |
| 120 | endpoint_key: "chat".to_string(), |
| 121 | default_for_provider: model.default_for_provider, |
| 122 | limits: model |
| 123 | .limit |
| 124 | .as_ref() |
| 125 | .map(RouteLimits::from) |
| 126 | .unwrap_or_default(), |
| 127 | capabilities: route_capabilities(&provider_id, model), |
| 128 | pricing: crate::pricing::route_pricing_sku_from_cost(model.cost.as_ref()), |
| 129 | }) |
| 130 | } |
| 131 | |
| 132 | /// Build route offerings for every normal text-chat model served by a |
| 133 | /// provider. |
| 134 | /// |
| 135 | /// Non-chat rows (for example TTS/audio-only offerings) stay in the parsed |
| 136 | /// catalog but are excluded from route resolution lists. |
| 137 | #[must_use] |
| 138 | pub fn provider_offerings(&self, provider_id: &str) -> Option<Vec<ProviderModelOffering>> { |
| 139 | let provider_key = provider_id.trim(); |
| 140 | let provider = self.provider(provider_key)?; |
| 141 | let provider_id = provider.effective_id(provider_key); |
| 142 | Some( |
| 143 | provider |
| 144 | .models |
| 145 | .values() |
| 146 | .filter(|model| model.supports_text_chat()) |
| 147 | .map(|model| ProviderModelOffering { |
| 148 | provider: ProviderId::from(provider_id.clone()), |
| 149 | canonical_model: model.canonical_id().map(ModelId::from), |
| 150 | wire_model_id: WireModelId::from(model.id.clone()), |
| 151 | endpoint_key: "chat".to_string(), |
| 152 | default_for_provider: model.default_for_provider, |
| 153 | limits: model |
| 154 | .limit |
| 155 | .as_ref() |
| 156 | .map(RouteLimits::from) |
| 157 | .unwrap_or_default(), |
| 158 | capabilities: route_capabilities(&provider_id, model), |
| 159 | pricing: crate::pricing::route_pricing_sku_from_cost(model.cost.as_ref()), |
| 160 | }) |
| 161 | .collect(), |
| 162 | ) |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | fn route_capabilities(provider_id: &str, model: &ModelsDevProviderModel) -> RouteCapabilities { |
| 167 | RouteCapabilities { |
| 168 | attachments: CapabilityState::from_optional_bool(model.attachment), |
| 169 | image_input: image_input_support(model.modalities.as_ref()), |
| 170 | reasoning: CapabilityState::from_optional_bool(model.reasoning), |
| 171 | native_tool_calls: CapabilityState::from_optional_bool(model.tool_call), |
| 172 | structured_output: CapabilityState::from_optional_bool(model.structured_output), |
| 173 | server_side_web_search: crate::route::documented_server_side_web_search( |
| 174 | provider_id, |
| 175 | &model.id, |
| 176 | ), |
| 177 | ..RouteCapabilities::default() |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | /// Resolve the exact image-input fact from a provider-owned modality block. |
| 182 | /// Missing or empty input metadata remains unknown; stated text-only input is |
| 183 | /// unsupported rather than silently treated as unknown. |
| 184 | #[must_use] |
| 185 | pub fn image_input_support(modalities: Option<&ModelsDevModalities>) -> CapabilityState { |
| 186 | let Some(modalities) = modalities else { |
| 187 | return CapabilityState::Unknown; |
| 188 | }; |
| 189 | if modalities.input.is_empty() { |
| 190 | return CapabilityState::Unknown; |
| 191 | } |
| 192 | CapabilityState::from_optional_bool(Some( |
| 193 | modalities |
| 194 | .input |
| 195 | .iter() |
| 196 | .any(|modality| modality.trim().eq_ignore_ascii_case("image")), |
| 197 | )) |
| 198 | } |
| 199 | |
| 200 | /// [`image_input_support`] for a fact from a layer that may be stale. |
| 201 | /// |
| 202 | /// A low-trust layer (the bundled offline seed) can say image input is |
| 203 | /// supported, but its text-only rows only mean "not known": the seed lags the |
| 204 | /// providers it describes, and treating its silence as a refusal would strip |
| 205 | /// the user's images before the request is sent. |
| 206 | #[must_use] |
| 207 | pub fn image_input_support_for( |
| 208 | modalities: Option<&ModelsDevModalities>, |
| 209 | low_trust: bool, |
| 210 | ) -> CapabilityState { |
| 211 | match image_input_support(modalities) { |
| 212 | CapabilityState::Unsupported if low_trust => CapabilityState::Unknown, |
| 213 | state => state, |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | /// Provider-agnostic model facts from `models.json` / `catalog.models`. |
| 218 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] |
| 219 | pub struct ModelsDevModel { |
| 220 | /// Canonical Models.dev model id, such as `zhipuai/glm-5.2`. |
| 221 | #[serde(default)] |
| 222 | pub id: String, |
| 223 | /// Human-friendly model name. |
| 224 | #[serde(default)] |
| 225 | pub name: Option<String>, |
| 226 | /// Model family, such as `glm`, `gpt`, or `claude`. |
| 227 | #[serde(default)] |
| 228 | pub family: Option<String>, |
| 229 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 230 | pub description: Option<String>, |
| 231 | #[serde(default, skip_serializing_if = "Option::is_none", rename = "type")] |
| 232 | pub model_type: Option<String>, |
| 233 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 234 | pub knowledge: Option<String>, |
| 235 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 236 | pub release_date: Option<String>, |
| 237 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 238 | pub last_updated: Option<String>, |
| 239 | /// Whether attachments are accepted. |
| 240 | #[serde(default)] |
| 241 | pub attachment: Option<bool>, |
| 242 | /// Whether the model supports reasoning. |
| 243 | #[serde(default)] |
| 244 | pub reasoning: Option<bool>, |
| 245 | /// Whether tool calling is supported. |
| 246 | #[serde(default)] |
| 247 | pub tool_call: Option<bool>, |
| 248 | /// Whether structured output is supported. |
| 249 | #[serde(default)] |
| 250 | pub structured_output: Option<bool>, |
| 251 | /// Whether temperature is supported. |
| 252 | #[serde(default)] |
| 253 | pub temperature: Option<bool>, |
| 254 | /// Whether weights are open. |
| 255 | #[serde(default)] |
| 256 | pub open_weights: Option<bool>, |
| 257 | /// Token limits. |
| 258 | #[serde(default)] |
| 259 | pub limit: Option<ModelsDevLimit>, |
| 260 | /// Input/output modalities. |
| 261 | #[serde(default)] |
| 262 | pub modalities: Option<ModelsDevModalities>, |
| 263 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 264 | pub license: Option<String>, |
| 265 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 266 | pub links: Option<Vec<serde_json::Value>>, |
| 267 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 268 | pub weights: Option<Vec<serde_json::Value>>, |
| 269 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 270 | pub benchmarks: Option<Vec<serde_json::Value>>, |
| 271 | } |
| 272 | |
| 273 | impl ModelsDevModel { |
| 274 | /// True when the model can be used for normal text chat. |
| 275 | #[must_use] |
| 276 | pub fn supports_text_chat(&self) -> bool { |
| 277 | supports_text_chat(self.modalities.as_ref()) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /// Provider-scoped model row from `api.json` / `catalog.providers.*.models`. |
| 282 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] |
| 283 | pub struct ModelsDevProviderModel { |
| 284 | /// Provider wire model id. |
| 285 | #[serde(default)] |
| 286 | pub id: String, |
| 287 | /// Optional explicit canonical model link from source TOML. |
| 288 | #[serde(default)] |
| 289 | pub base_model: Option<String>, |
| 290 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 291 | pub canonical_model_id: Option<String>, |
| 292 | /// Human-friendly model name. |
| 293 | #[serde(default)] |
| 294 | pub name: Option<String>, |
| 295 | /// Model family as exposed for this provider row. |
| 296 | #[serde(default)] |
| 297 | pub family: Option<String>, |
| 298 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 299 | pub description: Option<String>, |
| 300 | #[serde(default, skip_serializing_if = "Option::is_none", rename = "type")] |
| 301 | pub model_type: Option<String>, |
| 302 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 303 | pub knowledge: Option<String>, |
| 304 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 305 | pub release_date: Option<String>, |
| 306 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 307 | pub last_updated: Option<String>, |
| 308 | /// Whether this is the provider's default model in a CodeWhale snapshot. |
| 309 | #[serde(default, alias = "default")] |
| 310 | pub default_for_provider: bool, |
| 311 | /// Whether attachments are accepted. |
| 312 | #[serde(default)] |
| 313 | pub attachment: Option<bool>, |
| 314 | /// Whether the model supports reasoning. |
| 315 | #[serde(default)] |
| 316 | pub reasoning: Option<bool>, |
| 317 | /// Flexible reasoning-control metadata. |
| 318 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 319 | pub reasoning_options: Option<Vec<serde_json::Value>>, |
| 320 | /// Whether tool calling is supported. |
| 321 | #[serde(default)] |
| 322 | pub tool_call: Option<bool>, |
| 323 | /// Whether structured output is supported. |
| 324 | #[serde(default)] |
| 325 | pub structured_output: Option<bool>, |
| 326 | /// Whether temperature is supported. |
| 327 | #[serde(default)] |
| 328 | pub temperature: Option<bool>, |
| 329 | /// Whether weights are open through this offering. |
| 330 | #[serde(default)] |
| 331 | pub open_weights: Option<bool>, |
| 332 | /// Token limits for this provider offering. |
| 333 | #[serde(default)] |
| 334 | pub limit: Option<ModelsDevLimit>, |
| 335 | /// Input/output modalities for this provider offering. |
| 336 | #[serde(default)] |
| 337 | pub modalities: Option<ModelsDevModalities>, |
| 338 | /// Provider-scoped pricing. |
| 339 | #[serde(default)] |
| 340 | pub cost: Option<ModelsDevCost>, |
| 341 | /// Interleaved reasoning field hints. |
| 342 | #[serde(default)] |
| 343 | pub interleaved: Option<ModelsDevInterleaved>, |
| 344 | /// Per-model override of the provider's transport (`provider.npm`), used |
| 345 | /// when a gateway serves some models over a different wire than its |
| 346 | /// provider-level `npm` default (OpenCode Zen, #6705). |
| 347 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 348 | pub provider: Option<ModelsDevModelTransport>, |
| 349 | /// Lifecycle marker such as `deprecated` or `beta`; absent for current |
| 350 | /// rows. A model-aware gateway's deprecated row is not a routable wire |
| 351 | /// fact (#6705). |
| 352 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 353 | pub status: Option<String>, |
| 354 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 355 | pub experimental: Option<serde_json::Value>, |
| 356 | } |
| 357 | |
| 358 | /// A Models.dev model row's `provider` override: the AI SDK package that |
| 359 | /// serves this model when it differs from the provider default. |
| 360 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 361 | pub struct ModelsDevModelTransport { |
| 362 | /// AI SDK package identifier, such as `@ai-sdk/anthropic`. |
| 363 | #[serde(default)] |
| 364 | pub npm: Option<String>, |
| 365 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 366 | pub api: Option<String>, |
| 367 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 368 | pub shape: Option<String>, |
| 369 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 370 | pub body: Option<BTreeMap<String, serde_json::Value>>, |
| 371 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 372 | pub headers: Option<BTreeMap<String, String>>, |
| 373 | } |
| 374 | |
| 375 | impl ModelsDevProviderModel { |
| 376 | #[must_use] |
| 377 | pub fn canonical_id(&self) -> Option<&str> { |
| 378 | match ( |
| 379 | self.canonical_model_id.as_deref(), |
| 380 | self.base_model.as_deref(), |
| 381 | ) { |
| 382 | (Some(current), Some(legacy)) if current.trim() != legacy.trim() => None, |
| 383 | (current, legacy) => current.or(legacy), |
| 384 | } |
| 385 | .map(str::trim) |
| 386 | .filter(|id| !id.is_empty()) |
| 387 | } |
| 388 | |
| 389 | /// True when the provider offering can be used for normal text chat. |
| 390 | #[must_use] |
| 391 | pub fn supports_text_chat(&self) -> bool { |
| 392 | supports_text_chat(self.modalities.as_ref()) |
| 393 | } |
| 394 | |
| 395 | /// True when the catalog marks this offering `deprecated`. |
| 396 | #[must_use] |
| 397 | pub fn is_deprecated(&self) -> bool { |
| 398 | self.status |
| 399 | .as_deref() |
| 400 | .is_some_and(|status| status.trim().eq_ignore_ascii_case("deprecated")) |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | /// Provider row from Models.dev. |
| 405 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] |
| 406 | pub struct ModelsDevProvider { |
| 407 | /// Provider id, such as `zai`, `zhipuai`, or `openrouter`. |
| 408 | #[serde(default)] |
| 409 | pub id: String, |
| 410 | /// Human-friendly provider name. |
| 411 | #[serde(default)] |
| 412 | pub name: Option<String>, |
| 413 | /// Default API base URL, if published. |
| 414 | #[serde(default)] |
| 415 | pub api: Option<String>, |
| 416 | /// AI SDK package identifier, useful as a protocol hint. |
| 417 | #[serde(default)] |
| 418 | pub npm: Option<String>, |
| 419 | /// Documentation URL, if published. |
| 420 | #[serde(default)] |
| 421 | pub doc: Option<String>, |
| 422 | /// Environment variable names for credentials. |
| 423 | #[serde(default)] |
| 424 | pub env: Vec<String>, |
| 425 | /// Provider-scoped wire model rows. |
| 426 | #[serde(default)] |
| 427 | pub models: BTreeMap<String, ModelsDevProviderModel>, |
| 428 | } |
| 429 | |
| 430 | impl ModelsDevProvider { |
| 431 | /// Resolve the effective provider id for this row. |
| 432 | /// |
| 433 | /// Models.dev snapshots usually repeat the catalog key in the `id` field, |
| 434 | /// but generated JSON can omit it. Fall back to the catalog key so callers |
| 435 | /// never emit an empty [`ProviderId`]. |
| 436 | #[must_use] |
| 437 | fn effective_id(&self, provider_key: &str) -> String { |
| 438 | if self.id.trim().is_empty() { |
| 439 | provider_key.to_string() |
| 440 | } else { |
| 441 | self.id.trim().to_string() |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | /// Token limits. |
| 447 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 448 | pub struct ModelsDevLimit { |
| 449 | #[serde(default)] |
| 450 | pub context: Option<u64>, |
| 451 | #[serde(default)] |
| 452 | pub input: Option<u64>, |
| 453 | #[serde(default)] |
| 454 | pub output: Option<u64>, |
| 455 | } |
| 456 | |
| 457 | impl From<&ModelsDevLimit> for RouteLimits { |
| 458 | fn from(limit: &ModelsDevLimit) -> Self { |
| 459 | Self { |
| 460 | context_tokens: limit.context, |
| 461 | input_tokens: limit.input, |
| 462 | output_tokens: limit.output, |
| 463 | output_declared: false, |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | /// Input/output modalities. |
| 469 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 470 | pub struct ModelsDevModalities { |
| 471 | #[serde(default)] |
| 472 | pub input: Vec<String>, |
| 473 | #[serde(default)] |
| 474 | pub output: Vec<String>, |
| 475 | } |
| 476 | |
| 477 | /// Provider-scoped base rates and schedules, in USD per million tokens. |
| 478 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] |
| 479 | pub struct ModelsDevCost { |
| 480 | #[serde(default)] |
| 481 | pub input: Option<f64>, |
| 482 | #[serde(default)] |
| 483 | pub output: Option<f64>, |
| 484 | #[serde(default)] |
| 485 | pub cache_read: Option<f64>, |
| 486 | #[serde(default)] |
| 487 | pub cache_write: Option<f64>, |
| 488 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 489 | pub reasoning: Option<f64>, |
| 490 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 491 | pub input_audio: Option<f64>, |
| 492 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 493 | pub output_audio: Option<f64>, |
| 494 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 495 | pub tiers: Option<Vec<ModelsDevCostTier>>, |
| 496 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 497 | pub context_over_200k: Option<Box<ModelsDevCost>>, |
| 498 | } |
| 499 | |
| 500 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 501 | pub struct ModelsDevCostTier { |
| 502 | pub tier: ModelsDevContextTier, |
| 503 | #[serde(flatten)] |
| 504 | pub cost: ModelsDevCost, |
| 505 | } |
| 506 | |
| 507 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 508 | pub struct ModelsDevContextTier { |
| 509 | #[serde(rename = "type", default = "context_tier_type")] |
| 510 | pub kind: String, |
| 511 | pub size: u64, |
| 512 | } |
| 513 | |
| 514 | fn context_tier_type() -> String { |
| 515 | "context".to_string() |
| 516 | } |
| 517 | |
| 518 | impl ModelsDevCost { |
| 519 | pub(crate) fn validate(&self) -> serde_json::Result<()> { |
| 520 | if [ |
| 521 | self.input, |
| 522 | self.output, |
| 523 | self.cache_read, |
| 524 | self.cache_write, |
| 525 | self.reasoning, |
| 526 | self.input_audio, |
| 527 | self.output_audio, |
| 528 | ] |
| 529 | .into_iter() |
| 530 | .flatten() |
| 531 | .any(|rate| !rate.is_finite() || rate < 0.0) |
| 532 | { |
| 533 | return Err(<serde_json::Error as serde::de::Error>::custom( |
| 534 | "invalid published rate", |
| 535 | )); |
| 536 | } |
| 537 | let mut thresholds = std::collections::BTreeSet::new(); |
| 538 | for tier in self.tiers.iter().flatten() { |
| 539 | if !thresholds.insert((&tier.tier.kind, tier.tier.size)) { |
| 540 | return Err(<serde_json::Error as serde::de::Error>::custom( |
| 541 | "duplicate price tier", |
| 542 | )); |
| 543 | } |
| 544 | tier.cost.validate()?; |
| 545 | } |
| 546 | if let Some(legacy) = &self.context_over_200k { |
| 547 | legacy.validate()?; |
| 548 | if let Some(current) = self |
| 549 | .tiers |
| 550 | .iter() |
| 551 | .flatten() |
| 552 | .find(|tier| tier.tier.kind == "context" && tier.tier.size == 200_000) |
| 553 | && current.cost.base_rates() != legacy.base_rates() |
| 554 | { |
| 555 | return Err(<serde_json::Error as serde::de::Error>::custom( |
| 556 | "conflicting tiers and context_over_200k", |
| 557 | )); |
| 558 | } |
| 559 | } |
| 560 | Ok(()) |
| 561 | } |
| 562 | |
| 563 | fn base_rates(&self) -> [Option<f64>; 7] { |
| 564 | [ |
| 565 | self.input, |
| 566 | self.output, |
| 567 | self.cache_read, |
| 568 | self.cache_write, |
| 569 | self.reasoning, |
| 570 | self.input_audio, |
| 571 | self.output_audio, |
| 572 | ] |
| 573 | } |
| 574 | |
| 575 | #[must_use] |
| 576 | pub fn context_tiers(&self) -> Vec<ModelsDevCostTier> { |
| 577 | let mut tiers = self.tiers.clone().unwrap_or_default(); |
| 578 | if self.tiers.is_none() |
| 579 | && let Some(cost) = &self.context_over_200k |
| 580 | { |
| 581 | tiers.push(ModelsDevCostTier { |
| 582 | tier: ModelsDevContextTier { |
| 583 | kind: context_tier_type(), |
| 584 | size: 200_000, |
| 585 | }, |
| 586 | cost: (**cost).clone(), |
| 587 | }); |
| 588 | } |
| 589 | tiers.sort_by(|left, right| { |
| 590 | (&left.tier.kind, left.tier.size).cmp(&(&right.tier.kind, right.tier.size)) |
| 591 | }); |
| 592 | tiers |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | /// Interleaved reasoning metadata from a Models.dev provider row. |
| 597 | /// |
| 598 | /// Live Models.dev uses two shapes for this field, verified against |
| 599 | /// `https://models.dev/catalog.json` on 2026-07-07: |
| 600 | /// |
| 601 | /// - a bare boolean (`interleaved: true`) on ~32 provider rows, signalling the |
| 602 | /// provider supports interleaved reasoning without naming a wire field, and |
| 603 | /// - an object (`interleaved: { "field": "reasoning_content" }`) on the |
| 604 | /// majority of rows, naming the wire field that carries reasoning deltas. |
| 605 | /// |
| 606 | /// Modeling only the object shape made `serde_json::from_str::<ModelsDevCatalog>` |
| 607 | /// reject every boolean row before the live catalog could be used at all |
| 608 | /// (#4185). This untagged enum accepts both shapes while preserving the `field` |
| 609 | /// hint whenever the object form supplies one. |
| 610 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 611 | #[serde(untagged)] |
| 612 | pub enum ModelsDevInterleaved { |
| 613 | /// Boolean form: `interleaved: true` / `interleaved: false`. |
| 614 | Enabled(bool), |
| 615 | /// Object form: `interleaved: { "field": "reasoning_content" }`. |
| 616 | /// |
| 617 | /// `field` stays optional so an empty or partial object still parses, and |
| 618 | /// unknown sibling keys are ignored rather than rejected. |
| 619 | Field { |
| 620 | #[serde(default)] |
| 621 | field: Option<String>, |
| 622 | }, |
| 623 | } |
| 624 | |
| 625 | impl ModelsDevInterleaved { |
| 626 | /// Whether interleaved reasoning is enabled for this row. |
| 627 | /// |
| 628 | /// The boolean form reports its literal value. The object form is treated as |
| 629 | /// enabled because upstream only emits the object (naming a wire field) for |
| 630 | /// interleaved-capable rows. |
| 631 | #[must_use] |
| 632 | pub fn is_enabled(&self) -> bool { |
| 633 | match self { |
| 634 | Self::Enabled(enabled) => *enabled, |
| 635 | Self::Field { .. } => true, |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | /// The provider wire field carrying reasoning deltas, when upstream names |
| 640 | /// one. |
| 641 | /// |
| 642 | /// Only the object form supplies this; the boolean form returns `None`. |
| 643 | #[must_use] |
| 644 | pub fn field(&self) -> Option<&str> { |
| 645 | match self { |
| 646 | Self::Enabled(_) => None, |
| 647 | Self::Field { field } => field.as_deref(), |
| 648 | } |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | fn supports_text_chat(modalities: Option<&ModelsDevModalities>) -> bool { |
| 653 | let Some(modalities) = modalities else { |
| 654 | return true; |
| 655 | }; |
| 656 | // Treat an empty modality list the same as absent metadata. An incomplete |
| 657 | // catalog snapshot can deserialize to `Some({ input: [], output: [] })`, |
| 658 | // and `Iterator::any` over an empty slice is `false` — without this guard |
| 659 | // such rows would be silently dropped from chat offerings even though the |
| 660 | // `None` branch above defaults them to chat-capable. Only an explicitly |
| 661 | // populated, non-text list excludes the row. |
| 662 | let input_ok = modalities.input.is_empty() |
| 663 | || modalities |
| 664 | .input |
| 665 | .iter() |
| 666 | .any(|modality| modality.eq_ignore_ascii_case("text")); |
| 667 | let output_ok = modalities.output.is_empty() |
| 668 | || modalities |
| 669 | .output |
| 670 | .iter() |
| 671 | .any(|modality| modality.eq_ignore_ascii_case("text")); |
| 672 | input_ok && output_ok |
| 673 | } |
| 674 | |
| 675 | #[cfg(test)] |
| 676 | mod tests { |
| 677 | use super::*; |
| 678 | |
| 679 | const GLM_FIXTURE: &str = r#"{ |
| 680 | "models": { |
| 681 | "zhipuai/glm-5.2": { |
| 682 | "id": "zhipuai/glm-5.2", |
| 683 | "name": "GLM-5.2", |
| 684 | "family": "glm", |
| 685 | "reasoning": true, |
| 686 | "tool_call": true, |
| 687 | "structured_output": true, |
| 688 | "modalities": { "input": ["text"], "output": ["text"] }, |
| 689 | "limit": { "context": 1000000, "output": 131072 }, |
| 690 | "open_weights": true |
| 691 | } |
| 692 | }, |
| 693 | "providers": { |
| 694 | "zhipuai": { |
| 695 | "id": "zhipuai", |
| 696 | "name": "Zhipu AI", |
| 697 | "api": "https://open.bigmodel.cn/api/paas/v4", |
| 698 | "npm": "@ai-sdk/openai-compatible", |
| 699 | "env": ["ZHIPU_API_KEY"], |
| 700 | "models": { |
| 701 | "glm-5.2": { |
| 702 | "id": "glm-5.2", |
| 703 | "name": "GLM-5.2", |
| 704 | "family": "glm", |
| 705 | "reasoning": true, |
| 706 | "reasoning_options": [{ "type": "effort", "values": ["high", "max"] }], |
| 707 | "tool_call": true, |
| 708 | "structured_output": true, |
| 709 | "modalities": { "input": ["text"], "output": ["text"] }, |
| 710 | "limit": { "context": 1000000, "output": 131072 }, |
| 711 | "cost": { "input": 1.4, "output": 4.4, "cache_read": 0.26 } |
| 712 | } |
| 713 | } |
| 714 | }, |
| 715 | "zai": { |
| 716 | "id": "zai", |
| 717 | "name": "Z.AI", |
| 718 | "api": "https://api.z.ai/api/paas/v4", |
| 719 | "npm": "@ai-sdk/openai-compatible", |
| 720 | "env": ["ZHIPU_API_KEY"], |
| 721 | "models": { |
| 722 | "glm-5.2": { |
| 723 | "id": "glm-5.2", |
| 724 | "family": "glm", |
| 725 | "reasoning": true, |
| 726 | "tool_call": true, |
| 727 | "modalities": { "input": ["text"], "output": ["text"] }, |
| 728 | "cost": { "input": 1.4, "output": 4.4 } |
| 729 | } |
| 730 | } |
| 731 | } |
| 732 | } |
| 733 | }"#; |
| 734 | |
| 735 | #[test] |
| 736 | fn parses_models_dev_catalog_layers_without_joining_by_prefix() { |
| 737 | let catalog = ModelsDevCatalog::parse_json(GLM_FIXTURE).expect("fixture parses"); |
| 738 | |
| 739 | let canonical = catalog.model("zhipuai/glm-5.2").expect("canonical model"); |
| 740 | assert_eq!(canonical.family.as_deref(), Some("glm")); |
| 741 | assert_eq!( |
| 742 | canonical.limit.as_ref().and_then(|limit| limit.context), |
| 743 | Some(1_000_000) |
| 744 | ); |
| 745 | assert!(canonical.supports_text_chat()); |
| 746 | |
| 747 | let provider = catalog.provider("zhipuai").expect("provider"); |
| 748 | assert_eq!( |
| 749 | provider.api.as_deref(), |
| 750 | Some("https://open.bigmodel.cn/api/paas/v4") |
| 751 | ); |
| 752 | assert_eq!(provider.npm.as_deref(), Some("@ai-sdk/openai-compatible")); |
| 753 | assert_eq!(provider.env, ["ZHIPU_API_KEY"]); |
| 754 | |
| 755 | let offering = catalog |
| 756 | .provider_model("zhipuai", "glm-5.2") |
| 757 | .expect("provider model"); |
| 758 | assert_eq!(offering.id, "glm-5.2"); |
| 759 | assert_eq!(offering.reasoning, Some(true)); |
| 760 | assert_eq!( |
| 761 | offering.cost.as_ref().and_then(|cost| cost.cache_read), |
| 762 | Some(0.26) |
| 763 | ); |
| 764 | assert!(offering.supports_text_chat()); |
| 765 | assert_eq!( |
| 766 | offering.base_model, None, |
| 767 | "generated JSON does not prove a canonical join" |
| 768 | ); |
| 769 | |
| 770 | let route_offering = catalog |
| 771 | .provider_offering("zhipuai", "glm-5.2") |
| 772 | .expect("route offering"); |
| 773 | assert_eq!(route_offering.limits.context_tokens, Some(1_000_000)); |
| 774 | assert_eq!(route_offering.limits.output_tokens, Some(131_072)); |
| 775 | assert_eq!( |
| 776 | route_offering.capabilities.reasoning, |
| 777 | CapabilityState::Supported |
| 778 | ); |
| 779 | assert_eq!( |
| 780 | route_offering.capabilities.native_tool_calls, |
| 781 | CapabilityState::Supported |
| 782 | ); |
| 783 | assert_eq!( |
| 784 | route_offering.capabilities.structured_output, |
| 785 | CapabilityState::Supported |
| 786 | ); |
| 787 | assert_eq!( |
| 788 | route_offering.capabilities.streaming, |
| 789 | CapabilityState::Unknown |
| 790 | ); |
| 791 | } |
| 792 | |
| 793 | #[test] |
| 794 | fn provider_offering_preserves_wire_id_without_inferred_canonical_model() { |
| 795 | let catalog = ModelsDevCatalog::parse_json(GLM_FIXTURE).expect("fixture parses"); |
| 796 | let offering = catalog |
| 797 | .provider_offering("zai", "glm-5.2") |
| 798 | .expect("offering"); |
| 799 | |
| 800 | assert_eq!(offering.provider.as_str(), "zai"); |
| 801 | assert_eq!(offering.wire_model_id.as_str(), "glm-5.2"); |
| 802 | assert_eq!(offering.canonical_model, None); |
| 803 | assert_eq!(offering.endpoint_key, "chat"); |
| 804 | } |
| 805 | |
| 806 | #[test] |
| 807 | fn provider_offering_uses_explicit_base_model_when_present() { |
| 808 | let raw = r#"{ |
| 809 | "providers": { |
| 810 | "openrouter": { |
| 811 | "id": "openrouter", |
| 812 | "models": { |
| 813 | "z-ai/glm-5.2": { |
| 814 | "id": "z-ai/glm-5.2", |
| 815 | "base_model": "zhipuai/glm-5.2" |
| 816 | } |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | }"#; |
| 821 | let catalog = ModelsDevCatalog::parse_json(raw).expect("fixture parses"); |
| 822 | let offering = catalog |
| 823 | .provider_offering("openrouter", "z-ai/glm-5.2") |
| 824 | .expect("offering"); |
| 825 | |
| 826 | assert_eq!( |
| 827 | offering.canonical_model.as_ref().map(ModelId::as_str), |
| 828 | Some("zhipuai/glm-5.2") |
| 829 | ); |
| 830 | assert_eq!(offering.wire_model_id.as_str(), "z-ai/glm-5.2"); |
| 831 | } |
| 832 | |
| 833 | #[test] |
| 834 | fn reasoning_support_requires_canonical_rows_or_explicit_joins() { |
| 835 | let catalog = ModelsDevCatalog::parse_json(GLM_FIXTURE).expect("fixture parses"); |
| 836 | // The canonical row is intrinsic; the bare wire row has no proven join. |
| 837 | assert_eq!(catalog.reasoning_support("zhipuai/glm-5.2"), Some(true)); |
| 838 | assert_eq!(catalog.reasoning_support("glm-5.2"), None); |
| 839 | // Unknown id stays unknown; no prefix or alias inference. |
| 840 | assert_eq!(catalog.reasoning_support("glm-5.1"), None); |
| 841 | assert_eq!(catalog.reasoning_support("zai/glm-5.2"), None); |
| 842 | // Ids must match exactly, not after provider splitting. |
| 843 | assert_eq!(catalog.reasoning_support("zhipuai/glm-5.2 "), Some(true)); |
| 844 | } |
| 845 | |
| 846 | #[test] |
| 847 | fn reasoning_support_stays_unknown_on_disagreeing_rows() { |
| 848 | let raw = r#"{ |
| 849 | "providers": { |
| 850 | "one": { |
| 851 | "models": { |
| 852 | "split-fact": { "id": "split-fact", "reasoning": true } |
| 853 | } |
| 854 | }, |
| 855 | "two": { |
| 856 | "models": { |
| 857 | "split-fact": { "id": "split-fact", "reasoning": false } |
| 858 | } |
| 859 | }, |
| 860 | "three": { |
| 861 | "models": { |
| 862 | "silent-fact": { "id": "silent-fact" } |
| 863 | } |
| 864 | } |
| 865 | } |
| 866 | }"#; |
| 867 | let catalog = ModelsDevCatalog::parse_json(raw).expect("fixture parses"); |
| 868 | // A row that states nothing is not a vote; one sourced row resolves. |
| 869 | assert_eq!(catalog.reasoning_support("silent-fact"), None); |
| 870 | // Providers disagreeing on the fact stays unknown — never guessed (#6032). |
| 871 | assert_eq!(catalog.reasoning_support("split-fact"), None); |
| 872 | } |
| 873 | |
| 874 | #[test] |
| 875 | fn provider_offerings_emit_chat_rows_and_skip_non_text_outputs() { |
| 876 | let raw = r#"{ |
| 877 | "providers": { |
| 878 | "zai": { |
| 879 | "models": { |
| 880 | "glm-5.2": { |
| 881 | "id": "glm-5.2", |
| 882 | "base_model": "zhipuai/glm-5.2", |
| 883 | "default": true, |
| 884 | "modalities": { "input": ["text"], "output": ["text"] } |
| 885 | }, |
| 886 | "glm-voice": { |
| 887 | "id": "glm-voice", |
| 888 | "modalities": { "input": ["text"], "output": ["audio"] } |
| 889 | } |
| 890 | } |
| 891 | } |
| 892 | } |
| 893 | }"#; |
| 894 | let catalog = ModelsDevCatalog::parse_json(raw).expect("fixture parses"); |
| 895 | let offerings = catalog |
| 896 | .provider_offerings("zai") |
| 897 | .expect("provider offerings"); |
| 898 | |
| 899 | assert_eq!(offerings.len(), 1); |
| 900 | assert_eq!(offerings[0].provider.as_str(), "zai"); |
| 901 | assert_eq!(offerings[0].wire_model_id.as_str(), "glm-5.2"); |
| 902 | assert_eq!( |
| 903 | offerings[0].canonical_model.as_ref().map(ModelId::as_str), |
| 904 | Some("zhipuai/glm-5.2") |
| 905 | ); |
| 906 | assert!(offerings[0].default_for_provider); |
| 907 | } |
| 908 | |
| 909 | #[test] |
| 910 | fn non_text_output_is_not_a_chat_model() { |
| 911 | let model = ModelsDevProviderModel { |
| 912 | id: "mimo-v2.5-tts".to_string(), |
| 913 | modalities: Some(ModelsDevModalities { |
| 914 | input: vec!["text".to_string()], |
| 915 | output: vec!["audio".to_string()], |
| 916 | }), |
| 917 | ..Default::default() |
| 918 | }; |
| 919 | |
| 920 | assert!(!model.supports_text_chat()); |
| 921 | } |
| 922 | |
| 923 | #[test] |
| 924 | fn empty_modalities_struct_is_chat_capable() { |
| 925 | // `"modalities": {}` deserializes to Some(empty); it must default to |
| 926 | // chat-capable just like absent modality metadata (the None branch), |
| 927 | // otherwise rows from incomplete snapshots are silently dropped. |
| 928 | let provider_model = ModelsDevProviderModel { |
| 929 | modalities: Some(ModelsDevModalities::default()), |
| 930 | ..Default::default() |
| 931 | }; |
| 932 | assert!(provider_model.supports_text_chat()); |
| 933 | |
| 934 | let canonical = ModelsDevModel { |
| 935 | modalities: Some(ModelsDevModalities::default()), |
| 936 | ..Default::default() |
| 937 | }; |
| 938 | assert!(canonical.supports_text_chat()); |
| 939 | |
| 940 | // A list populated with only non-text entries still excludes the row. |
| 941 | let audio_only = ModelsDevProviderModel { |
| 942 | modalities: Some(ModelsDevModalities { |
| 943 | input: vec!["text".to_string()], |
| 944 | output: vec!["audio".to_string()], |
| 945 | }), |
| 946 | ..Default::default() |
| 947 | }; |
| 948 | assert!(!audio_only.supports_text_chat()); |
| 949 | } |
| 950 | |
| 951 | #[test] |
| 952 | fn image_input_support_preserves_unknown_and_text_only_facts() { |
| 953 | assert_eq!(image_input_support(None), CapabilityState::Unknown); |
| 954 | assert_eq!( |
| 955 | image_input_support(Some(&ModelsDevModalities::default())), |
| 956 | CapabilityState::Unknown |
| 957 | ); |
| 958 | assert_eq!( |
| 959 | image_input_support(Some(&ModelsDevModalities { |
| 960 | input: vec!["text".to_string()], |
| 961 | output: vec!["text".to_string()], |
| 962 | })), |
| 963 | CapabilityState::Unsupported |
| 964 | ); |
| 965 | assert_eq!( |
| 966 | image_input_support(Some(&ModelsDevModalities { |
| 967 | input: vec!["text".to_string(), "image".to_string()], |
| 968 | output: vec!["text".to_string()], |
| 969 | })), |
| 970 | CapabilityState::Supported |
| 971 | ); |
| 972 | } |
| 973 | |
| 974 | #[test] |
| 975 | fn low_trust_text_only_rows_never_refuse_images() { |
| 976 | let text_only = ModelsDevModalities { |
| 977 | input: vec!["text".to_string()], |
| 978 | output: vec!["text".to_string()], |
| 979 | }; |
| 980 | let vision = ModelsDevModalities { |
| 981 | input: vec!["text".to_string(), "image".to_string()], |
| 982 | output: vec!["text".to_string()], |
| 983 | }; |
| 984 | assert_eq!( |
| 985 | image_input_support_for(Some(&text_only), true), |
| 986 | CapabilityState::Unknown |
| 987 | ); |
| 988 | assert_eq!( |
| 989 | image_input_support_for(Some(&text_only), false), |
| 990 | CapabilityState::Unsupported |
| 991 | ); |
| 992 | for low_trust in [true, false] { |
| 993 | assert_eq!( |
| 994 | image_input_support_for(Some(&vision), low_trust), |
| 995 | CapabilityState::Supported |
| 996 | ); |
| 997 | assert_eq!( |
| 998 | image_input_support_for(None, low_trust), |
| 999 | CapabilityState::Unknown |
| 1000 | ); |
| 1001 | } |
| 1002 | } |
| 1003 | |
| 1004 | #[test] |
| 1005 | fn interleaved_boolean_true_parses_and_reports_enabled() { |
| 1006 | // 32 live provider rows (e.g. `vercel`, `amazon-bedrock`) send |
| 1007 | // `interleaved: true`; the object-only model rejected all of them. |
| 1008 | let raw = r#"{ |
| 1009 | "providers": { |
| 1010 | "vercel": { |
| 1011 | "models": { |
| 1012 | "zai/glm-4.7": { "id": "zai/glm-4.7", "interleaved": true } |
| 1013 | } |
| 1014 | } |
| 1015 | } |
| 1016 | }"#; |
| 1017 | let catalog = ModelsDevCatalog::parse_json(raw).expect("boolean interleaved parses"); |
| 1018 | let model = catalog |
| 1019 | .provider_model("vercel", "zai/glm-4.7") |
| 1020 | .expect("provider model"); |
| 1021 | let interleaved = model.interleaved.as_ref().expect("interleaved present"); |
| 1022 | assert_eq!(interleaved, &ModelsDevInterleaved::Enabled(true)); |
| 1023 | assert!(interleaved.is_enabled()); |
| 1024 | assert_eq!(interleaved.field(), None); |
| 1025 | } |
| 1026 | |
| 1027 | #[test] |
| 1028 | fn interleaved_boolean_false_parses_and_reports_disabled() { |
| 1029 | let raw = r#"{ |
| 1030 | "providers": { |
| 1031 | "custom": { |
| 1032 | "models": { |
| 1033 | "house-model": { "id": "house-model", "interleaved": false } |
| 1034 | } |
| 1035 | } |
| 1036 | } |
| 1037 | }"#; |
| 1038 | let catalog = ModelsDevCatalog::parse_json(raw).expect("boolean interleaved parses"); |
| 1039 | let model = catalog |
| 1040 | .provider_model("custom", "house-model") |
| 1041 | .expect("provider model"); |
| 1042 | let interleaved = model.interleaved.as_ref().expect("interleaved present"); |
| 1043 | assert_eq!(interleaved, &ModelsDevInterleaved::Enabled(false)); |
| 1044 | assert!(!interleaved.is_enabled()); |
| 1045 | assert_eq!(interleaved.field(), None); |
| 1046 | } |
| 1047 | |
| 1048 | #[test] |
| 1049 | fn interleaved_object_form_preserves_field_metadata() { |
| 1050 | // The majority of live rows use `{ "field": "reasoning_content" }`; the |
| 1051 | // fix must keep parsing them and surface the named wire field. |
| 1052 | let raw = r#"{ |
| 1053 | "providers": { |
| 1054 | "alibaba-cn": { |
| 1055 | "models": { |
| 1056 | "glm-5.2": { |
| 1057 | "id": "glm-5.2", |
| 1058 | "interleaved": { "field": "reasoning_content" } |
| 1059 | } |
| 1060 | } |
| 1061 | } |
| 1062 | } |
| 1063 | }"#; |
| 1064 | let catalog = ModelsDevCatalog::parse_json(raw).expect("object interleaved parses"); |
| 1065 | let model = catalog |
| 1066 | .provider_model("alibaba-cn", "glm-5.2") |
| 1067 | .expect("provider model"); |
| 1068 | let interleaved = model.interleaved.as_ref().expect("interleaved present"); |
| 1069 | assert_eq!(interleaved.field(), Some("reasoning_content")); |
| 1070 | assert!(interleaved.is_enabled()); |
| 1071 | } |
| 1072 | |
| 1073 | #[test] |
| 1074 | fn interleaved_object_tolerates_empty_and_unknown_keys() { |
| 1075 | // An empty object and an object with only unmodeled sibling keys must |
| 1076 | // still parse (object form, no named field) rather than erroring. |
| 1077 | let raw = r#"{ |
| 1078 | "providers": { |
| 1079 | "custom": { |
| 1080 | "models": { |
| 1081 | "empty-obj": { "id": "empty-obj", "interleaved": {} }, |
| 1082 | "future-obj": { |
| 1083 | "id": "future-obj", |
| 1084 | "interleaved": { "future_hint": "x" } |
| 1085 | } |
| 1086 | } |
| 1087 | } |
| 1088 | } |
| 1089 | }"#; |
| 1090 | let catalog = ModelsDevCatalog::parse_json(raw).expect("tolerant interleaved parses"); |
| 1091 | |
| 1092 | let empty = catalog |
| 1093 | .provider_model("custom", "empty-obj") |
| 1094 | .and_then(|m| m.interleaved.clone()) |
| 1095 | .expect("empty object interleaved present"); |
| 1096 | assert_eq!(empty, ModelsDevInterleaved::Field { field: None }); |
| 1097 | assert_eq!(empty.field(), None); |
| 1098 | assert!(empty.is_enabled()); |
| 1099 | |
| 1100 | let future = catalog |
| 1101 | .provider_model("custom", "future-obj") |
| 1102 | .and_then(|m| m.interleaved.clone()) |
| 1103 | .expect("future object interleaved present"); |
| 1104 | assert_eq!(future.field(), None); |
| 1105 | } |
| 1106 | |
| 1107 | #[test] |
| 1108 | fn live_ish_mixed_interleaved_sample_deserializes() { |
| 1109 | // A representative slice of live `catalog.json`: boolean and object |
| 1110 | // interleaved rows side by side, plus an unmodeled top-level provider |
| 1111 | // key (`doc`) and an unmodeled model key to prove unknown upstream |
| 1112 | // fields are ignored safely. This is the acceptance "live-ish sample". |
| 1113 | let raw = r#"{ |
| 1114 | "providers": { |
| 1115 | "amazon-bedrock": { |
| 1116 | "id": "amazon-bedrock", |
| 1117 | "doc": "https://docs.aws.amazon.com/bedrock/", |
| 1118 | "models": { |
| 1119 | "anthropic.claude-opus": { |
| 1120 | "id": "anthropic.claude-opus", |
| 1121 | "reasoning": true, |
| 1122 | "interleaved": true, |
| 1123 | "some_future_flag": 7, |
| 1124 | "modalities": { "input": ["text"], "output": ["text"] } |
| 1125 | } |
| 1126 | } |
| 1127 | }, |
| 1128 | "alibaba-cn": { |
| 1129 | "id": "alibaba-cn", |
| 1130 | "models": { |
| 1131 | "deepseek-v4-flash": { |
| 1132 | "id": "deepseek-v4-flash", |
| 1133 | "interleaved": { "field": "reasoning_content" }, |
| 1134 | "modalities": { "input": ["text"], "output": ["text"] } |
| 1135 | } |
| 1136 | } |
| 1137 | } |
| 1138 | } |
| 1139 | }"#; |
| 1140 | let catalog = ModelsDevCatalog::parse_json(raw).expect("live-ish sample parses"); |
| 1141 | |
| 1142 | let bedrock = catalog |
| 1143 | .provider_model("amazon-bedrock", "anthropic.claude-opus") |
| 1144 | .expect("bedrock row"); |
| 1145 | assert_eq!( |
| 1146 | bedrock.interleaved, |
| 1147 | Some(ModelsDevInterleaved::Enabled(true)) |
| 1148 | ); |
| 1149 | |
| 1150 | let alibaba = catalog |
| 1151 | .provider_model("alibaba-cn", "deepseek-v4-flash") |
| 1152 | .expect("alibaba row"); |
| 1153 | assert_eq!( |
| 1154 | alibaba.interleaved.as_ref().and_then(|i| i.field()), |
| 1155 | Some("reasoning_content") |
| 1156 | ); |
| 1157 | |
| 1158 | // Both rows still resolve as chat offerings; interleaved does not |
| 1159 | // interfere with route resolution. |
| 1160 | assert_eq!( |
| 1161 | catalog |
| 1162 | .provider_offerings("amazon-bedrock") |
| 1163 | .map(|rows| rows.len()), |
| 1164 | Some(1) |
| 1165 | ); |
| 1166 | } |
| 1167 | |
| 1168 | #[test] |
| 1169 | fn provider_offerings_keep_rows_with_empty_modalities_object() { |
| 1170 | // End-to-end guard for the empty-modalities case at the offering layer: |
| 1171 | // a custom/local provider row with `"modalities": {}` must still emit a |
| 1172 | // chat offering rather than being filtered out of route resolution. |
| 1173 | let raw = r#"{ |
| 1174 | "providers": { |
| 1175 | "custom": { |
| 1176 | "models": { |
| 1177 | "house-model": { "id": "house-model", "modalities": {} } |
| 1178 | } |
| 1179 | } |
| 1180 | } |
| 1181 | }"#; |
| 1182 | let catalog = ModelsDevCatalog::parse_json(raw).expect("fixture parses"); |
| 1183 | let offerings = catalog |
| 1184 | .provider_offerings("custom") |
| 1185 | .expect("provider offerings"); |
| 1186 | |
| 1187 | assert_eq!(offerings.len(), 1); |
| 1188 | assert_eq!(offerings[0].wire_model_id.as_str(), "house-model"); |
| 1189 | // `id` was omitted on the provider row → effective id is the catalog key. |
| 1190 | assert_eq!(offerings[0].provider.as_str(), "custom"); |
| 1191 | } |
| 1192 | } |
| 1193 |