| 1 | //! Persisted, operator-declared input to the existing catalog. These records |
| 2 | //! describe one exact route; they never create credentials or model aliases. |
| 3 | |
| 4 | use std::collections::{BTreeMap, BTreeSet}; |
| 5 | |
| 6 | use serde::{Deserialize, Deserializer, Serialize}; |
| 7 | |
| 8 | use super::{CatalogOffering, CatalogSource, base_url_fingerprint}; |
| 9 | use crate::models_dev::{ModelsDevCost, ModelsDevLimit, ModelsDevModalities}; |
| 10 | |
| 11 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 12 | pub struct ConfiguredModel { |
| 13 | pub provider: String, |
| 14 | pub base_url: String, |
| 15 | /// Exact, case-sensitive wire identity. The label is never sent instead. |
| 16 | pub id: String, |
| 17 | #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")] |
| 18 | pub model_type: Option<String>, |
| 19 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 20 | pub display_name: Option<String>, |
| 21 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 22 | #[serde(deserialize_with = "deserialize_limit")] |
| 23 | pub limit: Option<ModelsDevLimit>, |
| 24 | /// Per million tokens in `cost_currency` (USD unless declared), same shape as the catalog. |
| 25 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 26 | #[serde(deserialize_with = "deserialize_cost")] |
| 27 | pub cost: Option<ModelsDevCost>, |
| 28 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 29 | pub cost_currency: Option<String>, |
| 30 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 31 | #[serde(deserialize_with = "deserialize_modalities")] |
| 32 | pub modalities: Option<ModelsDevModalities>, |
| 33 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 34 | pub attachment: Option<bool>, |
| 35 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 36 | pub reasoning: Option<bool>, |
| 37 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 38 | pub tool_call: Option<bool>, |
| 39 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 40 | pub structured_output: Option<bool>, |
| 41 | /// Keep future metadata intact through typed config saves. |
| 42 | #[serde(flatten)] |
| 43 | pub extras: BTreeMap<String, toml::Value>, |
| 44 | } |
| 45 | |
| 46 | impl ConfiguredModel { |
| 47 | pub fn matches_route(&self, provider: &str, base_url: &str) -> bool { |
| 48 | !base_url.contains(['@', '?', '#']) |
| 49 | && self.provider == provider |
| 50 | && base_url_fingerprint(&self.base_url) == base_url_fingerprint(base_url) |
| 51 | } |
| 52 | |
| 53 | pub fn resolved_cost_currency(&self) -> Option<crate::pricing::Currency> { |
| 54 | match self.cost_currency.as_deref() { |
| 55 | None => Some(crate::pricing::Currency::Usd), |
| 56 | Some(raw) => { |
| 57 | if raw.chars().any(char::is_control) { |
| 58 | return None; |
| 59 | } |
| 60 | match raw.trim().to_ascii_lowercase().as_str() { |
| 61 | "usd" => Some(crate::pricing::Currency::Usd), |
| 62 | "cny" => Some(crate::pricing::Currency::Cny), |
| 63 | _ => None, |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// Unknown fields stay unknown; no sibling, alias, or provider fact is |
| 70 | /// inherited. Source is assigned here and cannot be supplied by the file. |
| 71 | pub fn to_catalog_offering(&self) -> CatalogOffering { |
| 72 | let cost = if self.resolved_cost_currency() == Some(crate::pricing::Currency::Usd) { |
| 73 | self.cost.clone() |
| 74 | } else { |
| 75 | None |
| 76 | }; |
| 77 | CatalogOffering { |
| 78 | provider: self.provider.clone(), |
| 79 | wire_model_id: self.id.clone(), |
| 80 | endpoint_key: "chat".into(), |
| 81 | model_type: self.model_type.clone(), |
| 82 | provider_api: Some(self.base_url.clone()), |
| 83 | limit: self.limit.clone(), |
| 84 | cost, |
| 85 | cost_source: (self.resolved_cost_currency() != Some(crate::pricing::Currency::Usd)) |
| 86 | .then_some(CatalogSource::ConfigOverride), |
| 87 | modalities: self.modalities.clone(), |
| 88 | attachment: self.attachment, |
| 89 | reasoning: self.reasoning, |
| 90 | tool_call: self.tool_call, |
| 91 | structured_output: self.structured_output, |
| 92 | source: CatalogSource::ConfigOverride, |
| 93 | ..CatalogOffering::default() |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | pub fn validate_configured_models(models: &[ConfiguredModel]) -> anyhow::Result<()> { |
| 99 | let mut identities = BTreeSet::new(); |
| 100 | for (index, model) in models.iter().enumerate() { |
| 101 | // Error messages name fields, never echo untrusted values or URLs. |
| 102 | let invalid = |field| anyhow::anyhow!("custom_models[{index}].{field} is invalid"); |
| 103 | for (field, value) in [("provider", &model.provider), ("id", &model.id)] { |
| 104 | if value.is_empty() |
| 105 | || value.len() > 256 |
| 106 | || value.chars().any(char::is_whitespace) |
| 107 | || value.chars().any(char::is_control) |
| 108 | { |
| 109 | return Err(invalid(field)); |
| 110 | } |
| 111 | } |
| 112 | if model.id.eq_ignore_ascii_case("auto") { |
| 113 | return Err(invalid("id")); |
| 114 | } |
| 115 | let Some((scheme, rest)) = model.base_url.split_once("://") else { |
| 116 | return Err(invalid("base_url")); |
| 117 | }; |
| 118 | if !matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https") |
| 119 | || rest.split('/').next().is_none_or(str::is_empty) |
| 120 | || model.base_url.contains(['@', '?', '#']) |
| 121 | || model |
| 122 | .base_url |
| 123 | .chars() |
| 124 | .any(|c| c.is_whitespace() || c.is_control()) |
| 125 | { |
| 126 | return Err(invalid("base_url")); |
| 127 | } |
| 128 | if model |
| 129 | .display_name |
| 130 | .as_ref() |
| 131 | .is_some_and(|name| name.trim().is_empty() || name.chars().any(char::is_control)) |
| 132 | { |
| 133 | return Err(invalid("display_name")); |
| 134 | } |
| 135 | if model.model_type.as_deref().is_some_and(|kind| { |
| 136 | kind.is_empty() || kind.len() > 64 || kind.chars().any(char::is_control) |
| 137 | }) { |
| 138 | return Err(invalid("type")); |
| 139 | } |
| 140 | if let Some(limit) = &model.limit |
| 141 | && ([limit.context, limit.input, limit.output] |
| 142 | .into_iter() |
| 143 | .flatten() |
| 144 | .any(|value| value == 0 || value > u64::from(u32::MAX)) |
| 145 | || limit.context.is_some_and(|context| { |
| 146 | limit.input.is_some_and(|input| input > context) |
| 147 | || limit.output.is_some_and(|output| output > context) |
| 148 | })) |
| 149 | { |
| 150 | return Err(invalid("limit")); |
| 151 | } |
| 152 | if model.cost.as_ref().is_some_and(|cost| { |
| 153 | !crate::pricing::catalog_cost_is_valid(cost) |
| 154 | || cost.context_tiers().iter().any(|tier| { |
| 155 | tier.tier.kind != "context" || !tier.cost.context_tiers().is_empty() |
| 156 | }) |
| 157 | }) { |
| 158 | return Err(invalid("cost")); |
| 159 | } |
| 160 | if model.resolved_cost_currency().is_none() { |
| 161 | return Err(invalid("cost_currency")); |
| 162 | } |
| 163 | if model.extras.keys().any(|key| { |
| 164 | matches!( |
| 165 | key.as_str(), |
| 166 | "source" |
| 167 | | "canonical_model" |
| 168 | | "aliases" |
| 169 | | "api_key" |
| 170 | | "auth" |
| 171 | | "headers" |
| 172 | | "endpoint_key" |
| 173 | | "default_for_provider" |
| 174 | ) |
| 175 | }) { |
| 176 | return Err(invalid("metadata authority")); |
| 177 | } |
| 178 | if !identities.insert(( |
| 179 | model.provider.clone(), |
| 180 | base_url_fingerprint(&model.base_url), |
| 181 | model.id.clone(), |
| 182 | )) { |
| 183 | return Err(invalid("duplicate route")); |
| 184 | } |
| 185 | } |
| 186 | Ok(()) |
| 187 | } |
| 188 | |
| 189 | pub fn deserialize_configured_models<'de, D>( |
| 190 | deserializer: D, |
| 191 | ) -> Result<Option<Vec<ConfiguredModel>>, D::Error> |
| 192 | where |
| 193 | D: Deserializer<'de>, |
| 194 | { |
| 195 | let models = Option::<Vec<ConfiguredModel>>::deserialize(deserializer)?; |
| 196 | validate_configured_models(models.as_deref().unwrap_or_default()) |
| 197 | .map_err(serde::de::Error::custom)?; |
| 198 | Ok(models) |
| 199 | } |
| 200 | |
| 201 | // Nested units and limits have precise meanings. Reject unrecognized keys |
| 202 | // instead of silently dropping a currency, tier, or other pricing condition. |
| 203 | fn deserialize_known<'de, D: Deserializer<'de>, T: serde::de::DeserializeOwned>( |
| 204 | d: D, |
| 205 | fields: &[&str], |
| 206 | ) -> Result<Option<T>, D::Error> { |
| 207 | let value = Option::<toml::Value>::deserialize(d)?; |
| 208 | value |
| 209 | .map(|value| { |
| 210 | if value |
| 211 | .as_table() |
| 212 | .is_none_or(|table| table.keys().any(|key| !fields.contains(&key.as_str()))) |
| 213 | { |
| 214 | return Err(serde::de::Error::custom( |
| 215 | "unsupported nested custom model metadata field", |
| 216 | )); |
| 217 | } |
| 218 | value |
| 219 | .try_into() |
| 220 | .map_err(|_| serde::de::Error::custom("invalid custom model metadata")) |
| 221 | }) |
| 222 | .transpose() |
| 223 | } |
| 224 | fn deserialize_limit<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ModelsDevLimit>, D::Error> { |
| 225 | deserialize_known(d, &["context", "input", "output"]) |
| 226 | } |
| 227 | fn deserialize_cost<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ModelsDevCost>, D::Error> { |
| 228 | fn supported_fields(value: &toml::Value, is_tier: bool) -> bool { |
| 229 | let Some(table) = value.as_table() else { |
| 230 | return false; |
| 231 | }; |
| 232 | table.iter().all(|(key, value)| match key.as_str() { |
| 233 | "input" | "output" | "cache_read" | "cache_write" | "reasoning" | "input_audio" |
| 234 | | "output_audio" => true, |
| 235 | "tiers" => value |
| 236 | .as_array() |
| 237 | .is_some_and(|tiers| tiers.iter().all(|tier| supported_fields(tier, true))), |
| 238 | "context_over_200k" => supported_fields(value, false), |
| 239 | "tier" if is_tier => value.as_table().is_some_and(|tier| { |
| 240 | tier.keys() |
| 241 | .all(|key| matches!(key.as_str(), "type" | "size")) |
| 242 | }), |
| 243 | _ => false, |
| 244 | }) |
| 245 | } |
| 246 | |
| 247 | Option::<toml::Value>::deserialize(d)? |
| 248 | .map(|value| { |
| 249 | if !supported_fields(&value, false) { |
| 250 | return Err(serde::de::Error::custom( |
| 251 | "unsupported nested custom model metadata field", |
| 252 | )); |
| 253 | } |
| 254 | value |
| 255 | .try_into() |
| 256 | .map_err(|_| serde::de::Error::custom("invalid custom model metadata")) |
| 257 | }) |
| 258 | .transpose() |
| 259 | } |
| 260 | fn deserialize_modalities<'de, D: Deserializer<'de>>( |
| 261 | d: D, |
| 262 | ) -> Result<Option<ModelsDevModalities>, D::Error> { |
| 263 | deserialize_known(d, &["input", "output"]) |
| 264 | } |
| 265 | |
| 266 | #[cfg(test)] |
| 267 | mod tests { |
| 268 | use super::*; |
| 269 | use crate::pricing::Currency; |
| 270 | |
| 271 | fn parse_custom_models(toml_str: &str) -> Result<Vec<ConfiguredModel>, toml::de::Error> { |
| 272 | #[derive(Deserialize)] |
| 273 | struct Wrapper { |
| 274 | #[serde(default, deserialize_with = "deserialize_configured_models")] |
| 275 | custom_models: Option<Vec<ConfiguredModel>>, |
| 276 | } |
| 277 | let parsed: Wrapper = toml::from_str(toml_str)?; |
| 278 | Ok(parsed.custom_models.unwrap_or_default()) |
| 279 | } |
| 280 | |
| 281 | #[test] |
| 282 | fn custom_model_cost_currency_defaults_to_usd_and_supports_cny_without_usd_catalog_projection() |
| 283 | { |
| 284 | let models = parse_custom_models( |
| 285 | r#" |
| 286 | [[custom_models]] |
| 287 | provider = "openai" |
| 288 | base_url = "https://token.sensenova.cn/v1" |
| 289 | id = "deepseek-flash" |
| 290 | cost_currency = "CNY" |
| 291 | cost = { input = 2.0, output = 8.0, cache_read = 0.04 } |
| 292 | |
| 293 | [[custom_models]] |
| 294 | provider = "openai" |
| 295 | base_url = "https://api.example.com/v1" |
| 296 | id = "usd-model" |
| 297 | cost = { input = 1.0, output = 3.0 } |
| 298 | "#, |
| 299 | ) |
| 300 | .expect("valid custom_models with CNY and default USD"); |
| 301 | |
| 302 | assert_eq!(models[0].resolved_cost_currency(), Some(Currency::Cny)); |
| 303 | assert!(models[0].to_catalog_offering().cost.is_none()); |
| 304 | let configured = models[0].to_catalog_offering(); |
| 305 | assert_eq!(configured.cost_source, Some(CatalogSource::ConfigOverride)); |
| 306 | let lower = CatalogOffering { |
| 307 | cost: models[1].cost.clone(), |
| 308 | cost_source: None, |
| 309 | source: CatalogSource::Bundled, |
| 310 | ..configured.clone() |
| 311 | }; |
| 312 | let mut completed = configured.clone(); |
| 313 | completed.complete_from(&lower, Some(&models[0].base_url)); |
| 314 | assert!(completed.cost.is_none()); |
| 315 | assert_eq!(completed.pricing_source(), &CatalogSource::ConfigOverride); |
| 316 | let snapshot = crate::catalog::CatalogCompiler::new() |
| 317 | .with_bundled(vec![lower.clone()]) |
| 318 | .with_overrides(vec![configured]) |
| 319 | .compile(); |
| 320 | assert_eq!(snapshot.offerings.len(), 1); |
| 321 | let merged = &snapshot.offerings[0]; |
| 322 | assert!(merged.cost.is_none()); |
| 323 | assert_eq!(merged.pricing_source(), &CatalogSource::ConfigOverride); |
| 324 | assert!(crate::pricing::OfferingPricing::from_catalog_offering(merged).is_none()); |
| 325 | let mut usd = models[0].clone(); |
| 326 | usd.cost_currency = Some("USD".into()); |
| 327 | let mut usd_offering = usd.to_catalog_offering(); |
| 328 | usd_offering.complete_from(&lower, Some(&usd.base_url)); |
| 329 | assert_eq!(usd_offering.cost, usd.cost); |
| 330 | |
| 331 | assert_eq!(models[1].resolved_cost_currency(), Some(Currency::Usd)); |
| 332 | assert_eq!( |
| 333 | models[1] |
| 334 | .to_catalog_offering() |
| 335 | .cost |
| 336 | .as_ref() |
| 337 | .and_then(|c| c.input), |
| 338 | Some(1.0) |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | #[test] |
| 343 | fn custom_model_rejects_unknown_cost_currency() { |
| 344 | for bad in ["eur", "", "rmb\n"] { |
| 345 | let toml_str = format!( |
| 346 | r#" |
| 347 | [[custom_models]] |
| 348 | provider = "openai" |
| 349 | base_url = "https://token.sensenova.cn/v1" |
| 350 | id = "deepseek-flash" |
| 351 | cost_currency = {bad:?} |
| 352 | cost = {{ input = 2.0, output = 8.0 }} |
| 353 | "# |
| 354 | ); |
| 355 | let err = parse_custom_models(&toml_str).expect_err("unknown currency must fail"); |
| 356 | assert!( |
| 357 | err.to_string().contains("cost_currency"), |
| 358 | "unexpected error for {bad:?}: {err}" |
| 359 | ); |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 |