1use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use serde::{Deserialize, Serialize};
8use tokio::process::Command;
9use weirdnet_agent::remote::catalog::{CatalogModel, Purpose};
10use weirdnet_agent::speech::SpeechProfile;
11use weirdnet_agent::{MediaLimits, Modalities};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
14#[serde(rename_all = "lowercase")]
15#[non_exhaustive]
16pub enum EngineKind {
17 Llamacpp,
19 Vllm,
21 Mlx,
24 #[serde(rename = "vllm-omni")]
29 VllmOmni,
30}
31
32impl EngineKind {
33 pub fn name(self) -> &'static str {
34 match self {
35 EngineKind::Llamacpp => "llamacpp",
36 EngineKind::Vllm => "vllm",
37 EngineKind::Mlx => "mlx",
38 EngineKind::VllmOmni => "vllm-omni",
39 }
40 }
41
42 pub fn parse(name: &str) -> Option<Self> {
45 match name.trim().to_ascii_lowercase().as_str() {
46 "llamacpp" | "llama.cpp" | "llama-server" => Some(EngineKind::Llamacpp),
47 "vllm" => Some(EngineKind::Vllm),
48 "mlx" | "mlx-lm" => Some(EngineKind::Mlx),
49 "vllm-omni" | "vllm_omni" | "omni" => Some(EngineKind::VllmOmni),
50 _ => None,
51 }
52 }
53
54 pub fn capabilities(self) -> Capabilities {
58 match self {
59 EngineKind::Llamacpp => {
60 Capabilities { chat: true, embeddings: true, vision: true, audio: true, transcribe: true, speak: true, ..Capabilities::default() }
61 }
62 EngineKind::Vllm => {
63 Capabilities { chat: true, embeddings: true, vision: true, audio: true, transcribe: true, video: true, ..Capabilities::default() }
64 }
65 EngineKind::Mlx => Capabilities::text(),
66 EngineKind::VllmOmni => Capabilities { chat: true, speak: true, ..Capabilities::default() },
67 }
68 }
69
70 pub fn supported(self, os: &str, arch: &str) -> bool {
74 match self {
75 EngineKind::Llamacpp => true,
76 EngineKind::Vllm | EngineKind::VllmOmni => os == "linux",
77 EngineKind::Mlx => crate::mlx::supported(os, arch),
78 }
79 }
80
81 pub fn supported_here(self) -> bool {
84 self.supported(std::env::consts::OS, std::env::consts::ARCH)
85 }
86
87 pub fn program(self) -> &'static str {
91 match self {
92 EngineKind::Llamacpp => "llama-server",
93 EngineKind::Vllm | EngineKind::VllmOmni => "vllm",
94 EngineKind::Mlx => "mlx_lm.server",
95 }
96 }
97
98 pub fn install_hint(self) -> &'static str {
100 match self {
101 EngineKind::Llamacpp => "install llama.cpp (https://github.com/ggml-org/llama.cpp) and put `llama-server` on PATH",
102 EngineKind::Vllm => "install vLLM in a venv (`pip install vllm`; Linux, NVIDIA sm_80+ or supported ROCm) and put its `vllm` on PATH",
103 EngineKind::VllmOmni => {
104 "install vLLM and vLLM-Omni in one venv, pinned to one release (`pip install vllm vllm-omni`; Linux, NVIDIA), and put its `vllm` on PATH; it runs as `vllm serve MODEL --omni`"
105 }
106 EngineKind::Mlx => "install MLX-LM into a venv (weirdnet_backends::mlx::install; macOS on Apple silicon)",
107 }
108 }
109}
110
111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
116#[non_exhaustive]
117pub struct Capabilities {
118 pub chat: bool,
120 pub embeddings: bool,
122 pub vision: bool,
124 pub audio: bool,
126 #[serde(default, skip_serializing_if = "MediaLimits::is_unknown")]
131 pub limits: MediaLimits,
132 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
138 pub transcribe: bool,
139 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
144 pub video: bool,
145 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
151 pub speak: bool,
152}
153
154impl Capabilities {
155 pub fn text() -> Self {
157 Self { chat: true, ..Self::default() }
158 }
159
160 pub fn embeddings() -> Self {
162 Self { embeddings: true, ..Self::default() }
163 }
164
165 pub fn with_vision(mut self, on: bool) -> Self {
166 self.vision = on;
167 self
168 }
169
170 pub fn with_audio(mut self, on: bool) -> Self {
171 self.audio = on;
172 self
173 }
174
175 pub fn with_limits(mut self, limits: MediaLimits) -> Self {
177 self.limits = limits;
178 self
179 }
180
181 pub fn with_transcribe(mut self, on: bool) -> Self {
183 self.transcribe = on;
184 self
185 }
186
187 pub fn with_video(mut self, on: bool) -> Self {
189 self.video = on;
190 self
191 }
192
193 pub fn with_speak(mut self, on: bool) -> Self {
195 self.speak = on;
196 self
197 }
198
199 pub fn apply_to(&self, entry: CatalogModel) -> CatalogModel {
202 entry.with_inputs(self.inputs()).with_limits(self.limits)
203 }
204
205 pub fn purpose(&self, embedding: bool) -> Purpose {
211 if embedding {
212 Purpose::Embedding
213 } else if self.speak {
214 Purpose::Speak
215 } else if self.transcribe {
216 Purpose::Transcribe
217 } else {
218 Purpose::Chat
219 }
220 }
221
222 pub fn inputs(&self) -> Modalities {
225 Modalities::new(self.vision, self.audio).with_video(self.video)
226 }
227
228 pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
230 self.inputs().lacking(needed)
231 }
232
233 pub fn intersect(self, other: Self) -> Self {
236 Self {
237 chat: self.chat && other.chat,
238 embeddings: self.embeddings && other.embeddings,
239 vision: self.vision && other.vision,
240 audio: self.audio && other.audio,
241 limits: self.limits.tightest(other.limits),
242 transcribe: self.transcribe && other.transcribe,
243 video: self.video && other.video,
244 speak: self.speak && other.speak,
245 }
246 }
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
251pub struct EngineConfig {
252 pub kind: EngineKind,
253 pub program: PathBuf,
254 pub extra_args: Vec<String>,
256 pub ready_timeout: Duration,
257}
258
259impl EngineConfig {
260 pub fn llamacpp(program: impl Into<PathBuf>) -> Self {
261 Self { kind: EngineKind::Llamacpp, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(300) }
262 }
263
264 pub fn vllm(program: impl Into<PathBuf>) -> Self {
265 Self { kind: EngineKind::Vllm, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
266 }
267
268 pub fn vllm_omni(program: impl Into<PathBuf>) -> Self {
271 Self { kind: EngineKind::VllmOmni, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
272 }
273
274 pub async fn version(&self) -> Option<String> {
278 let mut cmd = Command::new(&self.program);
279 cmd.arg("--version").stdin(std::process::Stdio::null()).kill_on_drop(true);
280 let out = tokio::time::timeout(Duration::from_secs(30), cmd.output()).await.ok()?.ok()?;
281 let text = [out.stdout, out.stderr].iter().map(|b| String::from_utf8_lossy(b).into_owned()).collect::<Vec<_>>().join("\n");
282 text.lines().map(str::trim).find(|l| !l.is_empty()).map(str::to_string)
283 }
284
285 pub fn mlx(program: impl Into<PathBuf>) -> Self {
288 Self { kind: EngineKind::Mlx, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
289 }
290
291 pub fn command(&self, model: &ModelLaunch, port: u16, api_key: &str) -> Command {
300 let mut cmd = Command::new(&self.program);
301 for (name, value) in model.env.iter() {
302 cmd.env(name, value);
303 }
304 match self.kind {
305 EngineKind::Llamacpp => {
306 cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--alias", &model.id, "--no-webui"]);
307 if let Some(ctx) = model.context {
308 cmd.args(["--ctx-size", &ctx.to_string()]);
309 }
310 if let Some(slots) = model.slots {
311 cmd.args(["--parallel", &slots.to_string()]);
312 }
313 if let Some(ngl) = model.gpu_layers {
314 cmd.args(["--n-gpu-layers", &ngl.to_string()]);
315 }
316 if model.embedding {
317 cmd.arg("--embedding");
318 }
319 if let Some(mmproj) = &model.mmproj {
320 cmd.args(["--mmproj", mmproj]);
321 }
322 for a in &model.adapters {
326 cmd.args(["--lora", &a.path]);
327 }
328 if !model.adapters.is_empty() {
329 cmd.arg("--lora-init-without-apply");
330 }
331 cmd.env("LLAMA_API_KEY", api_key);
332 }
333 EngineKind::Vllm => {
334 cmd.args(["serve", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
335 if let Some(ctx) = model.context {
336 cmd.args(["--max-model-len", &ctx.to_string()]);
337 }
338 if let Some(slots) = model.slots {
339 cmd.args(["--max-num-seqs", &slots.to_string()]);
340 }
341 if model.runtime_lora() {
342 cmd.arg("--enable-lora");
343 if !model.adapters.is_empty() {
344 cmd.arg("--lora-modules");
346 for a in &model.adapters {
347 cmd.arg(serde_json::json!({"name": a.id, "path": a.path, "base_model_name": model.id}).to_string());
348 }
349 }
350 let max = (model.adapters.len() as u32).max(model.lora_slots.unwrap_or(0)).max(1);
351 cmd.args(["--max-loras", &max.to_string()]);
352 cmd.env("VLLM_ALLOW_RUNTIME_LORA_UPDATING", "True");
355 }
356 cmd.env("VLLM_API_KEY", api_key);
357 }
358 EngineKind::VllmOmni => {
359 cmd.args(["serve", &model.source, "--omni", "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
362 if let Some(ctx) = model.context {
363 cmd.args(["--max-model-len", &ctx.to_string()]);
364 }
365 if let Some(slots) = model.slots {
366 cmd.args(["--max-num-seqs", &slots.to_string()]);
367 }
368 cmd.env("VLLM_API_KEY", api_key);
369 }
370 EngineKind::Mlx => {
371 let max = model.context.unwrap_or(crate::mlx::DEFAULT_MAX_TOKENS).to_string();
374 cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--max-tokens", &max]);
375 }
376 }
377 cmd.args(&self.extra_args).args(&model.extra_args);
378 cmd
379 }
380}
381
382#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
384#[non_exhaustive]
385pub struct LoraAdapter {
386 pub id: String,
388 pub path: String,
390 #[serde(default, skip_serializing_if = "Option::is_none")]
392 pub scale: Option<f32>,
393}
394
395impl Eq for LoraAdapter {}
397
398impl LoraAdapter {
399 pub fn new(id: impl Into<String>, path: impl Into<String>) -> Self {
400 Self { id: id.into(), path: path.into(), scale: None }
401 }
402
403 pub fn with_scale(mut self, scale: f32) -> Self {
404 self.scale = Some(scale);
405 self
406 }
407
408 pub fn effective_scale(&self) -> f32 {
410 self.scale.unwrap_or(1.0)
411 }
412}
413
414#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
416#[non_exhaustive]
417pub struct ModelLaunch {
418 pub id: String,
420 pub engine: EngineKind,
421 pub source: String,
424 pub context: Option<u32>,
425 pub slots: Option<u32>,
427 pub gpu_layers: Option<i32>,
429 pub swap_group: Option<String>,
431 pub embedding: bool,
432 pub extra_args: Vec<String>,
433 #[serde(default, with = "opt_secs")]
435 pub idle_ttl: Option<Duration>,
436 #[serde(default)]
439 pub wrap: Option<Wrap>,
440 #[serde(default, skip_serializing_if = "Vec::is_empty")]
443 pub adapters: Vec<LoraAdapter>,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
449 pub lora_slots: Option<u32>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
453 pub mmproj: Option<String>,
454 #[serde(default, skip_serializing_if = "MediaLimits::is_unknown")]
458 pub limits: MediaLimits,
459 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
464 pub transcribe: bool,
465 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
471 pub video: bool,
472 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
477 pub speak: bool,
478 #[serde(default, skip_serializing_if = "SpeechProfile::is_unknown")]
485 pub speech: SpeechProfile,
486 #[serde(default, skip_serializing_if = "LaunchEnv::is_empty")]
492 pub env: LaunchEnv,
493}
494
495#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(transparent)]
499pub struct LaunchEnv(BTreeMap<String, String>);
500
501impl LaunchEnv {
502 pub fn is_empty(&self) -> bool {
503 self.0.is_empty()
504 }
505
506 pub fn len(&self) -> usize {
507 self.0.len()
508 }
509
510 pub fn get(&self, name: &str) -> Option<&str> {
512 self.0.get(name).map(String::as_str)
513 }
514
515 pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
517 self.0.iter().map(|(k, v)| (k.as_str(), v.as_str()))
518 }
519}
520
521impl std::fmt::Debug for LaunchEnv {
522 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
523 f.debug_list().entries(self.0.keys()).finish()
524 }
525}
526
527#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
529pub struct Wrap {
530 pub url: String,
532 #[serde(default, skip_serializing)]
534 pub api_key: Option<String>,
535}
536
537impl std::fmt::Debug for Wrap {
538 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
539 f.debug_struct("Wrap").field("url", &self.url).field("api_key", &self.api_key.as_ref().map(|_| "<redacted>")).finish()
540 }
541}
542
543impl Wrap {
544 pub fn check(&self) -> Result<(), String> {
546 let rest = self.url.strip_prefix("http://").ok_or_else(|| format!("wrap url {} must start with http:// (loopback only)", self.url))?;
547 let host = match rest.strip_prefix('[') {
548 Some(v6) => v6.split(']').next().unwrap_or(""),
549 None => rest.split(['/', ':']).next().unwrap_or(""),
550 };
551 if matches!(host, "127.0.0.1" | "localhost" | "::1") { Ok(()) } else { Err(format!("wrap url {} is not loopback", self.url)) }
552 }
553
554 pub fn base(&self) -> String {
555 self.url.trim_end_matches('/').trim_end_matches("/v1").to_string()
556 }
557}
558
559mod opt_secs {
560 use std::time::Duration;
561
562 use serde::{Deserialize, Deserializer, Serializer};
563
564 pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
565 match d {
566 Some(d) => s.serialize_some(&d.as_secs()),
567 None => s.serialize_none(),
568 }
569 }
570
571 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
572 Ok(Option::<u64>::deserialize(d)?.map(Duration::from_secs))
573 }
574}
575
576impl ModelLaunch {
577 pub fn new(id: impl Into<String>, engine: EngineKind, source: impl Into<String>) -> Self {
578 Self {
579 id: id.into(),
580 engine,
581 source: source.into(),
582 context: None,
583 slots: None,
584 gpu_layers: None,
585 swap_group: None,
586 embedding: false,
587 extra_args: Vec::new(),
588 idle_ttl: None,
589 wrap: None,
590 adapters: Vec::new(),
591 lora_slots: None,
592 mmproj: None,
593 limits: MediaLimits::UNKNOWN,
594 transcribe: false,
595 video: false,
596 speak: false,
597 speech: SpeechProfile::default(),
598 env: LaunchEnv::default(),
599 }
600 }
601
602 pub fn with_env(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
606 self.env.0.insert(name.into(), value.into());
607 self
608 }
609
610 pub fn with_envs<K: Into<String>, V: Into<String>>(mut self, vars: impl IntoIterator<Item = (K, V)>) -> Self {
612 self.env.0.extend(vars.into_iter().map(|(k, v)| (k.into(), v.into())));
613 self
614 }
615
616 pub fn check_env(&self) -> Result<(), String> {
621 for (name, value) in self.env.iter() {
622 if name.is_empty() || name.contains(['=', '\0']) {
623 return Err(format!("{}: environment variable name {name:?} is not valid", self.id));
624 }
625 if value.contains('\0') {
626 return Err(format!("{}: the value of environment variable {name} has a NUL byte", self.id));
627 }
628 if matches!(name, "LLAMA_API_KEY" | "VLLM_API_KEY") {
629 return Err(format!("{}: {name} is set by the node and can't be overridden", self.id));
630 }
631 }
632 Ok(())
633 }
634
635 pub fn with_video(mut self, on: bool) -> Self {
637 self.video = on;
638 self
639 }
640
641 pub fn with_speak(mut self, on: bool) -> Self {
643 self.speak = on;
644 self
645 }
646
647 pub fn with_speech(mut self, speech: SpeechProfile) -> Self {
649 self.speech = speech;
650 self
651 }
652
653 pub fn cataloged_speech(&self) -> Option<weirdnet_model::SpeechProfile> {
658 if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::VllmOmni) {
659 return None;
660 }
661 let gguf = self.engine == EngineKind::Llamacpp;
662 let name = |p: &str| Path::new(p).file_name().map(|n| n.to_string_lossy().to_ascii_lowercase());
663 let file = name(&self.source);
664 weirdnet_model::hw::by_purpose(weirdnet_model::hw::Purpose::Speak)
665 .into_iter()
666 .filter(|e| e.is_gguf() == gguf)
667 .find(|e| {
668 e.id() == self.id
669 || (!gguf && e.spec.repo.eq_ignore_ascii_case(self.source.trim()))
670 || (gguf && file.is_some() && name(&e.spec.file) == file)
671 })
672 .and_then(|e| e.speech())
673 }
674
675 pub fn check_speech(&self) -> Result<(), String> {
682 let id = &self.id;
683 if !self.speak {
684 return if self.speech.is_unknown() { Ok(()) } else { Err(format!("{id}: speech settings need the speak role")) };
685 }
686 if self.embedding || self.transcribe {
687 return Err(format!("{id}: a speaking model can't also be an embedding or transcription model"));
688 }
689 match self.engine {
690 EngineKind::Llamacpp if !self.has_projector() => {
691 return Err(format!("{id}: llama.cpp speaks only with the model's projector (mmproj)"));
692 }
693 EngineKind::Llamacpp | EngineKind::VllmOmni => {}
694 other => return Err(format!("{id}: {} has no speech engine; use llama.cpp or vLLM-Omni", other.name())),
695 }
696 if self.engine == EngineKind::VllmOmni && self.extra_args.iter().any(|a| a.split('=').next() == Some("--allowed-local-media-path")) {
697 return Err(format!("{id}: vLLM-Omni must not read local media (--allowed-local-media-path); reference clips travel inline"));
698 }
699 if !self.speech.is_unknown()
700 && let Some(cataloged) = self.cataloged_speech()
701 {
702 cataloged.to_agent().narrowed_by(&self.speech).map_err(|e| format!("{id}: speech settings widen the model's: {e}"))?;
703 }
704 Ok(())
705 }
706
707 pub fn with_transcribe(mut self, on: bool) -> Self {
709 self.transcribe = on;
710 self
711 }
712
713 pub fn purpose(&self) -> Purpose {
716 self.capabilities().purpose(self.embedding)
717 }
718
719 pub fn with_limits(mut self, limits: MediaLimits) -> Self {
721 self.limits = limits;
722 self
723 }
724
725 pub fn with_mmproj(mut self, path: impl Into<String>) -> Self {
727 self.mmproj = Some(path.into());
728 self
729 }
730
731 pub fn with_lora_slots(mut self, slots: u32) -> Self {
733 self.lora_slots = Some(slots);
734 self
735 }
736
737 pub fn runtime_lora(&self) -> bool {
740 self.engine == EngineKind::Vllm && self.wrap.is_none() && (!self.adapters.is_empty() || self.lora_slots.is_some_and(|n| n > 0))
741 }
742
743 pub fn with_adapters(mut self, adapters: Vec<LoraAdapter>) -> Self {
744 self.adapters = adapters;
745 self
746 }
747
748 pub fn served_ids(&self) -> Vec<String> {
750 std::iter::once(self.id.clone()).chain(self.adapters.iter().map(|a| a.id.clone())).collect()
751 }
752
753 pub fn check_adapters(&self) -> Result<(), String> {
760 if self.adapters.is_empty() {
761 return Ok(());
762 }
763 let id = &self.id;
764 if self.wrap.is_some() {
765 return Err(format!("{id}: a wrapped server can't take adapters from this node"));
766 }
767 if self.embedding {
768 return Err(format!("{id}: embedding models take no adapters"));
769 }
770 if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::Vllm) {
771 return Err(format!("{id}: {} serves no adapters here; use llama.cpp or vLLM", self.engine.name()));
772 }
773 let mut seen = std::collections::HashSet::new();
774 for a in &self.adapters {
775 if a.id.trim().is_empty() {
776 return Err(format!("{id}: an adapter needs an id"));
777 }
778 if a.id == *id {
779 return Err(format!("{id}: adapter id {} is the base model's", a.id));
780 }
781 if !seen.insert(a.id.as_str()) {
782 return Err(format!("{id}: adapter id {} is used twice", a.id));
783 }
784 if a.scale.is_some_and(|s| !s.is_finite()) {
785 return Err(format!("{}: the scale must be a finite number", a.id));
786 }
787 }
788 match self.engine {
789 EngineKind::Llamacpp => {
790 let header = |path: &str| -> Result<weirdnet_model::gguf::GgufHeader, String> {
791 let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
792 weirdnet_model::gguf::read_header(std::io::BufReader::new(f)).map_err(|e| format!("{path}: {e}"))
793 };
794 let base = header(&self.source)?;
795 if base.kind.is_adapter() {
796 return Err(format!("{id}: {} is an adapter, not a base model", self.source));
797 }
798 for a in &self.adapters {
799 if a.path.contains(',') {
800 return Err(format!("{}: llama.cpp can't take a path with a comma ({})", a.id, a.path));
801 }
802 let h = header(&a.path)?;
803 if !h.kind.is_lora() {
804 return Err(format!("{}: {} is not a LoRA adapter GGUF", a.id, a.path));
805 }
806 if h.architecture != base.architecture {
807 return Err(format!("{}: adapter architecture {} doesn't match the base's {}", a.id, h.architecture, base.architecture));
808 }
809 }
810 }
811 _ => {
812 for a in &self.adapters {
813 let p = Path::new(&a.path);
814 if p.is_dir() {
815 let config: serde_json::Value = std::fs::read(p.join("adapter_config.json"))
816 .ok()
817 .and_then(|b| serde_json::from_slice(&b).ok())
818 .ok_or_else(|| format!("{}: {} has no readable adapter_config.json", a.id, a.path))?;
819 if !config["peft_type"].as_str().unwrap_or("LORA").eq_ignore_ascii_case("lora") {
820 return Err(format!("{}: {} is not a LoRA adapter", a.id, a.path));
821 }
822 } else if p.exists() {
823 return Err(format!("{}: vLLM takes a PEFT directory, not the file {}", a.id, a.path));
824 } else if weirdnet_model::hf::check_repo(&a.path).is_err() {
825 return Err(format!("{}: {} is neither a directory nor a Hub id", a.id, a.path));
826 }
827 }
828 }
829 }
830 Ok(())
831 }
832
833 pub fn capabilities(&self) -> Capabilities {
850 let own = if self.embedding {
851 Capabilities::embeddings()
852 } else if self.speak {
853 let speaks = match self.engine {
854 EngineKind::Llamacpp => self.has_projector(),
855 EngineKind::VllmOmni => true,
856 _ => false,
857 };
858 Capabilities::default().with_speak(speaks)
859 } else {
860 let media = self.engine == EngineKind::Llamacpp && self.has_projector();
861 let transcribe = self.transcribe && (media || self.engine == EngineKind::Vllm);
862 let video = self.video && self.engine == EngineKind::Vllm;
863 Capabilities::text().with_vision(media || video).with_audio(media).with_transcribe(transcribe).with_video(video)
865 };
866 own.with_limits(self.limits).intersect(self.engine.capabilities())
867 }
868
869 fn has_projector(&self) -> bool {
870 self.mmproj.is_some() || self.extra_args.iter().any(|a| matches!(a.split('=').next(), Some("--mmproj" | "-mm" | "--mmproj-url" | "-mmu")))
871 }
872}
873
874pub fn find_in_path(name: &str) -> Option<PathBuf> {
876 let path = std::env::var_os("PATH")?;
877 std::env::split_paths(&path).map(|d| d.join(name)).find(|p| is_executable(p))
878}
879
880fn is_executable(p: &Path) -> bool {
881 #[cfg(unix)]
882 {
883 use std::os::unix::fs::PermissionsExt;
884 std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
885 }
886 #[cfg(not(unix))]
887 {
888 p.is_file()
889 }
890}
891
892#[cfg(test)]
893pub(crate) mod tests {
894 use super::*;
895
896 fn args(cmd: &Command) -> Vec<String> {
897 cmd.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect()
898 }
899
900 #[test]
901 fn llama_args() {
902 let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/m/q.gguf");
903 m.context = Some(8192);
904 m.slots = Some(2);
905 let cmd = EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k");
906 let a = args(&cmd);
907 assert!(a.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
908 assert!(a.windows(2).any(|w| w == ["--port", "4321"]));
909 assert!(a.windows(2).any(|w| w == ["--alias", "qwen3-8b"]));
910 assert!(a.windows(2).any(|w| w == ["--parallel", "2"]));
911 assert!(!a.iter().any(|x| x == "k"), "the key stays out of argv");
912 }
913
914 #[test]
915 fn a_projector_goes_on_the_command_and_into_capabilities() {
916 let m = ModelLaunch::new("v", EngineKind::Llamacpp, "/m/v.gguf");
917 assert!(!m.capabilities().vision);
918 let m = m.with_mmproj("/m/mmproj.gguf");
919 let a = args(&EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k"));
920 assert!(a.windows(2).any(|w| w == ["--mmproj", "/m/mmproj.gguf"]));
921 assert!(m.capabilities().vision);
922 let back: ModelLaunch = serde_json::from_value(serde_json::to_value(&m).unwrap()).unwrap();
923 assert_eq!(back.mmproj.as_deref(), Some("/m/mmproj.gguf"));
924 }
925
926 pub(crate) fn gguf(kv: &[(&str, serde_json::Value)]) -> Vec<u8> {
928 let mut out = b"GGUF".to_vec();
929 out.extend(3u32.to_le_bytes());
930 out.extend(0u64.to_le_bytes());
931 out.extend((kv.len() as u64).to_le_bytes());
932 let s = |out: &mut Vec<u8>, s: &str| {
933 out.extend((s.len() as u64).to_le_bytes());
934 out.extend(s.as_bytes());
935 };
936 for (k, v) in kv {
937 s(&mut out, k);
938 match v {
939 serde_json::Value::String(t) => {
940 out.extend(8u32.to_le_bytes());
941 s(&mut out, t);
942 }
943 serde_json::Value::Number(n) if n.is_u64() => {
944 out.extend(4u32.to_le_bytes());
945 out.extend((n.as_u64().unwrap() as u32).to_le_bytes());
946 }
947 serde_json::Value::Number(n) => {
948 out.extend(6u32.to_le_bytes());
949 out.extend((n.as_f64().unwrap() as f32).to_le_bytes());
950 }
951 serde_json::Value::Bool(b) => {
952 out.extend(7u32.to_le_bytes());
953 out.push(*b as u8);
954 }
955 _ => unreachable!(),
956 }
957 }
958 out
959 }
960
961 pub(crate) fn base_gguf(arch: &str) -> Vec<u8> {
962 gguf(&[("general.architecture", arch.into()), (format!("{arch}.block_count").as_str(), 1.into())])
963 }
964
965 pub(crate) fn lora_gguf(arch: &str) -> Vec<u8> {
966 gguf(&[
967 ("general.architecture", arch.into()),
968 ("general.type", "adapter".into()),
969 ("adapter.type", "lora".into()),
970 ("adapter.lora.alpha", 16.5.into()),
971 ])
972 }
973
974 #[test]
975 fn llama_adapter_args_and_checks() {
976 let tmp = tempfile::tempdir().unwrap();
977 let w = |name: &str, b: Vec<u8>| {
978 let p = tmp.path().join(name);
979 std::fs::write(&p, b).unwrap();
980 p.display().to_string()
981 };
982 let base = w("base.gguf", base_gguf("qwen3"));
983 let (a, b) = (w("a.gguf", lora_gguf("qwen3")), w("b.gguf", lora_gguf("qwen3")));
984 let m = ModelLaunch::new("qwen", EngineKind::Llamacpp, &base)
985 .with_adapters(vec![LoraAdapter::new("tune-a", &a).with_scale(0.5), LoraAdapter::new("tune-b", &b)]);
986 assert_eq!(m.served_ids(), ["qwen", "tune-a", "tune-b"]);
987 m.check_adapters().unwrap();
988 let argv = args(&EngineConfig::llamacpp("llama-server").command(&m, 1, "k"));
989 let loras: Vec<&String> = argv.windows(2).filter(|w| w[0] == "--lora").map(|w| &w[1]).collect();
990 assert_eq!(loras, [&a, &b], "one --lora per adapter, in order");
991 assert!(argv.iter().any(|x| x == "--lora-init-without-apply"));
992 assert!(
993 !args(&EngineConfig::llamacpp("l").command(&ModelLaunch::new("x", EngineKind::Llamacpp, &base), 1, "k"))
994 .iter()
995 .any(|x| x.starts_with("--lora"))
996 );
997
998 let bad =
999 |adapters: Vec<LoraAdapter>| ModelLaunch::new("qwen", EngineKind::Llamacpp, &base).with_adapters(adapters).check_adapters().unwrap_err();
1000 assert!(bad(vec![LoraAdapter::new("qwen", &a)]).contains("base model's"));
1001 assert!(bad(vec![LoraAdapter::new("t", &a), LoraAdapter::new("t", &b)]).contains("twice"));
1002 assert!(bad(vec![LoraAdapter::new("t", &a).with_scale(f32::NAN)]).contains("finite"));
1003 assert!(bad(vec![LoraAdapter::new("t", &base)]).contains("not a LoRA"));
1004 assert!(bad(vec![LoraAdapter::new("t", w("llama.gguf", lora_gguf("llama")))]).contains("architecture"));
1005 assert!(bad(vec![LoraAdapter::new("t", tmp.path().join("missing.gguf").display().to_string())]).contains("missing.gguf"));
1006 assert!(bad(vec![LoraAdapter::new("t", w("a,b.gguf", lora_gguf("qwen3")))]).contains("comma"));
1007 let mut emb = m.clone();
1008 emb.embedding = true;
1009 assert!(emb.check_adapters().unwrap_err().contains("embedding"));
1010 let mut wrapped = m.clone();
1011 wrapped.wrap = Some(Wrap { url: "http://127.0.0.1:1".into(), api_key: None });
1012 assert!(wrapped.check_adapters().unwrap_err().contains("wrapped"));
1013 let mlx = ModelLaunch::new("m", EngineKind::Mlx, &base).with_adapters(vec![LoraAdapter::new("t", &a)]);
1014 assert!(mlx.check_adapters().unwrap_err().contains("mlx"));
1015 let json = serde_json::to_string(&ModelLaunch::new("x", EngineKind::Llamacpp, "/m")).unwrap();
1016 assert!(!json.contains("adapters"), "no adapters, same JSON as before");
1017 }
1018
1019 #[test]
1020 fn vllm_adapter_args_and_checks() {
1021 let tmp = tempfile::tempdir().unwrap();
1022 let peft = tmp.path().join("tune");
1023 std::fs::create_dir(&peft).unwrap();
1024 std::fs::write(peft.join("adapter_config.json"), br#"{"peft_type":"LORA","r":8}"#).unwrap();
1025 let peft = peft.display().to_string();
1026 let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B")
1027 .with_adapters(vec![LoraAdapter::new("tune", &peft), LoraAdapter::new("hub", "owner/some-lora")]);
1028 m.check_adapters().unwrap();
1029 let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
1030 assert_eq!(a.iter().filter(|x| *x == "--lora-modules").count(), 1, "vLLM keeps only the last --lora-modules");
1031 let at = a.iter().position(|x| x == "--lora-modules").unwrap();
1032 let mods: Vec<serde_json::Value> = a[at + 1..at + 3].iter().map(|j| serde_json::from_str(j).unwrap()).collect();
1033 assert_eq!(mods[0], serde_json::json!({"name": "tune", "path": peft, "base_model_name": "big"}));
1034 assert_eq!(mods[1]["name"], "hub");
1035 assert!(a.iter().any(|x| x == "--enable-lora"));
1036 assert!(a.windows(2).any(|w| w == ["--max-loras", "2"]));
1037 let cmd = EngineConfig::vllm("vllm").command(&m, 9000, "k");
1038 let env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
1039 assert!(env.iter().any(|(k, v)| k == "VLLM_ALLOW_RUNTIME_LORA_UPDATING" && v.as_deref() == Some("True".as_ref())));
1040 let empty = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B").with_lora_slots(4);
1042 assert!(empty.runtime_lora());
1043 let a = args(&EngineConfig::vllm("vllm").command(&empty, 9000, "k"));
1044 assert!(a.iter().any(|x| x == "--enable-lora") && !a.iter().any(|x| x == "--lora-modules"));
1045 assert!(a.windows(2).any(|w| w == ["--max-loras", "4"]));
1046 let plain = args(&EngineConfig::vllm("vllm").command(&ModelLaunch::new("big", EngineKind::Vllm, "Q/Q"), 9000, "k"));
1047 assert!(!plain.iter().any(|x| x == "--enable-lora"));
1048 assert!(!ModelLaunch::new("q", EngineKind::Llamacpp, "/q.gguf").with_lora_slots(2).runtime_lora(), "llama.cpp ignores it");
1049 let file = tmp.path().join("x.gguf");
1050 std::fs::write(&file, lora_gguf("qwen3")).unwrap();
1051 let bad = |path: String| {
1052 ModelLaunch::new("big", EngineKind::Vllm, "Q/Q").with_adapters(vec![LoraAdapter::new("t", path)]).check_adapters().unwrap_err()
1053 };
1054 assert!(bad(file.display().to_string()).contains("PEFT directory"));
1055 assert!(bad("/no/such/dir".into()).contains("Hub id"));
1056 }
1057
1058 #[test]
1059 fn wrap_is_loopback_only() {
1060 let w = |u: &str| Wrap { url: u.into(), api_key: None }.check();
1061 assert!(w("http://127.0.0.1:8000").is_ok());
1062 assert!(w("http://localhost:8000/").is_ok());
1063 assert!(w("http://[::1]:8000").is_ok());
1064 assert!(w("https://127.0.0.1:8000").is_err());
1065 assert!(w("http://10.0.0.2:8000").is_err());
1066 assert!(w("http://127.0.0.1.evil:8000").is_err());
1067 assert_eq!(Wrap { url: "http://127.0.0.1:8000/v1/".into(), api_key: None }.base(), "http://127.0.0.1:8000");
1068 }
1069
1070 fn envs(cmd: &Command) -> Vec<(String, Option<String>)> {
1071 cmd.as_std().get_envs().map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned()))).collect()
1072 }
1073
1074 #[test]
1075 fn a_launch_carries_its_own_environment() {
1076 let plain = ModelLaunch::new("asr", EngineKind::Vllm, "Qwen/Qwen3-ASR-1.7B");
1077 assert!(plain.env.is_empty());
1078 assert_eq!(plain.clone().with_env("A", "1").env.len(), 1);
1079 let set = envs(&EngineConfig::vllm("vllm").command(&plain, 9000, "k"));
1080 assert_eq!(set, vec![("VLLM_API_KEY".to_string(), Some("k".to_string()))], "only what the node sets");
1081 assert!(!serde_json::to_string(&plain).unwrap().contains("env"), "left out when empty");
1082
1083 let asr = plain.clone().with_env("VLLM_USE_RUST_FRONTEND", "0").with_envs([("HF_HUB_OFFLINE", "1"), ("VLLM_USE_RUST_FRONTEND", "no")]);
1084 assert_eq!(asr.env.get("VLLM_USE_RUST_FRONTEND"), Some("no"), "a later value replaces an earlier one");
1085 assert_eq!(asr.env.iter().collect::<Vec<_>>(), [("HF_HUB_OFFLINE", "1"), ("VLLM_USE_RUST_FRONTEND", "no")]);
1086 let asr = asr.with_env("VLLM_USE_RUST_FRONTEND", "0");
1087 for (engine, config) in [
1088 (EngineKind::Vllm, EngineConfig::vllm("vllm")),
1089 (EngineKind::VllmOmni, EngineConfig::vllm_omni("vllm")),
1090 (EngineKind::Llamacpp, EngineConfig::llamacpp("llama-server")),
1091 (EngineKind::Mlx, EngineConfig::mlx("mlx_lm.server")),
1092 ] {
1093 let mut m = asr.clone();
1094 m.engine = engine;
1095 let set = envs(&config.command(&m, 9000, "k"));
1096 assert!(set.contains(&("VLLM_USE_RUST_FRONTEND".to_string(), Some("0".to_string()))), "{engine:?}: {set:?}");
1097 assert!(set.contains(&("HF_HUB_OFFLINE".to_string(), Some("1".to_string()))), "{engine:?}");
1098 let other = envs(&config.command(&ModelLaunch::new("o", engine, "x"), 9000, "k"));
1100 assert!(other.iter().all(|(k, _)| k != "VLLM_USE_RUST_FRONTEND" && k != "HF_HUB_OFFLINE"), "{engine:?}: {other:?}");
1101 }
1102
1103 let back: ModelLaunch = serde_json::from_str(&serde_json::to_string(&asr).unwrap()).unwrap();
1105 assert_eq!(back, asr);
1106 let old: ModelLaunch = serde_json::from_str(&serde_json::to_string(&plain).unwrap()).unwrap();
1107 assert!(old.env.is_empty());
1108 let secret = plain.with_env("HF_TOKEN", "hf_secret_value");
1109 let dbg = format!("{secret:?}");
1110 assert!(dbg.contains("HF_TOKEN") && !dbg.contains("hf_secret_value"), "{dbg}");
1111 }
1112
1113 #[test]
1114 fn launch_environment_checks() {
1115 let base = ModelLaunch::new("m", EngineKind::Vllm, "x");
1116 assert!(base.check_env().is_ok());
1117 assert!(base.clone().with_env("VLLM_USE_RUST_FRONTEND", "0").check_env().is_ok());
1118 for name in ["", "A=B", "A\0B"] {
1119 assert!(base.clone().with_env(name, "1").check_env().unwrap_err().contains("not valid"), "{name:?}");
1120 }
1121 assert!(base.clone().with_env("A", "x\0y").check_env().unwrap_err().contains("NUL"));
1122 for key in ["LLAMA_API_KEY", "VLLM_API_KEY"] {
1123 assert!(base.clone().with_env(key, "x").check_env().unwrap_err().contains("set by the node"), "{key}");
1124 }
1125 let cmd = EngineConfig::vllm("vllm").command(&base.clone().with_env("VLLM_API_KEY", "mine"), 1, "node");
1127 let key = envs(&cmd).into_iter().rev().find(|(k, _)| k == "VLLM_API_KEY").unwrap();
1128 assert_eq!(key.1.as_deref(), Some("node"));
1129 }
1130
1131 #[test]
1132 fn vllm_args() {
1133 let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B");
1134 let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
1135 assert_eq!(&a[..2], ["serve", "Qwen/Qwen3-8B"]);
1136 assert!(a.windows(2).any(|w| w == ["--served-model-name", "big"]));
1137 }
1138
1139 #[test]
1140 fn mlx_args() {
1141 let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Mlx, "/m/mlx/Qwen3-8B-4bit");
1142 m.context = Some(4096);
1143 let cmd = EngineConfig::mlx("/v/bin/mlx_lm.server").command(&m, 9, "k");
1144 assert_eq!(args(&cmd), ["--model", "/m/mlx/Qwen3-8B-4bit", "--host", "127.0.0.1", "--port", "9", "--max-tokens", "4096"]);
1145 assert!(cmd.as_std().get_envs().all(|(_, v)| v != Some(std::ffi::OsStr::new("k"))), "MLX-LM gets no key");
1146 m.context = None;
1147 let a = args(&EngineConfig::mlx("mlx_lm.server").command(&m, 9, "k"));
1148 assert_eq!(a.last().map(String::as_str), Some("32768"));
1149 assert_eq!(serde_json::to_string(&EngineKind::Mlx).unwrap(), "\"mlx\"");
1150 }
1151
1152 #[test]
1153 fn capabilities_as_modalities() {
1154 let media = Capabilities::text().with_vision(true).with_audio(true);
1155 assert_eq!(media.inputs(), Modalities::new(true, true));
1156 assert_eq!(Capabilities::text().lacking(Modalities::VISION), Some("images"));
1157 assert_eq!(Capabilities::text().with_vision(true).lacking(Modalities::new(true, true)), Some("audio"));
1158 assert_eq!(media.lacking(Modalities::AUDIO), None);
1159 assert_eq!(
1160 ModelLaunch::new("x", EngineKind::Mlx, "/m/x").capabilities().lacking(Modalities::VISION),
1161 Some("images"),
1162 "MLX never takes images"
1163 );
1164 }
1165
1166 #[test]
1167 fn capabilities() {
1168 let mut m = ModelLaunch::new("x", EngineKind::Mlx, "/m/x");
1169 assert_eq!(m.capabilities(), Capabilities::text());
1170 m.extra_args = vec!["--mmproj".into(), "/p".into()];
1171 assert!(!m.capabilities().vision, "MLX-LM never takes images");
1172 m.embedding = true;
1173 assert_eq!(m.capabilities(), Capabilities::default(), "MLX-LM serves no embeddings");
1174
1175 let mut l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
1176 assert_eq!(l.capabilities(), Capabilities::text());
1177 l.extra_args = vec!["--mmproj=/p/mm.gguf".into()];
1178 let c = l.capabilities();
1179 assert!(c.chat && c.vision && c.audio && !c.embeddings);
1180 l.embedding = true;
1181 assert_eq!(l.capabilities(), Capabilities::embeddings());
1182
1183 let v = ModelLaunch::new("v", EngineKind::Vllm, "Qwen/Qwen3-8B");
1184 assert_eq!(v.capabilities(), Capabilities::text());
1185 assert!(!EngineKind::Mlx.capabilities().embeddings && EngineKind::Llamacpp.capabilities().vision);
1186 }
1187
1188 fn limits() -> MediaLimits {
1189 MediaLimits::new().with_max_images(4).with_image_tokens(256).with_image_edge(896).with_audio_max_seconds(30).with_max_request_bytes(16 << 20)
1190 }
1191
1192 #[test]
1193 fn limits_reach_capabilities_and_catalog_entries() {
1194 assert!(Capabilities::text().limits.is_unknown());
1195 let l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf").with_mmproj("/p/mm.gguf").with_limits(limits());
1196 let c = l.capabilities();
1197 assert_eq!(c.limits, limits(), "the operator's limits survive the engine's (which knows none)");
1198 assert!(c.vision && c.audio);
1199 let both = c.intersect(Capabilities::text().with_vision(true).with_limits(MediaLimits::new().with_max_images(2)));
1200 assert_eq!((both.limits.max_images, both.limits.image_tokens), (Some(2), Some(256)), "stricter wins, one-sided kept");
1201 use weirdnet_agent::remote::catalog::{ModelState as CatalogState, Purpose};
1202 let entry = c.apply_to(CatalogModel::new("g", Purpose::Chat, CatalogState::Warm).with_replicas(1));
1203 assert_eq!((entry.inputs, entry.limits, entry.replicas), (Modalities::new(true, true), limits(), 1));
1204 let wire: CatalogModel = serde_json::from_str(&serde_json::to_string(&entry).unwrap()).unwrap();
1206 assert_eq!(wire.limits, limits());
1207 }
1208
1209 #[test]
1210 fn transcription_role_and_purpose() {
1211 use weirdnet_agent::remote::catalog::Purpose;
1212 let vox = ModelLaunch::new("vox", EngineKind::Llamacpp, "/m/v.gguf").with_mmproj("/m/mm.gguf").with_transcribe(true);
1213 assert!(vox.capabilities().transcribe && vox.capabilities().audio);
1214 assert_eq!(vox.purpose(), Purpose::Transcribe);
1215 let no_projector = ModelLaunch::new("v", EngineKind::Llamacpp, "/m/v.gguf").with_transcribe(true);
1216 assert!(!no_projector.capabilities().transcribe, "llama-server takes no audio without a projector");
1217 assert_eq!(no_projector.purpose(), Purpose::Chat);
1218 let mut via_args = no_projector.clone();
1219 via_args.extra_args = vec!["-mm".into(), "/m/mm.gguf".into()];
1220 assert!(via_args.capabilities().transcribe);
1221 let whisper = ModelLaunch::new("w", EngineKind::Vllm, "openai/whisper-large-v3").with_transcribe(true);
1222 assert!(whisper.capabilities().transcribe && !whisper.capabilities().audio);
1223 assert!(!ModelLaunch::new("m", EngineKind::Mlx, "/m").with_transcribe(true).capabilities().transcribe);
1224 let mut emb = vox.clone();
1225 emb.embedding = true;
1226 assert_eq!((emb.capabilities().transcribe, emb.purpose()), (false, Purpose::Embedding));
1227 assert_eq!(ModelLaunch::new("c", EngineKind::Llamacpp, "/m/c.gguf").purpose(), Purpose::Chat);
1228 let both = vox.capabilities().intersect(Capabilities::text().with_audio(true));
1229 assert!(!both.transcribe, "both sides must transcribe");
1230
1231 let json = serde_json::to_string(&Capabilities::text()).unwrap();
1233 assert!(!json.contains("transcribe"));
1234 let back: Capabilities = serde_json::from_str(&serde_json::to_string(&vox.capabilities()).unwrap()).unwrap();
1235 assert!(back.transcribe);
1236 let cbor = weirdnet_agent::remote::to_cbor(&vox.capabilities()).unwrap();
1237 assert!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap().transcribe);
1238 assert!(!serde_json::to_string(&no_projector.clone().with_transcribe(false)).unwrap().contains("transcribe"));
1239 let old: ModelLaunch = serde_json::from_str(&serde_json::to_string(&ModelLaunch::new("o", EngineKind::Llamacpp, "/o")).unwrap()).unwrap();
1240 assert!(!old.transcribe);
1241 let l: ModelLaunch = serde_json::from_value(serde_json::to_value(&whisper).unwrap()).unwrap();
1242 assert!(l.transcribe);
1243 }
1244
1245 #[test]
1246 fn vllm_omni_is_its_own_engine() {
1247 assert_eq!(serde_json::to_string(&EngineKind::VllmOmni).unwrap(), r#""vllm-omni""#);
1248 assert_eq!(serde_json::from_str::<EngineKind>(r#""vllm-omni""#).unwrap(), EngineKind::VllmOmni);
1249 for k in [EngineKind::Llamacpp, EngineKind::Vllm, EngineKind::Mlx, EngineKind::VllmOmni] {
1250 assert_eq!(EngineKind::parse(k.name()), Some(k));
1251 assert!(!k.install_hint().is_empty());
1252 }
1253 assert_eq!(
1254 (EngineKind::parse("omni"), EngineKind::parse("llama.cpp"), EngineKind::parse("x")),
1255 (Some(EngineKind::VllmOmni), Some(EngineKind::Llamacpp), None)
1256 );
1257 assert!(EngineKind::VllmOmni.supported("linux", "x86_64") && !EngineKind::VllmOmni.supported("macos", "aarch64"));
1258 assert!(EngineKind::Llamacpp.supported("windows", "x86_64") && !EngineKind::Mlx.supported("linux", "x86_64"));
1259 assert_eq!((EngineKind::VllmOmni.program(), EngineKind::Llamacpp.program()), ("vllm", "llama-server"));
1260 let caps = EngineKind::VllmOmni.capabilities();
1261 assert!(caps.speak && caps.chat && !caps.video && !caps.embeddings);
1262 assert!(EngineKind::Llamacpp.capabilities().speak && !EngineKind::Llamacpp.capabilities().video);
1263 assert!(EngineKind::Vllm.capabilities().video && !EngineKind::Vllm.capabilities().speak);
1264
1265 let mut m = ModelLaunch::new("qwen3-tts-1.7b-customvoice", EngineKind::VllmOmni, "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice").with_speak(true);
1266 m.slots = Some(4);
1267 let a = args(&EngineConfig::vllm_omni("/venv/bin/vllm").command(&m, 4321, "k"));
1268 assert_eq!(&a[..3], ["serve", "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice", "--omni"]);
1269 assert!(a.windows(2).any(|w| w == ["--served-model-name", "qwen3-tts-1.7b-customvoice"]));
1270 assert!(a.windows(2).any(|w| w == ["--max-num-seqs", "4"]));
1271 assert!(!a.iter().any(|x| x == "k" || x.starts_with("--allowed-local-media-path")), "no key in argv, no local media");
1272 assert_eq!(EngineConfig::vllm_omni("/v").ready_timeout, Duration::from_secs(1200));
1273 }
1274
1275 #[test]
1276 fn speakers_speak_and_nothing_else() {
1277 let kokoro = ModelLaunch::new("kokoro-82m", EngineKind::Llamacpp, "/m/kokoro.gguf").with_speak(true);
1278 assert_eq!(kokoro.capabilities(), Capabilities::default(), "no projector: llama.cpp can't speak");
1279 assert!(kokoro.check_speech().unwrap_err().contains("projector"));
1280 let kokoro = kokoro.with_mmproj("/m/mmproj-kokoro.gguf");
1281 assert_eq!(kokoro.capabilities(), Capabilities::default().with_speak(true));
1282 assert_eq!(kokoro.purpose(), Purpose::Speak);
1283 assert!(kokoro.check_speech().is_ok());
1284 let omni = ModelLaunch::new("q", EngineKind::VllmOmni, "Qwen/X").with_speak(true);
1285 assert_eq!((omni.capabilities().speak, omni.purpose()), (true, Purpose::Speak));
1286 for engine in [EngineKind::Vllm, EngineKind::Mlx] {
1287 let m = ModelLaunch::new("s", engine, "/m/s").with_speak(true);
1288 assert!(!m.capabilities().speak && m.check_speech().unwrap_err().contains("no speech engine"), "{engine:?}");
1289 }
1290 let mut both = omni.clone().with_transcribe(true);
1291 assert!(both.check_speech().is_err());
1292 both.transcribe = false;
1293 both.extra_args = vec!["--allowed-local-media-path=/".into()];
1294 assert!(both.check_speech().unwrap_err().contains("local media"));
1295 let p = SpeechProfile::new().with_max_input_chars(100);
1297 assert!(ModelLaunch::new("c", EngineKind::Llamacpp, "/m/c.gguf").with_speech(p.clone()).check_speech().is_err());
1298 assert!(kokoro.clone().with_speech(p.clone().with_presets(vec!["af_heart".into()])).check_speech().is_ok());
1299 let e = kokoro.clone().with_speech(SpeechProfile::new().with_presets(vec!["alloy".into()])).check_speech().unwrap_err();
1300 assert!(e.contains("widen") && e.contains("alloy"), "{e}");
1301 assert!(kokoro.clone().with_speech(SpeechProfile::new().with_design(true)).check_speech().is_err());
1302
1303 assert!(kokoro.cataloged_speech().unwrap().raw);
1305 let by_repo = ModelLaunch::new("tts", EngineKind::VllmOmni, "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign");
1306 let entry = weirdnet_model::hw::find(weirdnet_model::hw::QWEN3_TTS_1_7B_VOICEDESIGN).unwrap();
1307 assert_eq!(by_repo.cataloged_speech().is_some(), entry.spec.repo.eq_ignore_ascii_case("Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign"));
1308 let by_repo = ModelLaunch::new("tts", EngineKind::VllmOmni, entry.spec.repo.clone());
1309 assert!(by_repo.cataloged_speech().unwrap().design);
1310 let gguf = weirdnet_model::hw::find(weirdnet_model::hw::VOXCPM2).unwrap();
1311 let by_file = ModelLaunch::new("vox", EngineKind::Llamacpp, format!("/models/{}", gguf.spec.file));
1312 assert!(by_file.cataloged_speech().unwrap().design);
1313 assert!(ModelLaunch::new("kokoro-82m", EngineKind::VllmOmni, "x/y").cataloged_speech().is_none(), "a GGUF entry is not vLLM-Omni's");
1314 assert!(ModelLaunch::new("kokoro-82m", EngineKind::Vllm, "x/y").cataloged_speech().is_none());
1315
1316 let json = serde_json::to_value(kokoro.clone().with_speech(p.clone())).unwrap();
1317 assert_eq!((json["speak"].as_bool(), json["speech"]["max_input_chars"].as_u64()), (Some(true), Some(100)));
1318 let back: ModelLaunch = serde_json::from_value(json).unwrap();
1319 assert_eq!(back.speech, p);
1320 }
1321
1322 #[test]
1323 fn video_is_vllms_on_the_operators_word() {
1324 let vl = ModelLaunch::new("vl", EngineKind::Vllm, "Qwen/Qwen2.5-VL-7B-Instruct");
1325 assert!(!vl.capabilities().video);
1326 let vl = vl.with_video(true);
1327 let caps = vl.capabilities();
1328 assert!(caps.video && caps.chat && caps.vision, "a video model takes images too");
1329 assert_eq!(caps.inputs(), Modalities::new(true, false).with_video(true));
1330 assert_eq!(caps.lacking(Modalities::VIDEO), None);
1331 assert_eq!(Capabilities::text().lacking(Modalities::VIDEO), Some("video"));
1332 assert!(!ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf").with_mmproj("/m/p.gguf").with_video(true).capabilities().video);
1333 assert!(!ModelLaunch::new("m", EngineKind::Mlx, "/m/m").with_video(true).capabilities().video);
1334 assert!(!caps.intersect(Capabilities::text()).video);
1335 let limits = MediaLimits::new().with_video_max_seconds(120).with_video_frames_per_minute(120);
1336 let entry = caps.with_limits(limits).apply_to(CatalogModel::new("vl", Purpose::Chat, weirdnet_agent::remote::catalog::ModelState::Warm));
1337 assert!(entry.inputs.video);
1338 assert_eq!((entry.limits.video_max_seconds, entry.limits.video_frame_rate()), (Some(120), Some(2.0)));
1339 let json = serde_json::to_string(&caps).unwrap();
1340 assert!(json.contains(r#""video":true"#) && !json.contains("speak"));
1341 assert_eq!(serde_json::from_str::<Capabilities>(&json).unwrap(), caps);
1342 let cbor = weirdnet_agent::remote::to_cbor(&caps).unwrap();
1343 assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap(), caps);
1344 }
1345
1346 #[test]
1347 fn records_without_limits_read_as_before() {
1348 let old = r#"{"chat":true,"embeddings":false,"vision":true,"audio":false}"#;
1349 let c: Capabilities = serde_json::from_str(old).unwrap();
1350 assert_eq!(c, Capabilities::text().with_vision(true));
1351 assert!(c.limits.is_unknown());
1352 assert_eq!(serde_json::to_string(&c).unwrap(), old, "no limits: the record looks as before");
1353 let with: Capabilities = serde_json::from_str(&serde_json::to_string(&c.with_limits(limits())).unwrap()).unwrap();
1354 assert_eq!(with.limits, limits());
1355 let cbor = weirdnet_agent::remote::to_cbor(&c.with_limits(limits())).unwrap();
1356 assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap(), c.with_limits(limits()));
1357 assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&weirdnet_agent::remote::to_cbor(&c).unwrap()).unwrap(), c);
1358 let launch = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
1359 let json = serde_json::to_string(&launch).unwrap();
1360 assert!(!json.contains("limits"));
1361 let back: ModelLaunch = serde_json::from_str(&json).unwrap();
1362 assert_eq!(back, launch);
1363 let with = launch.with_limits(limits());
1364 assert_eq!(serde_json::from_str::<ModelLaunch>(&serde_json::to_string(&with).unwrap()).unwrap(), with);
1365 }
1366}