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 fn local_settings(mut self, settings: troupekit_local::LocalChatSettings) -> Self {
206 self.local_settings = settings;
207 self
208 }
209
210 pub(crate) fn fetch(&self) -> Fetch<'_> {
211 Fetch {
212 owner: self.name(),
213 download: self.download,
214 transport: self.transport_handle(),
215 }
216 }
217
218 pub(crate) async fn load_local(mut self, loads: &mut Loads) -> Result<Self, KitError> {
223 if self.route.local_model.is_some() {
224 return Ok(self);
225 }
226 let selector = self.selector();
227 let from_selector = selector
228 .as_deref()
229 .and_then(|s| s.strip_prefix("local/"))
230 .filter(|_| !self.has_client())
231 .map(str::to_string);
232 let choice = match (from_selector.clone(), self.local.clone()) {
233 (Some(_), Some(_)) => {
234 return Err(KitError::config(
235 self.name(),
236 "name the on-device model once: .model(\"local/<id>\") or .local(..)",
237 ))
238 }
239 (Some(id), None) => LocalChoice::Catalog(id),
240 (None, Some(choice)) => choice,
241 (None, None) => return Ok(self),
242 };
243 if !troupekit_agent::persona::valid_name(self.name()) {
244 return Err(KitError::config(
245 self.name(),
246 "name must be 1 to 64 of [a-z0-9-], not starting with `-`",
247 ));
248 }
249 let local_only = !self.has_client() && (selector.is_none() || from_selector.is_some());
250 let model = load(&choice, &self.fetch(), loads, false).await?;
251 if selector.is_none() {
252 self.set_selector(choice.chat_id());
253 }
254 let chat = LocalChat::new(model.clone(), choice.chat_id())
255 .with_settings(self.local_settings.clone());
256 self.route.on_device = Some((Arc::new(chat), Price::FREE));
257 self.route.local_model = Some(model);
258 self.route.local_only = local_only;
259 assert!(self.selector().is_some(), "a loaded agent has a selector");
260 Ok(self)
261 }
262
263 #[cfg(feature = "knowledge")]
267 pub(crate) async fn local_embedder(
268 &self,
269 choice: &LocalChoice,
270 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
271 let model = load(choice, &self.fetch(), &mut Loads::new(), true).await?;
272 embedder_of(self.name(), &model)
273 }
274}
275
276#[cfg(feature = "knowledge")]
280pub(crate) fn embedder_of(
281 owner: &str,
282 model: &Arc<dyn LocalModel>,
283) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
284 match troupekit_local::LocalEmbedder::new(model.clone()) {
285 Ok(embedder) => Ok(Arc::new(embedder)),
286 Err(troupekit_local::LocalError::Unsupported(_)) => Err(KitError::config(
287 owner,
288 "the local model cannot embed: call Knowledge::dir(..).local_embedder(..) \
289 with a model that can, or .on_device_embedder(..)",
290 )),
291 Err(other) => Err(other.into()),
292 }
293}