use std::path::PathBuf;
use anyhow::Context;
use clap::Args;
use serde::Serialize;
use crate::modelpack::{resolve_model, ModelFormat};
use crate::storage::OciStore;
#[derive(Args, Debug)]
pub struct ResolveArgs {
#[arg(value_name = "REFERENCE")]
pub reference: String,
#[arg(long)]
pub cache: Option<PathBuf>,
#[arg(long)]
pub no_pull: bool,
#[arg(long)]
pub dir: bool,
}
#[derive(Serialize)]
struct ResolveOutput<'a> {
reference: &'a str,
path: String,
format: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
mmproj: Option<String>,
}
#[derive(Serialize)]
struct TreeOutput<'a> {
reference: &'a str,
dir: String,
digest: String,
format: &'static str,
}
pub fn run(args: &ResolveArgs) -> anyhow::Result<()> {
let reference = crate::shortnames::resolve_ollama_api(&args.reference)?;
let store_path = crate::default_store()?;
let cache_path = args
.cache
.clone()
.map(Ok)
.unwrap_or_else(crate::default_cache)?;
std::fs::create_dir_all(&store_path)
.with_context(|| format!("creating store dir {}", store_path.display()))?;
std::fs::create_dir_all(&cache_path)
.with_context(|| format!("creating cache dir {}", cache_path.display()))?;
let pull_lock = if OciStore::open(&store_path)
.and_then(|s| s.find(&reference))
.is_ok()
{
None
} else {
if args.no_pull {
anyhow::bail!(
"{reference} not found in local store ({}) and --no-pull was set",
store_path.display()
);
}
Some(crate::managed::InstallLock::acquire_noting(
&store_path,
"another llmman process is pulling into this store; waiting for it to finish",
)?)
};
let mut notices = tokio::runtime::Runtime::new()
.context("start tokio runtime")?
.block_on(crate::cmd::serve::pull_checked(&store_path, &reference))
.with_context(|| format!("pulling {reference}"))?;
drop(pull_lock);
let desc = OciStore::open(&store_path)?
.find(&reference)
.with_context(|| format!("model not found in store: {reference}"))?;
let (load_ref, layer_notices) =
crate::cmd::serve::verify_layers_found(&store_path, &reference, &desc)
.with_context(|| format!("verify layers of {reference}"))?;
notices.extend(layer_notices);
for notice in notices {
eprintln!("[llmman] {notice}");
}
if args.dir {
let tree = crate::modelpack::resolve_model_tree(&store_path, &cache_path, &load_ref)
.with_context(|| format!("resolving {reference}"))?;
let out = TreeOutput {
reference: &reference,
dir: tree.root.to_string_lossy().into_owned(),
digest: tree.digest,
format: tree.format.map_or("unknown", ModelFormat::as_str),
};
println!("{}", serde_json::to_string(&out)?);
return Ok(());
}
let resolved = resolve_model(&store_path, &cache_path, &load_ref)
.with_context(|| format!("resolving {reference}"))?;
let out = ResolveOutput {
reference: &reference,
path: resolved.path().to_string_lossy().into_owned(),
format: resolved.format(),
mmproj: resolved.mmproj().map(|p| p.to_string_lossy().into_owned()),
};
println!("{}", serde_json::to_string(&out)?);
Ok(())
}