use std::time::Duration;
use serde::Deserialize;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Server {
pub provider: &'static str,
pub label: &'static str,
pub base_url: &'static str,
pub models: Vec<String>,
}
pub const KNOWN: [(&str, &str, &str); 2] =
[("ollama", "Ollama", "http://localhost:11434/v1"), ("lmstudio", "LM Studio", "http://localhost:1234/v1")];
#[derive(Deserialize)]
struct ModelList {
data: Vec<ModelEntry>,
}
#[derive(Deserialize)]
struct ModelEntry {
id: String,
}
pub async fn list_models(base_url: &str) -> Option<Vec<String>> {
let client = reqwest::Client::builder().timeout(Duration::from_millis(1500)).build().ok()?;
let response = client.get(format!("{}/models", base_url.trim_end_matches('/'))).send().await.ok()?;
let list: ModelList = response.error_for_status().ok()?.json().await.ok()?;
let mut models: Vec<String> = list.data.into_iter().map(|m| m.id).collect();
models.sort();
Some(models)
}
pub async fn probe() -> Vec<Server> {
let probes = KNOWN.map(|(provider, label, base_url)| async move {
list_models(base_url).await.map(|models| Server { provider, label, base_url, models })
});
futures_join(probes).await.into_iter().flatten().collect()
}
async fn futures_join<F: std::future::Future>(futures: [F; 2]) -> [F::Output; 2] {
let [a, b] = futures;
let (a, b) = tokio::join!(a, b);
[a, b]
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Hardware {
pub ram_gb: u64,
pub vram_gb: Option<u64>,
pub apple_silicon: bool,
}
pub fn detect_hardware() -> Hardware {
let mut system = sysinfo::System::new();
system.refresh_memory();
let ram_gb = system.total_memory() / (1024 * 1024 * 1024);
let vram_gb = std::process::Command::new("nvidia-smi")
.args(["--query-gpu=memory.total", "--format=csv,noheader,nounits"])
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8_lossy(&o.stdout).lines().filter_map(|l| l.trim().parse::<u64>().ok()).max())
.map(|mib| mib / 1024);
let apple_silicon = cfg!(all(target_os = "macos", target_arch = "aarch64"));
Hardware { ram_gb, vram_gb, apple_silicon }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tier {
pub size: &'static str,
pub ollama_model: &'static str,
pub lmstudio_hint: &'static str,
pub alternatives: &'static [&'static str],
pub reason: String,
}
pub fn recommend(hardware: Hardware) -> Tier {
let vram = hardware.vram_gb.unwrap_or(0);
let (ram_mid, ram_high) = (15, 30);
let memory = if hardware.apple_silicon { "unified memory" } else { "RAM" };
if vram >= 12 || hardware.ram_gb >= ram_high {
Tier {
size: "14B to 32B",
ollama_model: "qwen2.5-coder:14b",
lmstudio_hint: "Qwen2.5-Coder-14B-Instruct (Q4_K_M)",
alternatives: &["deepseek-r1:32b", "qwen2.5-coder:7b"],
reason: format!("{} GB {memory}{}", hardware.ram_gb, vram_note(vram)),
}
} else if vram >= 6 || hardware.ram_gb >= ram_mid {
Tier {
size: "7B to 9B",
ollama_model: "qwen2.5-coder:7b",
lmstudio_hint: "Qwen2.5-Coder-7B-Instruct (Q4_K_M)",
alternatives: &["llama3:8b", "deepseek-r1:8b"],
reason: format!("{} GB {memory}{}", hardware.ram_gb, vram_note(vram)),
}
} else {
Tier {
size: "1B to 3B",
ollama_model: "qwen2.5-coder:1.5b",
lmstudio_hint: "Qwen2.5-Coder-1.5B-Instruct (Q4_K_M)",
alternatives: &["llama3.2:3b"],
reason: format!("{} GB {memory}{}", hardware.ram_gb, vram_note(vram)),
}
}
}
fn vram_note(vram: u64) -> String {
if vram > 0 { format!(", {vram} GB GPU memory") } else { String::new() }
}
pub fn has_model(models: &[String], wanted: &str) -> bool {
models.iter().any(|m| m == wanted || m.strip_suffix(":latest") == Some(wanted))
}
pub fn pick_installed(models: &[String], recommended: &str) -> Option<String> {
if has_model(models, recommended) {
return Some(recommended.to_owned());
}
models.iter().find(|m| m.contains("coder")).or_else(|| models.first()).cloned()
}
pub fn install_instructions() -> Vec<String> {
let ollama = if cfg!(windows) {
"winget install Ollama.Ollama (or download from https://ollama.com)"
} else if cfg!(target_os = "macos") {
"brew install ollama (or download from https://ollama.com)"
} else {
"curl -fsSL https://ollama.com/install.sh | sh"
};
vec![
format!("Ollama (recommended): {ollama}"),
"LM Studio (graphical): https://lmstudio.ai, then Developer > Start Server".to_owned(),
]
}
#[cfg(test)]
mod tests {
use super::*;
fn hw(ram_gb: u64, vram_gb: Option<u64>) -> Hardware {
Hardware { ram_gb, vram_gb, apple_silicon: false }
}
#[test]
fn tiers_follow_the_local_llm_guide() {
assert_eq!(recommend(hw(7, None)).ollama_model, "qwen2.5-coder:1.5b");
assert_eq!(recommend(hw(15, None)).ollama_model, "qwen2.5-coder:7b");
assert_eq!(recommend(hw(8, Some(8))).ollama_model, "qwen2.5-coder:7b");
assert_eq!(recommend(hw(31, None)).ollama_model, "qwen2.5-coder:14b");
assert_eq!(recommend(hw(16, Some(12))).ollama_model, "qwen2.5-coder:14b");
}
#[test]
fn model_matching() {
let models = vec!["llama3:8b".to_owned(), "qwen2.5-coder:7b".to_owned()];
assert!(has_model(&models, "qwen2.5-coder:7b"));
assert!(has_model(&["qwen2.5-coder:7b:latest".to_owned()], "qwen2.5-coder:7b"));
assert_eq!(pick_installed(&models, "qwen2.5-coder:14b").unwrap(), "qwen2.5-coder:7b");
assert_eq!(pick_installed(&["llama3:8b".to_owned()], "x").unwrap(), "llama3:8b");
assert!(pick_installed(&[], "x").is_none());
}
}