Skip to main content

weirdnet_backends/
engine.rs

1//! How each engine is launched and probed.
2
3use 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    /// llama.cpp `llama-server`.
15    Llamacpp,
16    /// `vllm serve` (Linux, NVIDIA sm_80+ or supported ROCm).
17    Vllm,
18    /// MLX-LM's `mlx_lm.server` (macOS on Apple silicon). Text only, no embeddings; the
19    /// supervisor puts a key-checking proxy in front of it (see [`crate::mlx`]).
20    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    /// The most this engine can serve. A model may serve less (see [`ModelLaunch::capabilities`]).
33    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/// What a model takes, so routing can keep requests off models that can't serve them: images
42/// or audio off text-only models, embeddings off chat-only engines such as MLX-LM.
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[non_exhaustive]
45pub struct Capabilities {
46    /// Chat and raw text completions.
47    pub chat: bool,
48    /// `/v1/embeddings`.
49    pub embeddings: bool,
50    /// Image content parts.
51    pub vision: bool,
52    /// Audio content parts.
53    pub audio: bool,
54}
55
56impl Capabilities {
57    /// Text chat and completions only.
58    pub fn text() -> Self {
59        Self { chat: true, ..Self::default() }
60    }
61
62    /// Embeddings only.
63    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    /// The inputs beyond text, as `weirdnet-agent` [`Modalities`] (what catalog entries carry).
78    pub fn inputs(&self) -> Modalities {
79        Modalities::new(self.vision, self.audio)
80    }
81
82    /// What a request needing `needed` would lack here (`"images"`, `"audio"`, ...), if anything.
83    pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
84        self.inputs().lacking(needed)
85    }
86
87    /// What both allow.
88    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/// One engine binary and how long it may take to come up.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct EngineConfig {
101    pub kind: EngineKind,
102    pub program: PathBuf,
103    /// Arguments added to every launch of this engine.
104    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    /// `program` is `mlx_lm.server`, such as [`crate::mlx::server_in`] of a venv made by
118    /// [`crate::mlx::install`].
119    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    /// The command for `model` on `127.0.0.1:port`. The API key goes in the environment, not the
124    /// command line, so other local users can't read it from the process list.
125    ///
126    /// MLX-LM takes no API key: the supervisor starts it on a private port and checks the key in
127    /// a proxy on the advertised one, so `api_key` is not passed to it.
128    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                // mlx_lm.server stops at 512 tokens unless told otherwise; the others run to the
159                // context window.
160                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/// A model this node may be told to load.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub struct ModelLaunch {
172    /// Pool id; also the engine's served model name.
173    pub id: String,
174    pub engine: EngineKind,
175    /// A GGUF path for llama.cpp; a path or Hub id for vLLM; an MLX-format model directory (or
176    /// Hub id) for MLX-LM.
177    pub source: String,
178    pub context: Option<u32>,
179    /// Concurrent requests (llama.cpp slots, vLLM max sequences).
180    pub slots: Option<u32>,
181    /// llama.cpp `--n-gpu-layers`; `None` keeps the engine's default (all that fit).
182    pub gpu_layers: Option<i32>,
183    /// Models in the same group are never resident together.
184    pub swap_group: Option<String>,
185    pub embedding: bool,
186    pub extra_args: Vec<String>,
187    /// Unload after this long without requests; `None` keeps it loaded.
188    #[serde(default, with = "opt_secs")]
189    pub idle_ttl: Option<Duration>,
190    /// Wrap a stock server already running on loopback (such as `vllm serve` or `llama-server`
191    /// started by hand) instead of starting an engine: the node only probes, advertises and forwards.
192    #[serde(default)]
193    pub wrap: Option<Wrap>,
194}
195
196/// A stock OpenAI-compatible server the node forwards to but doesn't own.
197#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
198pub struct Wrap {
199    /// Base URL without `/v1`, such as `http://127.0.0.1:8000`. Must be loopback.
200    pub url: String,
201    /// The server's API key, if it wants one (read from the environment or a file by the caller).
202    #[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    /// Only loopback URLs: the wrapped server is on this machine, reached without TLS.
214    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    /// What this model takes. Embedding models only embed (and can't run on MLX-LM at all). A
263    /// llama.cpp model takes images and audio when it has a multimodal projector (`--mmproj` in
264    /// `extra_args`); the projector decides which, and llama-server refuses what it lacks. vLLM
265    /// and MLX-LM models are text only here.
266    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
281/// The first executable called `name` on `PATH`.
282pub 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}