use std::collections::HashMap;
use rho_protocol as wire;
use rho_providers::{
model::{
catalog::{
self, ModelCatalogEntry, ModelSelection, ModelSelectionError, SelectionAuthContext,
},
display_name::model_display_name,
favorites,
provider_models::listed_model_id,
},
provider::{model_reference, provider_descriptor},
};
use crate::app::session_runtime::CurrentModel;
pub(super) fn model_options(
current: Option<&CurrentModel>,
favorite_models: &[String],
mut available: Vec<ModelCatalogEntry>,
) -> wire::ModelOptions {
let Some(current) = current else {
return wire::ModelOptions {
current: wire::ModelRef {
provider: String::new(),
model: String::new(),
},
auth: String::new(),
available: model_choices(favorite_models, available),
};
};
let identity = ModelIds::new(¤t.provider, ¤t.model);
if !available
.iter()
.any(|entry| identity.is(&entry.provider, &entry.model))
{
available.push(ModelCatalogEntry {
provider: current.provider.clone(),
model: current.model.clone(),
display_name: current.model.clone(),
auth_modes: vec![current.auth.clone()],
});
}
let mut choices = model_choices(favorite_models, available);
for choice in choices
.iter_mut()
.filter(|choice| identity.is(&choice.model.provider, &choice.model.model))
{
choice.model.model.clone_from(¤t.model);
}
wire::ModelOptions {
current: wire::ModelRef {
provider: current.provider.clone(),
model: current.model.clone(),
},
auth: current.auth.clone(),
available: choices,
}
}
pub(crate) fn model_choices(
favorite_models: &[String],
available: Vec<ModelCatalogEntry>,
) -> Vec<wire::ModelChoice> {
let favorites = favorites::normalized_favorite_models(favorite_models);
let ordered = favorites::reorder_models_by_favorites(available, &favorites);
model_labels(&ordered)
.into_iter()
.zip(ordered)
.map(|(label, entry)| wire::ModelChoice {
model: wire::ModelRef {
provider: entry.provider,
model: entry.model,
},
label,
})
.collect()
}
pub(crate) struct ModelIds<'a> {
provider: &'a str,
model: &'a str,
listed: String,
}
impl<'a> ModelIds<'a> {
pub(crate) fn new(provider: &'a str, model: &'a str) -> Self {
Self {
provider,
model,
listed: listed_model_id(provider, model),
}
}
pub(crate) fn is(&self, provider: &str, model: &str) -> bool {
provider == self.provider && (model == self.model || model == self.listed)
}
}
pub(crate) struct OfferedModels<'a> {
available: &'a [wire::ModelChoice],
current: Option<(&'a wire::ModelRef, ModelIds<'a>)>,
}
impl<'a> OfferedModels<'a> {
pub(crate) fn new(options: &'a wire::ModelOptions) -> Self {
Self {
available: &options.available,
current: Some((
&options.current,
ModelIds::new(&options.current.provider, &options.current.model),
)),
}
}
pub(crate) fn listed(available: &'a [wire::ModelChoice]) -> Self {
Self {
available,
current: None,
}
}
pub(crate) fn available(&self) -> &'a [wire::ModelChoice] {
self.available
}
pub(crate) fn by_reference(&self, reference: &str) -> Option<&'a wire::ModelChoice> {
let (provider, model) = reference.split_once('/')?;
self.available
.iter()
.find(|choice| choice.model.provider == provider && self.answers(choice, model))
}
pub(crate) fn answers(&self, choice: &wire::ModelChoice, model: &str) -> bool {
choice.model.model == model
|| self.current.as_ref().is_some_and(|(current, ids)| {
choice.model == **current && ids.is(&choice.model.provider, model)
})
}
}
fn model_labels(entries: &[ModelCatalogEntry]) -> Vec<String> {
let names = entries
.iter()
.map(|entry| {
model_display_name(&entry.provider, &entry.model).unwrap_or_else(|| entry.model.clone())
})
.collect::<Vec<_>>();
let mut name_counts = HashMap::<&str, usize>::new();
let mut provider_counts = HashMap::<(&str, &str), usize>::new();
for (name, entry) in names.iter().zip(entries) {
*name_counts.entry(name).or_default() += 1;
*provider_counts.entry((name, &entry.provider)).or_default() += 1;
}
names
.iter()
.zip(entries)
.map(|(name, entry)| {
let shared = name_counts[name.as_str()];
let within_provider = provider_counts[&(name.as_str(), entry.provider.as_str())];
match (shared, within_provider) {
(1, _) => name.clone(),
(_, 1) => format!("{name} ({})", entry.provider),
_ if shared == within_provider => entry.model.clone(),
_ => format!("{} ({})", entry.model, entry.provider),
}
})
.collect()
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub(crate) struct ModelRefused(String);
#[derive(Clone, Copy, Debug)]
pub(crate) enum AuthPick<'a> {
Named(&'a str),
AnyOf(&'a [String]),
}
pub(crate) fn resolve_model(
provider: &str,
model: &str,
current: Option<&CurrentModel>,
auth: AuthPick<'_>,
) -> Result<ModelSelection, ModelRefused> {
let asked = model_reference(provider, model);
let kept_current =
current.filter(|current| asked == model_reference(¤t.provider, ¤t.model));
let kept = |current: &CurrentModel, auth: &str| ModelSelection {
provider: current.provider.clone(),
model: current.model.clone(),
auth: auth.to_owned(),
from_catalog: false,
};
let listed = |context| {
catalog::resolve_model_selection_for_provider(provider, model, context)
.map_err(|error| ModelRefused(refusal(error, &asked)))
};
let selection = match (auth, kept_current) {
(AuthPick::AnyOf(_), Some(current)) => kept(current, ¤t.auth),
(AuthPick::AnyOf(available), None) => listed(SelectionAuthContext {
current: current.map(|current| current.auth.as_str()),
available,
})?,
(AuthPick::Named(named), Some(current)) => {
let takes = provider_descriptor(¤t.provider)
.is_some_and(|descriptor| descriptor.auth_mode(named).is_some());
if takes {
kept(current, named)
} else {
return Err(not_on_auth(&asked, named));
}
}
(AuthPick::Named(named), None) => {
let available = [named.to_owned()];
let selection = listed(SelectionAuthContext {
current: Some(named),
available: &available,
})?;
if selection.auth != named {
return Err(not_on_auth(&asked, named));
}
selection
}
};
Ok(selection)
}
fn not_on_auth(asked: &str, auth: &str) -> ModelRefused {
ModelRefused(format!("model '{asked}' does not run on auth '{auth}'"))
}
fn refusal(error: ModelSelectionError, asked: &str) -> String {
match error {
ModelSelectionError::UnknownProvider { provider } => {
format!("unknown provider '{provider}' for model value '{asked}'")
}
ModelSelectionError::AmbiguousModel { model } => {
format!("model '{model}' is ambiguous for value '{asked}'")
}
ModelSelectionError::Empty => format!("model value '{asked}' is empty"),
ModelSelectionError::DecisionOnly { provider } => {
format!("provider '{provider}' serves decision models, not chat (value '{asked}')")
}
ModelSelectionError::UnavailableModel {
provider,
model,
hint,
} => format!(
"model '{model}' is not available for provider '{provider}' (value '{asked}'). {hint}"
),
other => format!("{other} (value '{asked}')"),
}
}
#[cfg(test)]
#[path = "models_tests.rs"]
mod tests;