Skip to main content

aither_llama/
provider.rs

1use crate::{Llama, LlamaError};
2use aither_core::llm::{
3    LanguageModelProvider, model::Profile as ModelProfile, provider::Profile as ProviderProfile,
4};
5use futures_lite::StreamExt;
6use std::{future::Future, path::PathBuf, sync::Arc};
7
8/// Provider for local llama.cpp GGUF models from disk.
9#[derive(Clone, Debug)]
10pub struct LlamaProvider {
11    inner: Arc<ProviderConfig>,
12}
13
14impl LlamaProvider {
15    /// Create a provider rooted at a directory containing GGUF models.
16    pub fn new(models_dir: impl Into<PathBuf>) -> Self {
17        Self {
18            inner: Arc::new(ProviderConfig {
19                models_dir: models_dir.into(),
20            }),
21        }
22    }
23}
24
25impl LanguageModelProvider for LlamaProvider {
26    type Model = Llama;
27    type Error = LlamaError;
28
29    fn list_models(&self) -> impl Future<Output = Result<Vec<ModelProfile>, Self::Error>> + Send {
30        let cfg = self.inner.clone();
31        async move {
32            let mut profiles = Vec::new();
33            let mut entries = async_fs::read_dir(&cfg.models_dir)
34                .await
35                .map_err(|err| LlamaError::Model(err.to_string()))?;
36
37            while let Some(entry) = entries.next().await {
38                let entry = entry.map_err(|err| LlamaError::Model(err.to_string()))?;
39                let path = entry.path();
40                let Some(ext) = path.extension().and_then(|s| s.to_str()) else {
41                    continue;
42                };
43                if ext != "gguf" {
44                    continue;
45                }
46                let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
47                    continue;
48                };
49                profiles.push(ModelProfile::new(
50                    name.to_string(),
51                    "llama.cpp",
52                    name.to_string(),
53                    "Local GGUF model",
54                    8192,
55                ));
56            }
57
58            Ok(profiles)
59        }
60    }
61
62    fn get_model(
63        &self,
64        name: &str,
65    ) -> impl Future<Output = Result<Self::Model, Self::Error>> + Send {
66        let cfg = self.inner.clone();
67        let name = name.to_string();
68        async move {
69            let path = cfg.models_dir.join(name);
70            Llama::from_file(path)
71        }
72    }
73
74    fn profile() -> ProviderProfile {
75        ProviderProfile::new("llama", "Local llama.cpp GGUF provider")
76    }
77}
78
79#[derive(Debug, Clone)]
80struct ProviderConfig {
81    models_dir: PathBuf,
82}