|
| 1 | +use duct::cmd; |
| 2 | +use rayon::prelude::*; |
| 3 | +use yaml_rust2::yaml::LoadError; |
| 4 | +use yaml_rust2::{ScanError, Yaml, YamlLoader}; |
| 5 | + |
| 6 | +/// Read the given filesystem path and produce a potentially multi-document Yaml |
| 7 | +fn from_path(path: &String) -> Result<Vec<Yaml>, ScanError> { |
| 8 | + let content = std::fs::read_to_string(path).unwrap(); |
| 9 | + YamlLoader::load_from_str(&content) |
| 10 | +} |
| 11 | + |
| 12 | +/// Take one Yaml fragment and produce the a vector of the models that are used |
| 13 | +fn extract_models(program: Yaml) -> Vec<String> { |
| 14 | + let mut models: Vec<String> = Vec::new(); |
| 15 | + |
| 16 | + match program { |
| 17 | + Yaml::Hash(h) => { |
| 18 | + for (key, val) in h { |
| 19 | + match key.as_str() { |
| 20 | + Some("model") => match &val { |
| 21 | + Yaml::String(m) => { |
| 22 | + models.push(m.to_string()); |
| 23 | + } |
| 24 | + _ => {} |
| 25 | + }, |
| 26 | + _ => {} |
| 27 | + } |
| 28 | + |
| 29 | + for m in extract_models(val) { |
| 30 | + models.push(m) |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + Yaml::Array(a) => { |
| 36 | + for val in a { |
| 37 | + for m in extract_models(val) { |
| 38 | + models.push(m) |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + _ => {} |
| 44 | + } |
| 45 | + |
| 46 | + models |
| 47 | +} |
| 48 | + |
| 49 | +/// Pull models (in parallel) from the PDL program in the given filepath. |
| 50 | +pub fn pull_if_needed(path: &String) -> Result<(), LoadError> { |
| 51 | + from_path(path) |
| 52 | + .unwrap() |
| 53 | + .into_iter() |
| 54 | + .flat_map(extract_models) |
| 55 | + .collect::<Vec<String>>() |
| 56 | + .into_par_iter() |
| 57 | + .try_for_each(|model| match model { |
| 58 | + m if model.starts_with("ollama/") => ollama_pull(&m[7..]), |
| 59 | + m if model.starts_with("ollama_chat/") => ollama_pull(&m[12..]), |
| 60 | + _ => { |
| 61 | + eprintln!("Skipping model pull for {}", model); |
| 62 | + Ok(()) |
| 63 | + } |
| 64 | + }) |
| 65 | + .expect("successfully pulled models"); |
| 66 | + |
| 67 | + Ok(()) |
| 68 | +} |
| 69 | + |
| 70 | +/// The Ollama implementation of a single model pull |
| 71 | +fn ollama_pull(model: &str) -> Result<(), LoadError> { |
| 72 | + cmd!("ollama", "pull", model).run().map_err(LoadError::IO)?; |
| 73 | + Ok(()) |
| 74 | +} |
0 commit comments