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