Skip to content
Merged
41 changes: 41 additions & 0 deletions crates/dim-agent-types/src/model.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::*;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::sync::Arc;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -248,6 +249,46 @@ pub struct ModelServiceTier {
pub options: Vec<String>,
}

impl ModelServiceTier {
/// A declaration that offers nothing: no tiers, and no default.
pub fn unavailable() -> Self {
Self {
supported: false,
default: None,
options: Vec::new(),
}
}

/// The capability this declaration states: `supported` means a usable set.
/// An option is a tier name, so surrounding space is dropped and an empty
/// one is no tier; a declaration left with none is unavailable. A default
/// the options do not offer is dropped, because it names no tier the model
/// offers and another value would be a choice nobody declared, and a
/// declaration that names no default keeps none.
pub fn usable(self) -> Self {
let Self {
supported,
default,
options,
} = self;
let mut seen = HashSet::new();
let options: Vec<String> = options
.into_iter()
.map(|option| option.trim().to_owned())
.filter(|option| !option.is_empty() && seen.insert(option.clone()))
.collect();
if !supported || options.is_empty() {
return Self::unavailable();
}
let default = default.map(|default| default.trim().to_owned());
Self {
supported: true,
default: default.filter(|default| options.contains(default)),
options,
}
}
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ModelCapabilitySnapshot {
Expand Down
81 changes: 63 additions & 18 deletions crates/dim-app-server/src/model_catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,44 @@ impl ModelEntry {
.get("max_context_window")?
.as_u64()
}

/// The entry as a catalog read serves it on `protocol`: its service-tier
/// declaration states a usable set, or no capability at all when the route
/// cannot send a tier or the model declares no limits and so has no
/// capability to adopt. Identification fills a declaration that lists no
/// options first, so this runs after a merge.
pub(crate) fn resolve_service_tier(
&mut self,
protocol: Option<dim_agent_types::ModelProtocol>,
) {
let adoptable = protocol.is_some_and(crate::provider::expresses_service_tier)
&& self.capabilities.missing_limits().is_empty();
let Some(metadata) = self.metadata.as_mut() else {
return;
};
let Some(tier) = metadata.service_tier.take() else {
return;
};
metadata.service_tier = Some(if adoptable {
tier.usable()
} else {
ModelServiceTier::unavailable()
});
}

/// A model a client creates out of a served entry arrives as the read
/// stated it, which is the capability its route offered, not the
/// declaration the source made. The listing's own item is still in `raw`,
/// so the entry a record stores keeps what the source stated and a later
/// route can serve it.
pub(crate) fn restore_service_tier(&mut self) {
let Some(metadata) = self.metadata.as_mut() else {
return;
};
if let Some(declared) = service_tier(None, &metadata.raw) {
metadata.service_tier = Some(declared);
}
}
}

/// The editable surface excludes model identity, lookup diagnostics and raw
Expand Down Expand Up @@ -1202,13 +1240,15 @@ fn merge_entry(mut current: ModelEntry, fallback: &ModelEntry, explicit: &[Strin
(r, _) => r.clone(),
};
match (&mut cm.service_tier, &fm.service_tier) {
(Some(tier), Some(fallback)) if tier.supported => {
(Some(tier), Some(fallback)) if tier.supported && tier.options.is_empty() => {
// A declaration that states no set of its own is unresolved, so
// the row fills both what it offers and its default. One that
// states its own set keeps that set, and names a default only
// when it named one itself.
tier.options = fallback.options.clone();
if tier.default.is_none() {
tier.default = fallback.default.clone();
}
if tier.options.is_empty() {
tier.options = fallback.options.clone();
}
}
(None, fallback) => cm.service_tier = fallback.clone(),
_ => {}
Expand Down Expand Up @@ -1715,28 +1755,29 @@ fn project_reasoning(
}
fn service_tier(value: Option<&Value>, raw: &Map<String, Value>) -> Option<ModelServiceTier> {
if value == Some(&Value::Bool(false)) {
return Some(ModelServiceTier {
supported: false,
default: None,
options: vec![],
});
return Some(ModelServiceTier::unavailable());
}
let extra = raw.get("extra_capabilities");
let direct = raw.get("serviceTier").or_else(|| raw.get("service_tier"));
let extra = extra.and_then(|v| v.get("serviceTier").or_else(|| v.get("service_tier")));
let fast = raw
.get("experimental")
.and_then(|v| v.pointer("/modes/fast/provider/body"))
.and_then(|v| string(v.get("service_tier").or_else(|| v.get("serviceTier"))));
.and_then(|v| string(v.get("service_tier").or_else(|| v.get("serviceTier"))))
.map(str::trim)
.filter(|tier| !tier.is_empty());
let mut supported = None;
let mut default = None;
let mut options = vec![];
for v in [direct, extra, value].into_iter().flatten() {
let text = v.as_str().map(str::trim).filter(|text| !text.is_empty());
let preference = v
.is_object()
.then(|| string(v.get("default").or_else(|| v.get("default_tier"))))
.flatten()
.or_else(|| v.as_str());
.map(str::trim)
.filter(|tier| !tier.is_empty())
.or(text);
let support = v
.as_bool()
.or_else(|| v.get("supported").and_then(Value::as_bool));
Expand All @@ -1747,19 +1788,23 @@ fn service_tier(value: Option<&Value>, raw: &Map<String, Value>) -> Option<Model
default = preference.map(str::to_owned);
}
if let Some(values) = v.get("options").and_then(Value::as_array) {
options.extend(strings(values));
} else if let Some(v) = v.as_str() {
options.push(v.to_owned());
options.extend(
values
.iter()
.filter_map(Value::as_str)
.map(str::trim)
.filter(|option| !option.is_empty())
.map(str::to_owned),
);
} else if let Some(text) = text {
options.push(text.to_owned());
}
}
if let Some(fast) = fast {
options.extend(["default".into(), fast.into()]);
options.extend(["default".to_owned(), fast.to_owned()]);
}
let mut seen = HashSet::new();
options.retain(|option| seen.insert(option.clone()));
let default = default
.or_else(|| options.iter().find(|v| *v == "default").cloned())
.or_else(|| options.first().cloned());
let supported =
supported.or_else(|| (default.is_some() || !options.is_empty()).then_some(true))?;
Some(ModelServiceTier {
Expand Down
5 changes: 4 additions & 1 deletion crates/dim-app-server/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub(crate) mod naming;
mod new_api;
pub(crate) mod persistence;
mod preferences;
pub(crate) use preferences::expresses_service_tier;
mod query;
#[cfg(feature = "testing")]
pub mod read_work;
Expand Down Expand Up @@ -578,6 +579,7 @@ impl ProviderRecord {
None => source.entry.clone(),
};
bundled.identify_entry(&projection, &mut entry);
entry.resolve_service_tier(Some(source.protocol));
let missing_limits = entry.capabilities.missing_limits();
let unavailable = if source.excluded_from_every_use() {
// A stored limits reason is the weaker derived fact and
Expand Down Expand Up @@ -1270,7 +1272,8 @@ fn static_models_from_entries(
entries
.into_iter()
.zip(names)
.map(|(entry, name)| {
.map(|(mut entry, name)| {
entry.resolve_service_tier(record.routes.get(&entry.model_id).copied());
let missing_limits = entry.capabilities.missing_limits();
let status_unavailable =
matches!(entry.status, crate::model_catalog::ModelStatus::Unavailable);
Expand Down
15 changes: 12 additions & 3 deletions crates/dim-app-server/src/provider/editing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,9 +364,17 @@ impl ProviderService {
};
validate_static_record(&id, &mut record)
.map_err(|error| ProviderError::InvalidConfig(error.to_string()))?;
Ok(ProbeResult {
models: owner.discover(&id, &record, &cancel).await?,
})
let mut models = owner.discover(&id, &record, &cancel).await?;
let routes = drivers::routes(
&record.driver_kind,
&models,
&record.endpoint_types,
&record.endpoint_overrides,
)?;
for model in &mut models {
model.resolve_service_tier(routes.get(&model.model_id).copied());
}
Ok(ProbeResult { models })
})
})
.await
Expand Down Expand Up @@ -395,6 +403,7 @@ impl ProviderService {
// carry it into the record.
for model in &mut models {
model.normalized_override = false;
model.restore_service_tier();
if model.capabilities.context_window.is_some() {
declare(model, "contextWindow");
}
Expand Down
1 change: 1 addition & 0 deletions crates/dim-app-server/src/provider/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ impl ProviderService {
// override writes carry (#2189) is not the client's to
// state.
model.normalized_override = false;
model.restore_service_tier();
if model.capabilities.context_window.is_some() {
declare(&mut model, "contextWindow");
}
Expand Down
11 changes: 11 additions & 0 deletions crates/dim-app-server/src/provider/preferences.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
use dim_agent_capabilities::host::{ModelProtocol, adopted_preferences, reasoning_config};
use dim_agent_types::*;

/// Whether `protocol` can send a service-tier preference at all. A declaration
/// the protocol cannot express is not a capability a client may offer.
pub(crate) fn expresses_service_tier(protocol: ModelProtocol) -> bool {
matches!(
protocol,
ModelProtocol::OpenaiChat
| ModelProtocol::OpenaiResponses
| ModelProtocol::OpenaiCompatible
)
}

/// The base configuration an adoption starts from: `base` with the model's
/// declared default reasoning effort and service tier applied.
///
Expand Down
3 changes: 2 additions & 1 deletion crates/dim-app-server/src/provider/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,10 +341,11 @@ impl ProviderService {
.collect(),
..Default::default()
};
let entry = self
let mut entry = self
.bundled
.project(&projection, &descriptor)
.map_err(failure)?;
entry.resolve_service_tier(Some(source.api_format));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This resolves the startup path, but provider.probe serves discover output without the same call (crates/dim-app-server/src/provider/editing.rs:368), so its reply can still carry serviceTier: {supported: true} with no options (crates/dim-app-server/src/provider/remote.rs:121, :344-346). Resolve the probe reply's entries with the connection protocol, and leave discover's stored path unresolved so a later row can enumerate the declaration.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fe0c789.

let mut snapshot = match previous {
Some(model) => model.capability_snapshot.clone().ok_or_else(|| failure("Model capabilities are not adopted"))?,
None => ModelCapabilitySnapshot {
Expand Down
3 changes: 2 additions & 1 deletion crates/dim-app-server/src/provider/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,8 @@ impl ProviderService {
let models = entries
.into_iter()
.zip(catalog)
.map(|(model, effective)| {
.map(|(mut model, effective)| {
model.resolve_service_tier(effective.endpoint);
let user = record
.user_models
.iter()
Expand Down
Loading
Loading