fix(openrouter): resolve variant suffixes like :free and :nitro to the base model (#12979)
Signed-off-by: Cassian433 <262026629+Cassian433@users.noreply.github.com> Co-authored-by: Cassian433 <262026629+Cassian433@users.noreply.github.com>
This commit is contained in:
@@ -6,7 +6,8 @@ mod registry;
|
||||
|
||||
pub use model::{CanonicalModel, Limit, Modalities, Modality, Pricing, PricingTier, ThinkingMode};
|
||||
pub use name_builder::{
|
||||
canonical_name, map_provider_name, map_to_canonical_model, strip_version_suffix,
|
||||
canonical_name, map_provider_name, map_to_canonical_model, strip_openrouter_variant,
|
||||
strip_version_suffix,
|
||||
};
|
||||
pub use registry::{
|
||||
fetch_remote_catalog, load_cached_catalog, CanonicalModelRegistry, RemoteCatalog,
|
||||
@@ -167,16 +168,48 @@ fn should_clear_catalog_pricing(provider: &str) -> bool {
|
||||
}
|
||||
|
||||
pub fn maybe_get_canonical_model(provider: &str, model: &str) -> Option<CanonicalModel> {
|
||||
maybe_get_canonical_model_with_variant_fallback(provider, model).map(|(canonical, _)| canonical)
|
||||
}
|
||||
|
||||
/// Resolve model metadata and report whether an OpenRouter variant used its base row.
|
||||
pub fn maybe_get_canonical_model_with_variant_fallback(
|
||||
provider: &str,
|
||||
model: &str,
|
||||
) -> Option<(CanonicalModel, bool)> {
|
||||
let registry = CanonicalModelRegistry::bundled().ok()?;
|
||||
|
||||
let canonical_id = map_to_canonical_model(provider, model, ®istry)?;
|
||||
let (canonical_id, is_variant_fallback) =
|
||||
match map_to_canonical_model(provider, model, ®istry) {
|
||||
Some(id) => (id, false),
|
||||
None if provider == "openrouter" => (
|
||||
map_to_canonical_model(provider, strip_openrouter_variant(model)?, ®istry)?,
|
||||
true,
|
||||
),
|
||||
None => return None,
|
||||
};
|
||||
let mut canonical = if let Some((canon_provider, canon_model)) = canonical_id.split_once('/') {
|
||||
registry.get(canon_provider, canon_model).cloned()?
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
if should_clear_catalog_pricing(provider) {
|
||||
if is_variant_fallback {
|
||||
// Variants share capabilities, but endpoint output caps and prices can differ.
|
||||
canonical.limit.output = None;
|
||||
// `:thinking` is the one tag that changes capabilities: it serves the reasoning mode.
|
||||
if model.ends_with(":thinking") {
|
||||
canonical.reasoning = Some(true);
|
||||
}
|
||||
canonical.cost = if model.ends_with(":free") {
|
||||
Pricing {
|
||||
input: Some(0.0),
|
||||
output: Some(0.0),
|
||||
..Pricing::default()
|
||||
}
|
||||
} else {
|
||||
Pricing::default()
|
||||
};
|
||||
} else if should_clear_catalog_pricing(provider) {
|
||||
canonical.cost = Pricing::default();
|
||||
} else if name_builder::is_meta_provider(provider) && canonical.cost.has_no_usable_rate() {
|
||||
// A meta-provider model can infer to a first-party catalog entry that carries literal
|
||||
@@ -187,7 +220,7 @@ pub fn maybe_get_canonical_model(provider: &str, model: &str) -> Option<Canonica
|
||||
canonical.cost = host_catalog_pricing(provider, model, ®istry).unwrap_or_default();
|
||||
}
|
||||
|
||||
Some(canonical)
|
||||
Some((canonical, is_variant_fallback))
|
||||
}
|
||||
|
||||
/// Pricing from the meta-provider's own catalog rows (`azure/*`, `databricks/*`,
|
||||
@@ -214,6 +247,100 @@ fn host_catalog_pricing(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:free"; "free")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash-0731:free"; "dated free")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash-0731:nitro"; "dated nitro")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:floor"; "floor")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:online"; "online")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:batch"; "batch")]
|
||||
fn openrouter_variants_resolve_to_base_model(model: &str) {
|
||||
let canonical = maybe_get_canonical_model("openrouter", model).unwrap();
|
||||
let base = maybe_get_canonical_model("openrouter", "deepseek/deepseek-v4-flash").unwrap();
|
||||
assert_eq!(canonical.id, base.id);
|
||||
assert_eq!(canonical.limit.context, base.limit.context);
|
||||
assert_eq!(canonical.reasoning, base.reasoning);
|
||||
assert_eq!(canonical.modalities.input, base.modalities.input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openrouter_exact_free_model_keeps_its_catalog_entry() {
|
||||
let model = "google/gemma-4-31b-it:free";
|
||||
let row = CanonicalModelRegistry::bundled()
|
||||
.unwrap()
|
||||
.get("openrouter", model)
|
||||
.cloned()
|
||||
.unwrap();
|
||||
let (canonical, is_variant_fallback) =
|
||||
maybe_get_canonical_model_with_variant_fallback("openrouter", model).unwrap();
|
||||
assert!(!is_variant_fallback);
|
||||
assert_eq!(canonical.id, row.id);
|
||||
assert!(row.limit.output.is_some());
|
||||
assert_eq!(canonical.limit.output, row.limit.output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openrouter_thinking_variant_is_reasoning() {
|
||||
let base = maybe_get_canonical_model("openrouter", "qwen/qwen-plus-2025-07-28").unwrap();
|
||||
assert_eq!(base.reasoning, Some(false));
|
||||
|
||||
let (thinking, is_variant_fallback) = maybe_get_canonical_model_with_variant_fallback(
|
||||
"openrouter",
|
||||
"qwen/qwen-plus-2025-07-28:thinking",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(is_variant_fallback);
|
||||
assert_eq!(thinking.id, base.id);
|
||||
assert_eq!(thinking.reasoning, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_openrouter_colon_model_does_not_resolve_to_base_model() {
|
||||
assert!(maybe_get_canonical_model("deepseek", "deepseek-v4-flash").is_some());
|
||||
assert!(maybe_get_canonical_model("deepseek", "deepseek-v4-flash:free").is_none());
|
||||
}
|
||||
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:free"; "free")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash-0731:free"; "dated free")]
|
||||
fn openrouter_free_fallback_has_zero_cost(model: &str) {
|
||||
let paid = maybe_get_canonical_model("openrouter", "deepseek/deepseek-v4-flash").unwrap();
|
||||
assert!(paid.cost.input.is_some_and(|price| price > 0.0));
|
||||
assert!(paid.cost.output.is_some_and(|price| price > 0.0));
|
||||
|
||||
let free = maybe_get_canonical_model("openrouter", model).unwrap();
|
||||
assert_eq!(free.id, paid.id);
|
||||
assert_eq!(free.limit.context, paid.limit.context);
|
||||
assert_eq!(free.cost.input, Some(0.0));
|
||||
assert_eq!(free.cost.output, Some(0.0));
|
||||
assert_eq!(free.cost.cache_read, None);
|
||||
assert_eq!(free.cost.cache_write, None);
|
||||
assert!(free.cost.tiers.is_empty());
|
||||
let usage = crate::conversation::token_usage::Usage {
|
||||
input_tokens: Some(1_000_000),
|
||||
output_tokens: Some(1_000_000),
|
||||
total_tokens: None,
|
||||
cache_read_input_tokens: Some(100_000),
|
||||
cache_write_input_tokens: Some(100_000),
|
||||
};
|
||||
assert_eq!(free.cost.estimate_cost(&usage), Some(0.0));
|
||||
}
|
||||
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:batch"; "batch")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:nitro"; "nitro")]
|
||||
fn openrouter_variant_fallback_has_no_catalog_price(model: &str) {
|
||||
let canonical = maybe_get_canonical_model("openrouter", model).unwrap();
|
||||
assert_eq!(canonical.cost.input, None);
|
||||
assert_eq!(canonical.cost.output, None);
|
||||
assert_eq!(canonical.cost.cache_read, None);
|
||||
assert_eq!(canonical.cost.cache_write, None);
|
||||
assert!(canonical.cost.tiers.is_empty());
|
||||
assert_eq!(
|
||||
canonical
|
||||
.cost
|
||||
.estimate_cost(&crate::conversation::token_usage::Usage::default()),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_models_have_zero_cost() {
|
||||
// "mistral-nemo" resolves to mistralai/mistral-nemo which has non-zero cloud pricing.
|
||||
|
||||
@@ -64,6 +64,12 @@ pub fn map_provider_name(provider: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip a trailing OpenRouter variant tag such as `:free` or `:nitro`.
|
||||
pub fn strip_openrouter_variant(model: &str) -> Option<&str> {
|
||||
let (base, tag) = model.rsplit_once(':')?;
|
||||
(!tag.is_empty() && tag.bytes().all(|byte| byte.is_ascii_lowercase())).then_some(base)
|
||||
}
|
||||
|
||||
/// Try to map a provider/model pair to a canonical model
|
||||
pub fn map_to_canonical_model(
|
||||
provider: &str,
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::api_client::ApiClient;
|
||||
pub type OpenRouterSessionIdProvider = Box<dyn Fn() -> Option<String> + Send + Sync>;
|
||||
use crate::base::{ConfigKey, MessageStream, Provider, ProviderMetadata};
|
||||
use crate::cache_semantics::{apply_chat_payload_breakpoints, CacheSemantics};
|
||||
use crate::canonical::{maybe_get_canonical_model_with_variant_fallback, strip_openrouter_variant};
|
||||
use crate::conversation::message::Message;
|
||||
use crate::decision::{DecisionProvider, DecisionRequest, DecisionResponse};
|
||||
use crate::errors::ProviderError;
|
||||
@@ -565,19 +566,22 @@ impl Provider for OpenRouterProvider {
|
||||
async fn get_context_limit(&self, model: &str, override_limit: Option<usize>) -> usize {
|
||||
crate::context_limit::ContextLimitResolver::new(&self.name)
|
||||
.resolve(model, override_limit, || async {
|
||||
// The catalog outranks the reported length, so a model it knows
|
||||
// never needs the model list.
|
||||
if let Some(canonical) =
|
||||
crate::canonical::maybe_get_canonical_model(&self.name, model)
|
||||
{
|
||||
let canonical = maybe_get_canonical_model_with_variant_fallback(&self.name, model);
|
||||
let base = strip_openrouter_variant(model);
|
||||
// Exact catalog rows outrank live exact IDs; base fallbacks come after both.
|
||||
if let Some((canonical, false)) = &canonical {
|
||||
return Ok(Some(canonical.limit.context));
|
||||
}
|
||||
Ok(self
|
||||
.get_or_fetch_models()
|
||||
.await?
|
||||
let models = self.get_or_fetch_models().await?;
|
||||
Ok(models
|
||||
.iter()
|
||||
.find(|info| info.id == model)
|
||||
.and_then(|info| info.context_length))
|
||||
.and_then(|info| info.context_length)
|
||||
.or_else(|| canonical.map(|(canonical, _)| canonical.limit.context))
|
||||
.or_else(|| {
|
||||
base.and_then(|base| models.iter().find(|info| info.id == base))
|
||||
.and_then(|info| info.context_length)
|
||||
}))
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -919,6 +923,68 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn context_limit_uses_base_model_for_variant_not_in_catalog() {
|
||||
let server = models_server(models_response(), 1).await;
|
||||
let provider = provider_for(&server);
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.get_context_limit(&format!("{MODEL_NOT_IN_CATALOG}:nitro"), None)
|
||||
.await,
|
||||
1_048_576
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn context_limit_keeps_exact_variant_precedence() {
|
||||
let variant = format!("{MODEL_NOT_IN_CATALOG}:nitro");
|
||||
let response = wiremock::ResponseTemplate::new(200).set_body_json(json!({
|
||||
"data": [
|
||||
{ "id": MODEL_NOT_IN_CATALOG, "context_length": 1_048_576 },
|
||||
{ "id": variant, "context_length": 64_000 }
|
||||
]
|
||||
}));
|
||||
let server = models_server(response, 1).await;
|
||||
let provider = provider_for(&server);
|
||||
|
||||
assert_eq!(provider.get_context_limit(&variant, None).await, 64_000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn context_limit_prefers_live_exact_variant_over_catalog_base() {
|
||||
let variant = "deepseek/deepseek-v4-flash:nitro";
|
||||
let response = wiremock::ResponseTemplate::new(200).set_body_json(json!({
|
||||
"data": [{ "id": variant, "context_length": 64_000 }]
|
||||
}));
|
||||
let server = models_server(response, 1).await;
|
||||
let provider = provider_for(&server);
|
||||
|
||||
assert_eq!(provider.get_context_limit(variant, None).await, 64_000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn context_limit_prefers_catalog_base_when_live_variant_is_missing() {
|
||||
let model = "deepseek/deepseek-v4-flash";
|
||||
let catalog_limit =
|
||||
crate::canonical::maybe_get_canonical_model(OPENROUTER_PROVIDER_NAME, model)
|
||||
.unwrap()
|
||||
.limit
|
||||
.context;
|
||||
let response = wiremock::ResponseTemplate::new(200).set_body_json(json!({
|
||||
"data": [{ "id": model, "context_length": 64_000 }]
|
||||
}));
|
||||
let server = models_server(response, 1).await;
|
||||
let provider = provider_for(&server);
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.get_context_limit(&format!("{model}:nitro"), None)
|
||||
.await,
|
||||
catalog_limit
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn context_limit_keeps_override_and_catalog_precedence_without_fetching() {
|
||||
let server = models_server(models_response(), 0).await;
|
||||
|
||||
@@ -383,6 +383,25 @@ mod azure_foundry_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod openrouter_tests {
|
||||
use super::*;
|
||||
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:free"; "free")]
|
||||
#[test_case::test_case("deepseek/deepseek-v4-flash:batch"; "batch")]
|
||||
fn openrouter_variant_does_not_inherit_base_output_limit(model: &str) {
|
||||
let config = apply_canonical_limits("openrouter", ModelConfig::new(model));
|
||||
assert_eq!(config.max_tokens, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openrouter_base_keeps_catalog_output_limit() {
|
||||
let config =
|
||||
apply_canonical_limits("openrouter", ModelConfig::new("deepseek/deepseek-v4-flash"));
|
||||
assert!(config.max_tokens.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod canonical_vision_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -7,7 +7,10 @@ pub use resolver::{
|
||||
};
|
||||
|
||||
use super::base::{ConfigKey, ModelInfo, Provider, ProviderType};
|
||||
use super::canonical::{map_provider_name, map_to_canonical_model, CanonicalModelRegistry};
|
||||
use super::canonical::{
|
||||
map_provider_name, map_to_canonical_model, maybe_get_canonical_model_with_variant_fallback,
|
||||
CanonicalModelRegistry,
|
||||
};
|
||||
use crate::config::declarative_providers::{DeclarativeProviderConfig, ProviderEngine};
|
||||
use crate::config::Config;
|
||||
use crate::session::session_manager::SessionStorage;
|
||||
@@ -1180,12 +1183,20 @@ fn enriched_model(
|
||||
model_id: &str,
|
||||
fallback_context_limit: Option<usize>,
|
||||
) -> InventoryModel {
|
||||
let registry = CanonicalModelRegistry::bundled().ok();
|
||||
let canonical = registry.as_ref().and_then(|registry| {
|
||||
let canonical_id = map_to_canonical_model(provider_family, model_id, registry)?;
|
||||
// The registry guard is dropped inside the closure: the fallback below takes its own
|
||||
// read lock, and a nested read can block behind a queued catalog refresh.
|
||||
let canonical = CanonicalModelRegistry::bundled().ok().and_then(|registry| {
|
||||
let canonical_id = map_to_canonical_model(provider_family, model_id, ®istry)?;
|
||||
let (provider, model) = canonical_id.split_once('/')?;
|
||||
registry.get(provider, model).cloned()
|
||||
});
|
||||
// A variant borrows its base row's metadata but keeps its own id as the name,
|
||||
// so the picker still lists it next to the base model.
|
||||
let metadata = canonical.clone().or_else(|| {
|
||||
maybe_get_canonical_model_with_variant_fallback(provider_family, model_id)
|
||||
.filter(|(_, is_variant_fallback)| *is_variant_fallback)
|
||||
.map(|(model, _)| model)
|
||||
});
|
||||
|
||||
InventoryModel {
|
||||
id: model_id.to_string(),
|
||||
@@ -1193,12 +1204,12 @@ fn enriched_model(
|
||||
.as_ref()
|
||||
.map(|model| model.name.clone())
|
||||
.unwrap_or_else(|| model_id.to_string()),
|
||||
family: canonical.as_ref().and_then(|model| model.family.clone()),
|
||||
context_limit: canonical
|
||||
family: metadata.as_ref().and_then(|model| model.family.clone()),
|
||||
context_limit: metadata
|
||||
.as_ref()
|
||||
.map(|model| model.limit.context)
|
||||
.or(fallback_context_limit),
|
||||
reasoning: canonical.as_ref().and_then(|model| model.reasoning),
|
||||
reasoning: metadata.as_ref().and_then(|model| model.reasoning),
|
||||
recommended: false,
|
||||
}
|
||||
}
|
||||
@@ -1260,6 +1271,26 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openrouter_inventory_keeps_base_and_unlisted_variants() {
|
||||
let ids = vec![
|
||||
"deepseek/deepseek-v4-flash".to_string(),
|
||||
"deepseek/deepseek-v4-flash:batch".to_string(),
|
||||
"deepseek/deepseek-v4-flash:free".to_string(),
|
||||
];
|
||||
let models = enrich_model_ids_with_canonical("openrouter", &ids);
|
||||
assert_eq!(
|
||||
models.iter().map(|model| &model.id).collect::<Vec<_>>(),
|
||||
ids.iter().collect::<Vec<_>>()
|
||||
);
|
||||
for variant in &models[1..] {
|
||||
assert_eq!(variant.name, variant.id);
|
||||
assert_eq!(variant.family, models[0].family);
|
||||
assert_eq!(variant.context_limit, models[0].context_limit);
|
||||
assert_eq!(variant.reasoning, models[0].reasoning);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_guard_complete_clears_refreshing_key() {
|
||||
let refreshing_keys = Arc::new(RwLock::new(HashSet::from(["key-a".to_string()])));
|
||||
|
||||
Reference in New Issue
Block a user