1use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7use tokio::process::Command;
8use weirdnet_agent::Modalities;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12#[non_exhaustive]
13pub enum EngineKind {
14 Llamacpp,
16 Vllm,
18 Mlx,
21}
22
23impl EngineKind {
24 pub fn name(self) -> &'static str {
25 match self {
26 EngineKind::Llamacpp => "llamacpp",
27 EngineKind::Vllm => "vllm",
28 EngineKind::Mlx => "mlx",
29 }
30 }
31
32 pub fn capabilities(self) -> Capabilities {
34 match self {
35 EngineKind::Llamacpp | EngineKind::Vllm => Capabilities { chat: true, embeddings: true, vision: true, audio: true },
36 EngineKind::Mlx => Capabilities::text(),
37 }
38 }
39}
40
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[non_exhaustive]
45pub struct Capabilities {
46 pub chat: bool,
48 pub embeddings: bool,
50 pub vision: bool,
52 pub audio: bool,
54}
55
56impl Capabilities {
57 pub fn text() -> Self {
59 Self { chat: true, ..Self::default() }
60 }
61
62 pub fn embeddings() -> Self {
64 Self { embeddings: true, ..Self::default() }
65 }
66
67 pub fn with_vision(mut self, on: bool) -> Self {
68 self.vision = on;
69 self
70 }
71
72 pub fn with_audio(mut self, on: bool) -> Self {
73 self.audio = on;
74 self
75 }
76
77 pub fn inputs(&self) -> Modalities {
79 Modalities::new(self.vision, self.audio)
80 }
81
82 pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
84 self.inputs().lacking(needed)
85 }
86
87 pub fn intersect(self, other: Self) -> Self {
89 Self {
90 chat: self.chat && other.chat,
91 embeddings: self.embeddings && other.embeddings,
92 vision: self.vision && other.vision,
93 audio: self.audio && other.audio,
94 }
95 }
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct EngineConfig {
101 pub kind: EngineKind,
102 pub program: PathBuf,
103 pub extra_args: Vec<String>,
105 pub ready_timeout: Duration,
106}
107
108impl EngineConfig {
109 pub fn llamacpp(program: impl Into<PathBuf>) -> Self {
110 Self { kind: EngineKind::Llamacpp, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(300) }
111 }
112
113 pub fn vllm(program: impl Into<PathBuf>) -> Self {
114 Self { kind: EngineKind::Vllm, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
115 }
116
117 pub fn mlx(program: impl Into<PathBuf>) -> Self {
120 Self { kind: EngineKind::Mlx, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
121 }
122
123 pub fn command(&self, model: &ModelLaunch, port: u16, api_key: &str) -> Command {
129 let mut cmd = Command::new(&self.program);
130 match self.kind {
131 EngineKind::Llamacpp => {
132 cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--alias", &model.id, "--no-webui"]);
133 if let Some(ctx) = model.context {
134 cmd.args(["--ctx-size", &ctx.to_string()]);
135 }
136 if let Some(slots) = model.slots {
137 cmd.args(["--parallel", &slots.to_string()]);
138 }
139 if let Some(ngl) = model.gpu_layers {
140 cmd.args(["--n-gpu-layers", &ngl.to_string()]);
141 }
142 if model.embedding {
143 cmd.arg("--embedding");
144 }
145 cmd.env("LLAMA_API_KEY", api_key);
146 }
147 EngineKind::Vllm => {
148 cmd.args(["serve", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
149 if let Some(ctx) = model.context {
150 cmd.args(["--max-model-len", &ctx.to_string()]);
151 }
152 if let Some(slots) = model.slots {
153 cmd.args(["--max-num-seqs", &slots.to_string()]);
154 }
155 cmd.env("VLLM_API_KEY", api_key);
156 }
157 EngineKind::Mlx => {
158 let max = model.context.unwrap_or(crate::mlx::DEFAULT_MAX_TOKENS).to_string();
161 cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--max-tokens", &max]);
162 }
163 }
164 cmd.args(&self.extra_args).args(&model.extra_args);
165 cmd
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub struct ModelLaunch {
172 pub id: String,
174 pub engine: EngineKind,
175 pub source: String,
178 pub context: Option<u32>,
179 pub slots: Option<u32>,
181 pub gpu_layers: Option<i32>,
183 pub swap_group: Option<String>,
185 pub embedding: bool,
186 pub extra_args: Vec<String>,
187 #[serde(default, with = "opt_secs")]
189 pub idle_ttl: Option<Duration>,
190 #[serde(default)]
193 pub wrap: Option<Wrap>,
194}
195
196#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
198pub struct Wrap {
199 pub url: String,
201 #[serde(default, skip_serializing)]
203 pub api_key: Option<String>,
204}
205
206impl std::fmt::Debug for Wrap {
207 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208 f.debug_struct("Wrap").field("url", &self.url).field("api_key", &self.api_key.as_ref().map(|_| "<redacted>")).finish()
209 }
210}
211
212impl Wrap {
213 pub fn check(&self) -> Result<(), String> {
215 let rest = self.url.strip_prefix("http://").ok_or_else(|| format!("wrap url {} must start with http:// (loopback only)", self.url))?;
216 let host = match rest.strip_prefix('[') {
217 Some(v6) => v6.split(']').next().unwrap_or(""),
218 None => rest.split(['/', ':']).next().unwrap_or(""),
219 };
220 if matches!(host, "127.0.0.1" | "localhost" | "::1") { Ok(()) } else { Err(format!("wrap url {} is not loopback", self.url)) }
221 }
222
223 pub fn base(&self) -> String {
224 self.url.trim_end_matches('/').trim_end_matches("/v1").to_string()
225 }
226}
227
228mod opt_secs {
229 use std::time::Duration;
230
231 use serde::{Deserialize, Deserializer, Serializer};
232
233 pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
234 match d {
235 Some(d) => s.serialize_some(&d.as_secs()),
236 None => s.serialize_none(),
237 }
238 }
239
240 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
241 Ok(Option::<u64>::deserialize(d)?.map(Duration::from_secs))
242 }
243}
244
245impl ModelLaunch {
246 pub fn new(id: impl Into<String>, engine: EngineKind, source: impl Into<String>) -> Self {
247 Self {
248 id: id.into(),
249 engine,
250 source: source.into(),
251 context: None,
252 slots: None,
253 gpu_layers: None,
254 swap_group: None,
255 embedding: false,
256 extra_args: Vec::new(),
257 idle_ttl: None,
258 wrap: None,
259 }
260 }
261
262 pub fn capabilities(&self) -> Capabilities {
267 let own = if self.embedding {
268 Capabilities::embeddings()
269 } else {
270 let media = self.engine == EngineKind::Llamacpp && self.has_projector();
271 Capabilities::text().with_vision(media).with_audio(media)
272 };
273 own.intersect(self.engine.capabilities())
274 }
275
276 fn has_projector(&self) -> bool {
277 self.extra_args.iter().any(|a| matches!(a.split('=').next(), Some("--mmproj" | "-mm" | "--mmproj-url" | "-mmu")))
278 }
279}
280
281pub fn find_in_path(name: &str) -> Option<PathBuf> {
283 let path = std::env::var_os("PATH")?;
284 std::env::split_paths(&path).map(|d| d.join(name)).find(|p| is_executable(p))
285}
286
287fn is_executable(p: &Path) -> bool {
288 #[cfg(unix)]
289 {
290 use std::os::unix::fs::PermissionsExt;
291 std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
292 }
293 #[cfg(not(unix))]
294 {
295 p.is_file()
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 fn args(cmd: &Command) -> Vec<String> {
304 cmd.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect()
305 }
306
307 #[test]
308 fn llama_args() {
309 let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/m/q.gguf");
310 m.context = Some(8192);
311 m.slots = Some(2);
312 let cmd = EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k");
313 let a = args(&cmd);
314 assert!(a.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
315 assert!(a.windows(2).any(|w| w == ["--port", "4321"]));
316 assert!(a.windows(2).any(|w| w == ["--alias", "qwen3-8b"]));
317 assert!(a.windows(2).any(|w| w == ["--parallel", "2"]));
318 assert!(!a.iter().any(|x| x == "k"), "the key stays out of argv");
319 }
320
321 #[test]
322 fn wrap_is_loopback_only() {
323 let w = |u: &str| Wrap { url: u.into(), api_key: None }.check();
324 assert!(w("http://127.0.0.1:8000").is_ok());
325 assert!(w("http://localhost:8000/").is_ok());
326 assert!(w("http://[::1]:8000").is_ok());
327 assert!(w("https://127.0.0.1:8000").is_err());
328 assert!(w("http://10.0.0.2:8000").is_err());
329 assert!(w("http://127.0.0.1.evil:8000").is_err());
330 assert_eq!(Wrap { url: "http://127.0.0.1:8000/v1/".into(), api_key: None }.base(), "http://127.0.0.1:8000");
331 }
332
333 #[test]
334 fn vllm_args() {
335 let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B");
336 let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
337 assert_eq!(&a[..2], ["serve", "Qwen/Qwen3-8B"]);
338 assert!(a.windows(2).any(|w| w == ["--served-model-name", "big"]));
339 }
340
341 #[test]
342 fn mlx_args() {
343 let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Mlx, "/m/mlx/Qwen3-8B-4bit");
344 m.context = Some(4096);
345 let cmd = EngineConfig::mlx("/v/bin/mlx_lm.server").command(&m, 9, "k");
346 assert_eq!(args(&cmd), ["--model", "/m/mlx/Qwen3-8B-4bit", "--host", "127.0.0.1", "--port", "9", "--max-tokens", "4096"]);
347 assert!(cmd.as_std().get_envs().all(|(_, v)| v != Some(std::ffi::OsStr::new("k"))), "MLX-LM gets no key");
348 m.context = None;
349 let a = args(&EngineConfig::mlx("mlx_lm.server").command(&m, 9, "k"));
350 assert_eq!(a.last().map(String::as_str), Some("32768"));
351 assert_eq!(serde_json::to_string(&EngineKind::Mlx).unwrap(), "\"mlx\"");
352 }
353
354 #[test]
355 fn capabilities_as_modalities() {
356 let media = Capabilities::text().with_vision(true).with_audio(true);
357 assert_eq!(media.inputs(), Modalities::new(true, true));
358 assert_eq!(Capabilities::text().lacking(Modalities::VISION), Some("images"));
359 assert_eq!(Capabilities::text().with_vision(true).lacking(Modalities::new(true, true)), Some("audio"));
360 assert_eq!(media.lacking(Modalities::AUDIO), None);
361 assert_eq!(
362 ModelLaunch::new("x", EngineKind::Mlx, "/m/x").capabilities().lacking(Modalities::VISION),
363 Some("images"),
364 "MLX never takes images"
365 );
366 }
367
368 #[test]
369 fn capabilities() {
370 let mut m = ModelLaunch::new("x", EngineKind::Mlx, "/m/x");
371 assert_eq!(m.capabilities(), Capabilities::text());
372 m.extra_args = vec!["--mmproj".into(), "/p".into()];
373 assert!(!m.capabilities().vision, "MLX-LM never takes images");
374 m.embedding = true;
375 assert_eq!(m.capabilities(), Capabilities::default(), "MLX-LM serves no embeddings");
376
377 let mut l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
378 assert_eq!(l.capabilities(), Capabilities::text());
379 l.extra_args = vec!["--mmproj=/p/mm.gguf".into()];
380 let c = l.capabilities();
381 assert!(c.chat && c.vision && c.audio && !c.embeddings);
382 l.embedding = true;
383 assert_eq!(l.capabilities(), Capabilities::embeddings());
384
385 let v = ModelLaunch::new("v", EngineKind::Vllm, "Qwen/Qwen3-8B");
386 assert_eq!(v.capabilities(), Capabilities::text());
387 assert!(!EngineKind::Mlx.capabilities().embeddings && EngineKind::Llamacpp.capabilities().vision);
388 }
389}