1use crate::agent::Agent;
2use crate::error::KitError;
3use std::collections::BTreeMap;
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use troupekit_local::{LocalCatalog, LocalChat, LocalModel, ModelCache};
8use troupekit_providers::{Price, Transport};
9
10#[non_exhaustive]
14#[derive(Clone)]
15pub enum LocalChoice {
16 Catalog(String),
17 File(PathBuf),
18 Model(Arc<dyn LocalModel>),
19}
20
21impl fmt::Debug for LocalChoice {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 match self {
24 LocalChoice::Catalog(id) => f.debug_tuple("Catalog").field(id).finish(),
25 LocalChoice::File(path) => f.debug_tuple("File").field(path).finish(),
26 LocalChoice::Model(_) => f.write_str("Model(..)"),
27 }
28 }
29}
30
31impl From<&str> for LocalChoice {
32 fn from(id: &str) -> Self {
33 LocalChoice::Catalog(id.to_string())
34 }
35}
36
37impl From<String> for LocalChoice {
38 fn from(id: String) -> Self {
39 LocalChoice::Catalog(id)
40 }
41}
42
43impl From<PathBuf> for LocalChoice {
44 fn from(path: PathBuf) -> Self {
45 LocalChoice::File(path)
46 }
47}
48
49impl From<&Path> for LocalChoice {
50 fn from(path: &Path) -> Self {
51 LocalChoice::File(path.to_path_buf())
52 }
53}
54
55impl From<Arc<dyn LocalModel>> for LocalChoice {
56 fn from(model: Arc<dyn LocalModel>) -> Self {
57 LocalChoice::Model(model)
58 }
59}
60
61impl LocalChoice {
62 fn key(&self) -> Option<String> {
63 match self {
64 LocalChoice::Catalog(id) => Some(format!("catalog:{id}")),
65 LocalChoice::File(path) => Some(format!("file:{}", path.display())),
66 LocalChoice::Model(_) => None,
67 }
68 }
69
70 fn chat_id(&self) -> String {
71 match self {
72 LocalChoice::Catalog(id) => format!("local/{id}"),
73 LocalChoice::File(path) => {
74 let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("model");
75 format!("local/{stem}")
76 }
77 LocalChoice::Model(_) => "local/model".to_string(),
78 }
79 }
80}
81
82pub(crate) type Loads = BTreeMap<String, Arc<dyn LocalModel>>;
85
86pub(crate) struct Fetch<'a> {
89 pub owner: &'a str,
90 pub download: bool,
91 pub transport: Option<Arc<dyn Transport>>,
92}
93
94pub(crate) async fn load(
99 choice: &LocalChoice,
100 fetch: &Fetch<'_>,
101 loads: &mut Loads,
102 embeddings: bool,
103) -> Result<Arc<dyn LocalModel>, KitError> {
104 let key = match (choice, choice.key()) {
105 (LocalChoice::Model(model), _) => return Ok(model.clone()),
106 (_, key) => key.expect("file and catalog choices have a key"),
107 };
108 let key = if embeddings {
109 format!("{key}:embed")
110 } else {
111 key
112 };
113 if let Some(model) = loads.get(&key) {
114 return Ok(model.clone());
115 }
116 let path = match choice {
117 LocalChoice::File(path) => path.clone(),
118 LocalChoice::Catalog(id) => cached(id, fetch).await?,
119 LocalChoice::Model(_) => unreachable!("a loaded model returns above"),
120 };
121 let model = load_file(fetch.owner, &path, embeddings)?;
122 loads.insert(key, model.clone());
123 assert!(!loads.is_empty());
124 Ok(model)
125}
126
127async fn cached(id: &str, fetch: &Fetch<'_>) -> Result<PathBuf, KitError> {
128 let Some(spec) = LocalCatalog::builtin().get(id) else {
129 return Err(KitError::config(
130 fetch.owner,
131 format!("unknown local model `{id}`: pick an id from LocalCatalog::builtin()"),
132 ));
133 };
134 let cache = ModelCache::default_dir()?;
135 if let Some(path) = cache.path(spec) {
136 return Ok(path);
137 }
138 if !fetch.download {
139 return Err(KitError::config(
140 fetch.owner,
141 format!(
142 "local model `{id}` is not in {}: call .download(true) to let build \
143 fetch it with ModelCache::fetch, or pass a file to .local(..)",
144 cache.dir().display()
145 ),
146 ));
147 }
148 let transport = match &fetch.transport {
149 Some(t) => t.clone(),
150 None => crate::model::default_transport(fetch.owner)?,
151 };
152 let path = cache.fetch(spec, transport.as_ref()).await?;
153 assert!(
154 cache.path(spec).is_some(),
155 "a fetched model is in the cache"
156 );
157 Ok(path)
158}
159
160#[cfg(feature = "llama")]
161fn load_file(owner: &str, path: &Path, embeddings: bool) -> Result<Arc<dyn LocalModel>, KitError> {
162 use troupekit_local::llama::{LlamaModel, LlamaSettings};
163 assert!(!owner.is_empty());
164 let settings = LlamaSettings::default().with_embeddings(embeddings);
165 let model = LlamaModel::load(path, settings)?;
166 assert!(
167 !embeddings || model.info().embedding_dims() > 0,
168 "an embedding load advertises its dimensions"
169 );
170 Ok(Arc::new(model))
171}
172
173#[cfg(not(feature = "llama"))]
174fn load_file(owner: &str, path: &Path, _embeddings: bool) -> Result<Arc<dyn LocalModel>, KitError> {
175 Err(KitError::config(
176 owner,
177 format!(
178 "loading `{}` needs the `llama` feature; or pass a loaded model to .local(..)",
179 path.display()
180 ),
181 ))
182}
183
184impl Agent {
185 pub fn local(mut self, choice: impl Into<LocalChoice>) -> Self {
189 self.local = Some(choice.into());
190 self
191 }
192
193 pub fn download(mut self, on: bool) -> Self {
197 self.download = on;
198 self
199 }
200
201 pub(crate) fn fetch(&self) -> Fetch<'_> {
202 Fetch {
203 owner: self.name(),
204 download: self.download,
205 transport: self.transport_handle(),
206 }
207 }
208
209 pub(crate) async fn load_local(mut self, loads: &mut Loads) -> Result<Self, KitError> {
213 if self.route.local_model.is_some() {
214 return Ok(self);
215 }
216 let from_selector = self
217 .selector()
218 .and_then(|s| s.strip_prefix("local/"))
219 .filter(|_| !self.has_client())
220 .map(str::to_string);
221 let choice = match (from_selector.clone(), self.local.clone()) {
222 (Some(_), Some(_)) => {
223 return Err(KitError::config(
224 self.name(),
225 "name the on-device model once: .model(\"local/<id>\") or .local(..)",
226 ))
227 }
228 (Some(id), None) => LocalChoice::Catalog(id),
229 (None, Some(choice)) => choice,
230 (None, None) => return Ok(self),
231 };
232 let local_only =
233 !self.has_client() && (self.selector().is_none() || from_selector.is_some());
234 let model = load(&choice, &self.fetch(), loads, false).await?;
235 if self.selector().is_none() {
236 self.set_selector(choice.chat_id());
237 }
238 let chat = LocalChat::new(model.clone(), choice.chat_id());
239 self.route.on_device = Some((Arc::new(chat), Price::FREE));
240 self.route.local_model = Some(model);
241 self.route.local_only = local_only;
242 assert!(self.selector().is_some(), "a loaded agent has a selector");
243 Ok(self)
244 }
245
246 #[cfg(feature = "knowledge")]
250 pub(crate) async fn local_embedder(
251 &self,
252 choice: &LocalChoice,
253 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
254 let model = load(choice, &self.fetch(), &mut Loads::new(), true).await?;
255 embedder_of(self.name(), &model)
256 }
257}
258
259#[cfg(feature = "knowledge")]
263pub(crate) fn embedder_of(
264 owner: &str,
265 model: &Arc<dyn LocalModel>,
266) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
267 match troupekit_local::LocalEmbedder::new(model.clone()) {
268 Ok(embedder) => Ok(Arc::new(embedder)),
269 Err(troupekit_local::LocalError::Unsupported(_)) => Err(KitError::config(
270 owner,
271 "the local model cannot embed: call Knowledge::dir(..).local_embedder(..) \
272 with a model that can, or .on_device_embedder(..)",
273 )),
274 Err(other) => Err(other.into()),
275 }
276}