1use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7use tokio::process::Command;
8use weirdnet_agent::remote::catalog::{CatalogModel, Purpose};
9use weirdnet_agent::speech::SpeechProfile;
10use weirdnet_agent::{MediaLimits, Modalities};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14#[non_exhaustive]
15pub enum EngineKind {
16 Llamacpp,
18 Vllm,
20 Mlx,
23 #[serde(rename = "vllm-omni")]
28 VllmOmni,
29}
30
31impl EngineKind {
32 pub fn name(self) -> &'static str {
33 match self {
34 EngineKind::Llamacpp => "llamacpp",
35 EngineKind::Vllm => "vllm",
36 EngineKind::Mlx => "mlx",
37 EngineKind::VllmOmni => "vllm-omni",
38 }
39 }
40
41 pub fn parse(name: &str) -> Option<Self> {
44 match name.trim().to_ascii_lowercase().as_str() {
45 "llamacpp" | "llama.cpp" | "llama-server" => Some(EngineKind::Llamacpp),
46 "vllm" => Some(EngineKind::Vllm),
47 "mlx" | "mlx-lm" => Some(EngineKind::Mlx),
48 "vllm-omni" | "vllm_omni" | "omni" => Some(EngineKind::VllmOmni),
49 _ => None,
50 }
51 }
52
53 pub fn capabilities(self) -> Capabilities {
57 match self {
58 EngineKind::Llamacpp => {
59 Capabilities { chat: true, embeddings: true, vision: true, audio: true, transcribe: true, speak: true, ..Capabilities::default() }
60 }
61 EngineKind::Vllm => {
62 Capabilities { chat: true, embeddings: true, vision: true, audio: true, transcribe: true, video: true, ..Capabilities::default() }
63 }
64 EngineKind::Mlx => Capabilities::text(),
65 EngineKind::VllmOmni => Capabilities { chat: true, speak: true, ..Capabilities::default() },
66 }
67 }
68
69 pub fn supported(self, os: &str, arch: &str) -> bool {
73 match self {
74 EngineKind::Llamacpp => true,
75 EngineKind::Vllm | EngineKind::VllmOmni => os == "linux",
76 EngineKind::Mlx => crate::mlx::supported(os, arch),
77 }
78 }
79
80 pub fn supported_here(self) -> bool {
83 self.supported(std::env::consts::OS, std::env::consts::ARCH)
84 }
85
86 pub fn program(self) -> &'static str {
90 match self {
91 EngineKind::Llamacpp => "llama-server",
92 EngineKind::Vllm | EngineKind::VllmOmni => "vllm",
93 EngineKind::Mlx => "mlx_lm.server",
94 }
95 }
96
97 pub fn install_hint(self) -> &'static str {
99 match self {
100 EngineKind::Llamacpp => "install llama.cpp (https://github.com/ggml-org/llama.cpp) and put `llama-server` on PATH",
101 EngineKind::Vllm => "install vLLM in a venv (`pip install vllm`; Linux, NVIDIA sm_80+ or supported ROCm) and put its `vllm` on PATH",
102 EngineKind::VllmOmni => {
103 "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`"
104 }
105 EngineKind::Mlx => "install MLX-LM into a venv (weirdnet_backends::mlx::install; macOS on Apple silicon)",
106 }
107 }
108}
109
110#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
115#[non_exhaustive]
116pub struct Capabilities {
117 pub chat: bool,
119 pub embeddings: bool,
121 pub vision: bool,
123 pub audio: bool,
125 #[serde(default, skip_serializing_if = "MediaLimits::is_unknown")]
130 pub limits: MediaLimits,
131 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
137 pub transcribe: bool,
138 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143 pub video: bool,
144 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
150 pub speak: bool,
151}
152
153impl Capabilities {
154 pub fn text() -> Self {
156 Self { chat: true, ..Self::default() }
157 }
158
159 pub fn embeddings() -> Self {
161 Self { embeddings: true, ..Self::default() }
162 }
163
164 pub fn with_vision(mut self, on: bool) -> Self {
165 self.vision = on;
166 self
167 }
168
169 pub fn with_audio(mut self, on: bool) -> Self {
170 self.audio = on;
171 self
172 }
173
174 pub fn with_limits(mut self, limits: MediaLimits) -> Self {
176 self.limits = limits;
177 self
178 }
179
180 pub fn with_transcribe(mut self, on: bool) -> Self {
182 self.transcribe = on;
183 self
184 }
185
186 pub fn with_video(mut self, on: bool) -> Self {
188 self.video = on;
189 self
190 }
191
192 pub fn with_speak(mut self, on: bool) -> Self {
194 self.speak = on;
195 self
196 }
197
198 pub fn apply_to(&self, entry: CatalogModel) -> CatalogModel {
201 entry.with_inputs(self.inputs()).with_limits(self.limits)
202 }
203
204 pub fn purpose(&self, embedding: bool) -> Purpose {
210 if embedding {
211 Purpose::Embedding
212 } else if self.speak {
213 Purpose::Speak
214 } else if self.transcribe {
215 Purpose::Transcribe
216 } else {
217 Purpose::Chat
218 }
219 }
220
221 pub fn inputs(&self) -> Modalities {
224 Modalities::new(self.vision, self.audio).with_video(self.video)
225 }
226
227 pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
229 self.inputs().lacking(needed)
230 }
231
232 pub fn intersect(self, other: Self) -> Self {
235 Self {
236 chat: self.chat && other.chat,
237 embeddings: self.embeddings && other.embeddings,
238 vision: self.vision && other.vision,
239 audio: self.audio && other.audio,
240 limits: self.limits.tightest(other.limits),
241 transcribe: self.transcribe && other.transcribe,
242 video: self.video && other.video,
243 speak: self.speak && other.speak,
244 }
245 }
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct EngineConfig {
251 pub kind: EngineKind,
252 pub program: PathBuf,
253 pub extra_args: Vec<String>,
255 pub ready_timeout: Duration,
256}
257
258impl EngineConfig {
259 pub fn llamacpp(program: impl Into<PathBuf>) -> Self {
260 Self { kind: EngineKind::Llamacpp, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(300) }
261 }
262
263 pub fn vllm(program: impl Into<PathBuf>) -> Self {
264 Self { kind: EngineKind::Vllm, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
265 }
266
267 pub fn vllm_omni(program: impl Into<PathBuf>) -> Self {
270 Self { kind: EngineKind::VllmOmni, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
271 }
272
273 pub async fn version(&self) -> Option<String> {
277 let mut cmd = Command::new(&self.program);
278 cmd.arg("--version").stdin(std::process::Stdio::null()).kill_on_drop(true);
279 let out = tokio::time::timeout(Duration::from_secs(30), cmd.output()).await.ok()?.ok()?;
280 let text = [out.stdout, out.stderr].iter().map(|b| String::from_utf8_lossy(b).into_owned()).collect::<Vec<_>>().join("\n");
281 text.lines().map(str::trim).find(|l| !l.is_empty()).map(str::to_string)
282 }
283
284 pub fn mlx(program: impl Into<PathBuf>) -> Self {
287 Self { kind: EngineKind::Mlx, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
288 }
289
290 pub fn command(&self, model: &ModelLaunch, port: u16, api_key: &str) -> Command {
296 let mut cmd = Command::new(&self.program);
297 match self.kind {
298 EngineKind::Llamacpp => {
299 cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--alias", &model.id, "--no-webui"]);
300 if let Some(ctx) = model.context {
301 cmd.args(["--ctx-size", &ctx.to_string()]);
302 }
303 if let Some(slots) = model.slots {
304 cmd.args(["--parallel", &slots.to_string()]);
305 }
306 if let Some(ngl) = model.gpu_layers {
307 cmd.args(["--n-gpu-layers", &ngl.to_string()]);
308 }
309 if model.embedding {
310 cmd.arg("--embedding");
311 }
312 if let Some(mmproj) = &model.mmproj {
313 cmd.args(["--mmproj", mmproj]);
314 }
315 for a in &model.adapters {
319 cmd.args(["--lora", &a.path]);
320 }
321 if !model.adapters.is_empty() {
322 cmd.arg("--lora-init-without-apply");
323 }
324 cmd.env("LLAMA_API_KEY", api_key);
325 }
326 EngineKind::Vllm => {
327 cmd.args(["serve", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
328 if let Some(ctx) = model.context {
329 cmd.args(["--max-model-len", &ctx.to_string()]);
330 }
331 if let Some(slots) = model.slots {
332 cmd.args(["--max-num-seqs", &slots.to_string()]);
333 }
334 if model.runtime_lora() {
335 cmd.arg("--enable-lora");
336 if !model.adapters.is_empty() {
337 cmd.arg("--lora-modules");
339 for a in &model.adapters {
340 cmd.arg(serde_json::json!({"name": a.id, "path": a.path, "base_model_name": model.id}).to_string());
341 }
342 }
343 let max = (model.adapters.len() as u32).max(model.lora_slots.unwrap_or(0)).max(1);
344 cmd.args(["--max-loras", &max.to_string()]);
345 cmd.env("VLLM_ALLOW_RUNTIME_LORA_UPDATING", "True");
348 }
349 cmd.env("VLLM_API_KEY", api_key);
350 }
351 EngineKind::VllmOmni => {
352 cmd.args(["serve", &model.source, "--omni", "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
355 if let Some(ctx) = model.context {
356 cmd.args(["--max-model-len", &ctx.to_string()]);
357 }
358 if let Some(slots) = model.slots {
359 cmd.args(["--max-num-seqs", &slots.to_string()]);
360 }
361 cmd.env("VLLM_API_KEY", api_key);
362 }
363 EngineKind::Mlx => {
364 let max = model.context.unwrap_or(crate::mlx::DEFAULT_MAX_TOKENS).to_string();
367 cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--max-tokens", &max]);
368 }
369 }
370 cmd.args(&self.extra_args).args(&model.extra_args);
371 cmd
372 }
373}
374
375#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
377#[non_exhaustive]
378pub struct LoraAdapter {
379 pub id: String,
381 pub path: String,
383 #[serde(default, skip_serializing_if = "Option::is_none")]
385 pub scale: Option<f32>,
386}
387
388impl Eq for LoraAdapter {}
390
391impl LoraAdapter {
392 pub fn new(id: impl Into<String>, path: impl Into<String>) -> Self {
393 Self { id: id.into(), path: path.into(), scale: None }
394 }
395
396 pub fn with_scale(mut self, scale: f32) -> Self {
397 self.scale = Some(scale);
398 self
399 }
400
401 pub fn effective_scale(&self) -> f32 {
403 self.scale.unwrap_or(1.0)
404 }
405}
406
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
409#[non_exhaustive]
410pub struct ModelLaunch {
411 pub id: String,
413 pub engine: EngineKind,
414 pub source: String,
417 pub context: Option<u32>,
418 pub slots: Option<u32>,
420 pub gpu_layers: Option<i32>,
422 pub swap_group: Option<String>,
424 pub embedding: bool,
425 pub extra_args: Vec<String>,
426 #[serde(default, with = "opt_secs")]
428 pub idle_ttl: Option<Duration>,
429 #[serde(default)]
432 pub wrap: Option<Wrap>,
433 #[serde(default, skip_serializing_if = "Vec::is_empty")]
436 pub adapters: Vec<LoraAdapter>,
437 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub lora_slots: Option<u32>,
443 #[serde(default, skip_serializing_if = "Option::is_none")]
446 pub mmproj: Option<String>,
447 #[serde(default, skip_serializing_if = "MediaLimits::is_unknown")]
451 pub limits: MediaLimits,
452 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
457 pub transcribe: bool,
458 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
464 pub video: bool,
465 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
470 pub speak: bool,
471 #[serde(default, skip_serializing_if = "SpeechProfile::is_unknown")]
478 pub speech: SpeechProfile,
479}
480
481#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
483pub struct Wrap {
484 pub url: String,
486 #[serde(default, skip_serializing)]
488 pub api_key: Option<String>,
489}
490
491impl std::fmt::Debug for Wrap {
492 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493 f.debug_struct("Wrap").field("url", &self.url).field("api_key", &self.api_key.as_ref().map(|_| "<redacted>")).finish()
494 }
495}
496
497impl Wrap {
498 pub fn check(&self) -> Result<(), String> {
500 let rest = self.url.strip_prefix("http://").ok_or_else(|| format!("wrap url {} must start with http:// (loopback only)", self.url))?;
501 let host = match rest.strip_prefix('[') {
502 Some(v6) => v6.split(']').next().unwrap_or(""),
503 None => rest.split(['/', ':']).next().unwrap_or(""),
504 };
505 if matches!(host, "127.0.0.1" | "localhost" | "::1") { Ok(()) } else { Err(format!("wrap url {} is not loopback", self.url)) }
506 }
507
508 pub fn base(&self) -> String {
509 self.url.trim_end_matches('/').trim_end_matches("/v1").to_string()
510 }
511}
512
513mod opt_secs {
514 use std::time::Duration;
515
516 use serde::{Deserialize, Deserializer, Serializer};
517
518 pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
519 match d {
520 Some(d) => s.serialize_some(&d.as_secs()),
521 None => s.serialize_none(),
522 }
523 }
524
525 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
526 Ok(Option::<u64>::deserialize(d)?.map(Duration::from_secs))
527 }
528}
529
530impl ModelLaunch {
531 pub fn new(id: impl Into<String>, engine: EngineKind, source: impl Into<String>) -> Self {
532 Self {
533 id: id.into(),
534 engine,
535 source: source.into(),
536 context: None,
537 slots: None,
538 gpu_layers: None,
539 swap_group: None,
540 embedding: false,
541 extra_args: Vec::new(),
542 idle_ttl: None,
543 wrap: None,
544 adapters: Vec::new(),
545 lora_slots: None,
546 mmproj: None,
547 limits: MediaLimits::UNKNOWN,
548 transcribe: false,
549 video: false,
550 speak: false,
551 speech: SpeechProfile::default(),
552 }
553 }
554
555 pub fn with_video(mut self, on: bool) -> Self {
557 self.video = on;
558 self
559 }
560
561 pub fn with_speak(mut self, on: bool) -> Self {
563 self.speak = on;
564 self
565 }
566
567 pub fn with_speech(mut self, speech: SpeechProfile) -> Self {
569 self.speech = speech;
570 self
571 }
572
573 pub fn cataloged_speech(&self) -> Option<weirdnet_model::SpeechProfile> {
578 if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::VllmOmni) {
579 return None;
580 }
581 let gguf = self.engine == EngineKind::Llamacpp;
582 let name = |p: &str| Path::new(p).file_name().map(|n| n.to_string_lossy().to_ascii_lowercase());
583 let file = name(&self.source);
584 weirdnet_model::hw::by_purpose(weirdnet_model::hw::Purpose::Speak)
585 .into_iter()
586 .filter(|e| e.is_gguf() == gguf)
587 .find(|e| {
588 e.id() == self.id
589 || (!gguf && e.spec.repo.eq_ignore_ascii_case(self.source.trim()))
590 || (gguf && file.is_some() && name(&e.spec.file) == file)
591 })
592 .and_then(|e| e.speech())
593 }
594
595 pub fn check_speech(&self) -> Result<(), String> {
602 let id = &self.id;
603 if !self.speak {
604 return if self.speech.is_unknown() { Ok(()) } else { Err(format!("{id}: speech settings need the speak role")) };
605 }
606 if self.embedding || self.transcribe {
607 return Err(format!("{id}: a speaking model can't also be an embedding or transcription model"));
608 }
609 match self.engine {
610 EngineKind::Llamacpp if !self.has_projector() => {
611 return Err(format!("{id}: llama.cpp speaks only with the model's projector (mmproj)"));
612 }
613 EngineKind::Llamacpp | EngineKind::VllmOmni => {}
614 other => return Err(format!("{id}: {} has no speech engine; use llama.cpp or vLLM-Omni", other.name())),
615 }
616 if self.engine == EngineKind::VllmOmni && self.extra_args.iter().any(|a| a.split('=').next() == Some("--allowed-local-media-path")) {
617 return Err(format!("{id}: vLLM-Omni must not read local media (--allowed-local-media-path); reference clips travel inline"));
618 }
619 if !self.speech.is_unknown()
620 && let Some(cataloged) = self.cataloged_speech()
621 {
622 cataloged.to_agent().narrowed_by(&self.speech).map_err(|e| format!("{id}: speech settings widen the model's: {e}"))?;
623 }
624 Ok(())
625 }
626
627 pub fn with_transcribe(mut self, on: bool) -> Self {
629 self.transcribe = on;
630 self
631 }
632
633 pub fn purpose(&self) -> Purpose {
636 self.capabilities().purpose(self.embedding)
637 }
638
639 pub fn with_limits(mut self, limits: MediaLimits) -> Self {
641 self.limits = limits;
642 self
643 }
644
645 pub fn with_mmproj(mut self, path: impl Into<String>) -> Self {
647 self.mmproj = Some(path.into());
648 self
649 }
650
651 pub fn with_lora_slots(mut self, slots: u32) -> Self {
653 self.lora_slots = Some(slots);
654 self
655 }
656
657 pub fn runtime_lora(&self) -> bool {
660 self.engine == EngineKind::Vllm && self.wrap.is_none() && (!self.adapters.is_empty() || self.lora_slots.is_some_and(|n| n > 0))
661 }
662
663 pub fn with_adapters(mut self, adapters: Vec<LoraAdapter>) -> Self {
664 self.adapters = adapters;
665 self
666 }
667
668 pub fn served_ids(&self) -> Vec<String> {
670 std::iter::once(self.id.clone()).chain(self.adapters.iter().map(|a| a.id.clone())).collect()
671 }
672
673 pub fn check_adapters(&self) -> Result<(), String> {
680 if self.adapters.is_empty() {
681 return Ok(());
682 }
683 let id = &self.id;
684 if self.wrap.is_some() {
685 return Err(format!("{id}: a wrapped server can't take adapters from this node"));
686 }
687 if self.embedding {
688 return Err(format!("{id}: embedding models take no adapters"));
689 }
690 if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::Vllm) {
691 return Err(format!("{id}: {} serves no adapters here; use llama.cpp or vLLM", self.engine.name()));
692 }
693 let mut seen = std::collections::HashSet::new();
694 for a in &self.adapters {
695 if a.id.trim().is_empty() {
696 return Err(format!("{id}: an adapter needs an id"));
697 }
698 if a.id == *id {
699 return Err(format!("{id}: adapter id {} is the base model's", a.id));
700 }
701 if !seen.insert(a.id.as_str()) {
702 return Err(format!("{id}: adapter id {} is used twice", a.id));
703 }
704 if a.scale.is_some_and(|s| !s.is_finite()) {
705 return Err(format!("{}: the scale must be a finite number", a.id));
706 }
707 }
708 match self.engine {
709 EngineKind::Llamacpp => {
710 let header = |path: &str| -> Result<weirdnet_model::gguf::GgufHeader, String> {
711 let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
712 weirdnet_model::gguf::read_header(std::io::BufReader::new(f)).map_err(|e| format!("{path}: {e}"))
713 };
714 let base = header(&self.source)?;
715 if base.kind.is_adapter() {
716 return Err(format!("{id}: {} is an adapter, not a base model", self.source));
717 }
718 for a in &self.adapters {
719 if a.path.contains(',') {
720 return Err(format!("{}: llama.cpp can't take a path with a comma ({})", a.id, a.path));
721 }
722 let h = header(&a.path)?;
723 if !h.kind.is_lora() {
724 return Err(format!("{}: {} is not a LoRA adapter GGUF", a.id, a.path));
725 }
726 if h.architecture != base.architecture {
727 return Err(format!("{}: adapter architecture {} doesn't match the base's {}", a.id, h.architecture, base.architecture));
728 }
729 }
730 }
731 _ => {
732 for a in &self.adapters {
733 let p = Path::new(&a.path);
734 if p.is_dir() {
735 let config: serde_json::Value = std::fs::read(p.join("adapter_config.json"))
736 .ok()
737 .and_then(|b| serde_json::from_slice(&b).ok())
738 .ok_or_else(|| format!("{}: {} has no readable adapter_config.json", a.id, a.path))?;
739 if !config["peft_type"].as_str().unwrap_or("LORA").eq_ignore_ascii_case("lora") {
740 return Err(format!("{}: {} is not a LoRA adapter", a.id, a.path));
741 }
742 } else if p.exists() {
743 return Err(format!("{}: vLLM takes a PEFT directory, not the file {}", a.id, a.path));
744 } else if weirdnet_model::hf::check_repo(&a.path).is_err() {
745 return Err(format!("{}: {} is neither a directory nor a Hub id", a.id, a.path));
746 }
747 }
748 }
749 }
750 Ok(())
751 }
752
753 pub fn capabilities(&self) -> Capabilities {
770 let own = if self.embedding {
771 Capabilities::embeddings()
772 } else if self.speak {
773 let speaks = match self.engine {
774 EngineKind::Llamacpp => self.has_projector(),
775 EngineKind::VllmOmni => true,
776 _ => false,
777 };
778 Capabilities::default().with_speak(speaks)
779 } else {
780 let media = self.engine == EngineKind::Llamacpp && self.has_projector();
781 let transcribe = self.transcribe && (media || self.engine == EngineKind::Vllm);
782 let video = self.video && self.engine == EngineKind::Vllm;
783 Capabilities::text().with_vision(media || video).with_audio(media).with_transcribe(transcribe).with_video(video)
785 };
786 own.with_limits(self.limits).intersect(self.engine.capabilities())
787 }
788
789 fn has_projector(&self) -> bool {
790 self.mmproj.is_some() || self.extra_args.iter().any(|a| matches!(a.split('=').next(), Some("--mmproj" | "-mm" | "--mmproj-url" | "-mmu")))
791 }
792}
793
794pub fn find_in_path(name: &str) -> Option<PathBuf> {
796 let path = std::env::var_os("PATH")?;
797 std::env::split_paths(&path).map(|d| d.join(name)).find(|p| is_executable(p))
798}
799
800fn is_executable(p: &Path) -> bool {
801 #[cfg(unix)]
802 {
803 use std::os::unix::fs::PermissionsExt;
804 std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
805 }
806 #[cfg(not(unix))]
807 {
808 p.is_file()
809 }
810}
811
812#[cfg(test)]
813pub(crate) mod tests {
814 use super::*;
815
816 fn args(cmd: &Command) -> Vec<String> {
817 cmd.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect()
818 }
819
820 #[test]
821 fn llama_args() {
822 let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/m/q.gguf");
823 m.context = Some(8192);
824 m.slots = Some(2);
825 let cmd = EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k");
826 let a = args(&cmd);
827 assert!(a.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
828 assert!(a.windows(2).any(|w| w == ["--port", "4321"]));
829 assert!(a.windows(2).any(|w| w == ["--alias", "qwen3-8b"]));
830 assert!(a.windows(2).any(|w| w == ["--parallel", "2"]));
831 assert!(!a.iter().any(|x| x == "k"), "the key stays out of argv");
832 }
833
834 #[test]
835 fn a_projector_goes_on_the_command_and_into_capabilities() {
836 let m = ModelLaunch::new("v", EngineKind::Llamacpp, "/m/v.gguf");
837 assert!(!m.capabilities().vision);
838 let m = m.with_mmproj("/m/mmproj.gguf");
839 let a = args(&EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k"));
840 assert!(a.windows(2).any(|w| w == ["--mmproj", "/m/mmproj.gguf"]));
841 assert!(m.capabilities().vision);
842 let back: ModelLaunch = serde_json::from_value(serde_json::to_value(&m).unwrap()).unwrap();
843 assert_eq!(back.mmproj.as_deref(), Some("/m/mmproj.gguf"));
844 }
845
846 pub(crate) fn gguf(kv: &[(&str, serde_json::Value)]) -> Vec<u8> {
848 let mut out = b"GGUF".to_vec();
849 out.extend(3u32.to_le_bytes());
850 out.extend(0u64.to_le_bytes());
851 out.extend((kv.len() as u64).to_le_bytes());
852 let s = |out: &mut Vec<u8>, s: &str| {
853 out.extend((s.len() as u64).to_le_bytes());
854 out.extend(s.as_bytes());
855 };
856 for (k, v) in kv {
857 s(&mut out, k);
858 match v {
859 serde_json::Value::String(t) => {
860 out.extend(8u32.to_le_bytes());
861 s(&mut out, t);
862 }
863 serde_json::Value::Number(n) if n.is_u64() => {
864 out.extend(4u32.to_le_bytes());
865 out.extend((n.as_u64().unwrap() as u32).to_le_bytes());
866 }
867 serde_json::Value::Number(n) => {
868 out.extend(6u32.to_le_bytes());
869 out.extend((n.as_f64().unwrap() as f32).to_le_bytes());
870 }
871 serde_json::Value::Bool(b) => {
872 out.extend(7u32.to_le_bytes());
873 out.push(*b as u8);
874 }
875 _ => unreachable!(),
876 }
877 }
878 out
879 }
880
881 pub(crate) fn base_gguf(arch: &str) -> Vec<u8> {
882 gguf(&[("general.architecture", arch.into()), (format!("{arch}.block_count").as_str(), 1.into())])
883 }
884
885 pub(crate) fn lora_gguf(arch: &str) -> Vec<u8> {
886 gguf(&[
887 ("general.architecture", arch.into()),
888 ("general.type", "adapter".into()),
889 ("adapter.type", "lora".into()),
890 ("adapter.lora.alpha", 16.5.into()),
891 ])
892 }
893
894 #[test]
895 fn llama_adapter_args_and_checks() {
896 let tmp = tempfile::tempdir().unwrap();
897 let w = |name: &str, b: Vec<u8>| {
898 let p = tmp.path().join(name);
899 std::fs::write(&p, b).unwrap();
900 p.display().to_string()
901 };
902 let base = w("base.gguf", base_gguf("qwen3"));
903 let (a, b) = (w("a.gguf", lora_gguf("qwen3")), w("b.gguf", lora_gguf("qwen3")));
904 let m = ModelLaunch::new("qwen", EngineKind::Llamacpp, &base)
905 .with_adapters(vec![LoraAdapter::new("tune-a", &a).with_scale(0.5), LoraAdapter::new("tune-b", &b)]);
906 assert_eq!(m.served_ids(), ["qwen", "tune-a", "tune-b"]);
907 m.check_adapters().unwrap();
908 let argv = args(&EngineConfig::llamacpp("llama-server").command(&m, 1, "k"));
909 let loras: Vec<&String> = argv.windows(2).filter(|w| w[0] == "--lora").map(|w| &w[1]).collect();
910 assert_eq!(loras, [&a, &b], "one --lora per adapter, in order");
911 assert!(argv.iter().any(|x| x == "--lora-init-without-apply"));
912 assert!(
913 !args(&EngineConfig::llamacpp("l").command(&ModelLaunch::new("x", EngineKind::Llamacpp, &base), 1, "k"))
914 .iter()
915 .any(|x| x.starts_with("--lora"))
916 );
917
918 let bad =
919 |adapters: Vec<LoraAdapter>| ModelLaunch::new("qwen", EngineKind::Llamacpp, &base).with_adapters(adapters).check_adapters().unwrap_err();
920 assert!(bad(vec![LoraAdapter::new("qwen", &a)]).contains("base model's"));
921 assert!(bad(vec![LoraAdapter::new("t", &a), LoraAdapter::new("t", &b)]).contains("twice"));
922 assert!(bad(vec![LoraAdapter::new("t", &a).with_scale(f32::NAN)]).contains("finite"));
923 assert!(bad(vec![LoraAdapter::new("t", &base)]).contains("not a LoRA"));
924 assert!(bad(vec![LoraAdapter::new("t", w("llama.gguf", lora_gguf("llama")))]).contains("architecture"));
925 assert!(bad(vec![LoraAdapter::new("t", tmp.path().join("missing.gguf").display().to_string())]).contains("missing.gguf"));
926 assert!(bad(vec![LoraAdapter::new("t", w("a,b.gguf", lora_gguf("qwen3")))]).contains("comma"));
927 let mut emb = m.clone();
928 emb.embedding = true;
929 assert!(emb.check_adapters().unwrap_err().contains("embedding"));
930 let mut wrapped = m.clone();
931 wrapped.wrap = Some(Wrap { url: "http://127.0.0.1:1".into(), api_key: None });
932 assert!(wrapped.check_adapters().unwrap_err().contains("wrapped"));
933 let mlx = ModelLaunch::new("m", EngineKind::Mlx, &base).with_adapters(vec![LoraAdapter::new("t", &a)]);
934 assert!(mlx.check_adapters().unwrap_err().contains("mlx"));
935 let json = serde_json::to_string(&ModelLaunch::new("x", EngineKind::Llamacpp, "/m")).unwrap();
936 assert!(!json.contains("adapters"), "no adapters, same JSON as before");
937 }
938
939 #[test]
940 fn vllm_adapter_args_and_checks() {
941 let tmp = tempfile::tempdir().unwrap();
942 let peft = tmp.path().join("tune");
943 std::fs::create_dir(&peft).unwrap();
944 std::fs::write(peft.join("adapter_config.json"), br#"{"peft_type":"LORA","r":8}"#).unwrap();
945 let peft = peft.display().to_string();
946 let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B")
947 .with_adapters(vec![LoraAdapter::new("tune", &peft), LoraAdapter::new("hub", "owner/some-lora")]);
948 m.check_adapters().unwrap();
949 let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
950 assert_eq!(a.iter().filter(|x| *x == "--lora-modules").count(), 1, "vLLM keeps only the last --lora-modules");
951 let at = a.iter().position(|x| x == "--lora-modules").unwrap();
952 let mods: Vec<serde_json::Value> = a[at + 1..at + 3].iter().map(|j| serde_json::from_str(j).unwrap()).collect();
953 assert_eq!(mods[0], serde_json::json!({"name": "tune", "path": peft, "base_model_name": "big"}));
954 assert_eq!(mods[1]["name"], "hub");
955 assert!(a.iter().any(|x| x == "--enable-lora"));
956 assert!(a.windows(2).any(|w| w == ["--max-loras", "2"]));
957 let cmd = EngineConfig::vllm("vllm").command(&m, 9000, "k");
958 let env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
959 assert!(env.iter().any(|(k, v)| k == "VLLM_ALLOW_RUNTIME_LORA_UPDATING" && v.as_deref() == Some("True".as_ref())));
960 let empty = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B").with_lora_slots(4);
962 assert!(empty.runtime_lora());
963 let a = args(&EngineConfig::vllm("vllm").command(&empty, 9000, "k"));
964 assert!(a.iter().any(|x| x == "--enable-lora") && !a.iter().any(|x| x == "--lora-modules"));
965 assert!(a.windows(2).any(|w| w == ["--max-loras", "4"]));
966 let plain = args(&EngineConfig::vllm("vllm").command(&ModelLaunch::new("big", EngineKind::Vllm, "Q/Q"), 9000, "k"));
967 assert!(!plain.iter().any(|x| x == "--enable-lora"));
968 assert!(!ModelLaunch::new("q", EngineKind::Llamacpp, "/q.gguf").with_lora_slots(2).runtime_lora(), "llama.cpp ignores it");
969 let file = tmp.path().join("x.gguf");
970 std::fs::write(&file, lora_gguf("qwen3")).unwrap();
971 let bad = |path: String| {
972 ModelLaunch::new("big", EngineKind::Vllm, "Q/Q").with_adapters(vec![LoraAdapter::new("t", path)]).check_adapters().unwrap_err()
973 };
974 assert!(bad(file.display().to_string()).contains("PEFT directory"));
975 assert!(bad("/no/such/dir".into()).contains("Hub id"));
976 }
977
978 #[test]
979 fn wrap_is_loopback_only() {
980 let w = |u: &str| Wrap { url: u.into(), api_key: None }.check();
981 assert!(w("http://127.0.0.1:8000").is_ok());
982 assert!(w("http://localhost:8000/").is_ok());
983 assert!(w("http://[::1]:8000").is_ok());
984 assert!(w("https://127.0.0.1:8000").is_err());
985 assert!(w("http://10.0.0.2:8000").is_err());
986 assert!(w("http://127.0.0.1.evil:8000").is_err());
987 assert_eq!(Wrap { url: "http://127.0.0.1:8000/v1/".into(), api_key: None }.base(), "http://127.0.0.1:8000");
988 }
989
990 #[test]
991 fn vllm_args() {
992 let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B");
993 let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
994 assert_eq!(&a[..2], ["serve", "Qwen/Qwen3-8B"]);
995 assert!(a.windows(2).any(|w| w == ["--served-model-name", "big"]));
996 }
997
998 #[test]
999 fn mlx_args() {
1000 let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Mlx, "/m/mlx/Qwen3-8B-4bit");
1001 m.context = Some(4096);
1002 let cmd = EngineConfig::mlx("/v/bin/mlx_lm.server").command(&m, 9, "k");
1003 assert_eq!(args(&cmd), ["--model", "/m/mlx/Qwen3-8B-4bit", "--host", "127.0.0.1", "--port", "9", "--max-tokens", "4096"]);
1004 assert!(cmd.as_std().get_envs().all(|(_, v)| v != Some(std::ffi::OsStr::new("k"))), "MLX-LM gets no key");
1005 m.context = None;
1006 let a = args(&EngineConfig::mlx("mlx_lm.server").command(&m, 9, "k"));
1007 assert_eq!(a.last().map(String::as_str), Some("32768"));
1008 assert_eq!(serde_json::to_string(&EngineKind::Mlx).unwrap(), "\"mlx\"");
1009 }
1010
1011 #[test]
1012 fn capabilities_as_modalities() {
1013 let media = Capabilities::text().with_vision(true).with_audio(true);
1014 assert_eq!(media.inputs(), Modalities::new(true, true));
1015 assert_eq!(Capabilities::text().lacking(Modalities::VISION), Some("images"));
1016 assert_eq!(Capabilities::text().with_vision(true).lacking(Modalities::new(true, true)), Some("audio"));
1017 assert_eq!(media.lacking(Modalities::AUDIO), None);
1018 assert_eq!(
1019 ModelLaunch::new("x", EngineKind::Mlx, "/m/x").capabilities().lacking(Modalities::VISION),
1020 Some("images"),
1021 "MLX never takes images"
1022 );
1023 }
1024
1025 #[test]
1026 fn capabilities() {
1027 let mut m = ModelLaunch::new("x", EngineKind::Mlx, "/m/x");
1028 assert_eq!(m.capabilities(), Capabilities::text());
1029 m.extra_args = vec!["--mmproj".into(), "/p".into()];
1030 assert!(!m.capabilities().vision, "MLX-LM never takes images");
1031 m.embedding = true;
1032 assert_eq!(m.capabilities(), Capabilities::default(), "MLX-LM serves no embeddings");
1033
1034 let mut l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
1035 assert_eq!(l.capabilities(), Capabilities::text());
1036 l.extra_args = vec!["--mmproj=/p/mm.gguf".into()];
1037 let c = l.capabilities();
1038 assert!(c.chat && c.vision && c.audio && !c.embeddings);
1039 l.embedding = true;
1040 assert_eq!(l.capabilities(), Capabilities::embeddings());
1041
1042 let v = ModelLaunch::new("v", EngineKind::Vllm, "Qwen/Qwen3-8B");
1043 assert_eq!(v.capabilities(), Capabilities::text());
1044 assert!(!EngineKind::Mlx.capabilities().embeddings && EngineKind::Llamacpp.capabilities().vision);
1045 }
1046
1047 fn limits() -> MediaLimits {
1048 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)
1049 }
1050
1051 #[test]
1052 fn limits_reach_capabilities_and_catalog_entries() {
1053 assert!(Capabilities::text().limits.is_unknown());
1054 let l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf").with_mmproj("/p/mm.gguf").with_limits(limits());
1055 let c = l.capabilities();
1056 assert_eq!(c.limits, limits(), "the operator's limits survive the engine's (which knows none)");
1057 assert!(c.vision && c.audio);
1058 let both = c.intersect(Capabilities::text().with_vision(true).with_limits(MediaLimits::new().with_max_images(2)));
1059 assert_eq!((both.limits.max_images, both.limits.image_tokens), (Some(2), Some(256)), "stricter wins, one-sided kept");
1060 use weirdnet_agent::remote::catalog::{ModelState as CatalogState, Purpose};
1061 let entry = c.apply_to(CatalogModel::new("g", Purpose::Chat, CatalogState::Warm).with_replicas(1));
1062 assert_eq!((entry.inputs, entry.limits, entry.replicas), (Modalities::new(true, true), limits(), 1));
1063 let wire: CatalogModel = serde_json::from_str(&serde_json::to_string(&entry).unwrap()).unwrap();
1065 assert_eq!(wire.limits, limits());
1066 }
1067
1068 #[test]
1069 fn transcription_role_and_purpose() {
1070 use weirdnet_agent::remote::catalog::Purpose;
1071 let vox = ModelLaunch::new("vox", EngineKind::Llamacpp, "/m/v.gguf").with_mmproj("/m/mm.gguf").with_transcribe(true);
1072 assert!(vox.capabilities().transcribe && vox.capabilities().audio);
1073 assert_eq!(vox.purpose(), Purpose::Transcribe);
1074 let no_projector = ModelLaunch::new("v", EngineKind::Llamacpp, "/m/v.gguf").with_transcribe(true);
1075 assert!(!no_projector.capabilities().transcribe, "llama-server takes no audio without a projector");
1076 assert_eq!(no_projector.purpose(), Purpose::Chat);
1077 let mut via_args = no_projector.clone();
1078 via_args.extra_args = vec!["-mm".into(), "/m/mm.gguf".into()];
1079 assert!(via_args.capabilities().transcribe);
1080 let whisper = ModelLaunch::new("w", EngineKind::Vllm, "openai/whisper-large-v3").with_transcribe(true);
1081 assert!(whisper.capabilities().transcribe && !whisper.capabilities().audio);
1082 assert!(!ModelLaunch::new("m", EngineKind::Mlx, "/m").with_transcribe(true).capabilities().transcribe);
1083 let mut emb = vox.clone();
1084 emb.embedding = true;
1085 assert_eq!((emb.capabilities().transcribe, emb.purpose()), (false, Purpose::Embedding));
1086 assert_eq!(ModelLaunch::new("c", EngineKind::Llamacpp, "/m/c.gguf").purpose(), Purpose::Chat);
1087 let both = vox.capabilities().intersect(Capabilities::text().with_audio(true));
1088 assert!(!both.transcribe, "both sides must transcribe");
1089
1090 let json = serde_json::to_string(&Capabilities::text()).unwrap();
1092 assert!(!json.contains("transcribe"));
1093 let back: Capabilities = serde_json::from_str(&serde_json::to_string(&vox.capabilities()).unwrap()).unwrap();
1094 assert!(back.transcribe);
1095 let cbor = weirdnet_agent::remote::to_cbor(&vox.capabilities()).unwrap();
1096 assert!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap().transcribe);
1097 assert!(!serde_json::to_string(&no_projector.clone().with_transcribe(false)).unwrap().contains("transcribe"));
1098 let old: ModelLaunch = serde_json::from_str(&serde_json::to_string(&ModelLaunch::new("o", EngineKind::Llamacpp, "/o")).unwrap()).unwrap();
1099 assert!(!old.transcribe);
1100 let l: ModelLaunch = serde_json::from_value(serde_json::to_value(&whisper).unwrap()).unwrap();
1101 assert!(l.transcribe);
1102 }
1103
1104 #[test]
1105 fn vllm_omni_is_its_own_engine() {
1106 assert_eq!(serde_json::to_string(&EngineKind::VllmOmni).unwrap(), r#""vllm-omni""#);
1107 assert_eq!(serde_json::from_str::<EngineKind>(r#""vllm-omni""#).unwrap(), EngineKind::VllmOmni);
1108 for k in [EngineKind::Llamacpp, EngineKind::Vllm, EngineKind::Mlx, EngineKind::VllmOmni] {
1109 assert_eq!(EngineKind::parse(k.name()), Some(k));
1110 assert!(!k.install_hint().is_empty());
1111 }
1112 assert_eq!(
1113 (EngineKind::parse("omni"), EngineKind::parse("llama.cpp"), EngineKind::parse("x")),
1114 (Some(EngineKind::VllmOmni), Some(EngineKind::Llamacpp), None)
1115 );
1116 assert!(EngineKind::VllmOmni.supported("linux", "x86_64") && !EngineKind::VllmOmni.supported("macos", "aarch64"));
1117 assert!(EngineKind::Llamacpp.supported("windows", "x86_64") && !EngineKind::Mlx.supported("linux", "x86_64"));
1118 assert_eq!((EngineKind::VllmOmni.program(), EngineKind::Llamacpp.program()), ("vllm", "llama-server"));
1119 let caps = EngineKind::VllmOmni.capabilities();
1120 assert!(caps.speak && caps.chat && !caps.video && !caps.embeddings);
1121 assert!(EngineKind::Llamacpp.capabilities().speak && !EngineKind::Llamacpp.capabilities().video);
1122 assert!(EngineKind::Vllm.capabilities().video && !EngineKind::Vllm.capabilities().speak);
1123
1124 let mut m = ModelLaunch::new("qwen3-tts-1.7b-customvoice", EngineKind::VllmOmni, "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice").with_speak(true);
1125 m.slots = Some(4);
1126 let a = args(&EngineConfig::vllm_omni("/venv/bin/vllm").command(&m, 4321, "k"));
1127 assert_eq!(&a[..3], ["serve", "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice", "--omni"]);
1128 assert!(a.windows(2).any(|w| w == ["--served-model-name", "qwen3-tts-1.7b-customvoice"]));
1129 assert!(a.windows(2).any(|w| w == ["--max-num-seqs", "4"]));
1130 assert!(!a.iter().any(|x| x == "k" || x.starts_with("--allowed-local-media-path")), "no key in argv, no local media");
1131 assert_eq!(EngineConfig::vllm_omni("/v").ready_timeout, Duration::from_secs(1200));
1132 }
1133
1134 #[test]
1135 fn speakers_speak_and_nothing_else() {
1136 let kokoro = ModelLaunch::new("kokoro-82m", EngineKind::Llamacpp, "/m/kokoro.gguf").with_speak(true);
1137 assert_eq!(kokoro.capabilities(), Capabilities::default(), "no projector: llama.cpp can't speak");
1138 assert!(kokoro.check_speech().unwrap_err().contains("projector"));
1139 let kokoro = kokoro.with_mmproj("/m/mmproj-kokoro.gguf");
1140 assert_eq!(kokoro.capabilities(), Capabilities::default().with_speak(true));
1141 assert_eq!(kokoro.purpose(), Purpose::Speak);
1142 assert!(kokoro.check_speech().is_ok());
1143 let omni = ModelLaunch::new("q", EngineKind::VllmOmni, "Qwen/X").with_speak(true);
1144 assert_eq!((omni.capabilities().speak, omni.purpose()), (true, Purpose::Speak));
1145 for engine in [EngineKind::Vllm, EngineKind::Mlx] {
1146 let m = ModelLaunch::new("s", engine, "/m/s").with_speak(true);
1147 assert!(!m.capabilities().speak && m.check_speech().unwrap_err().contains("no speech engine"), "{engine:?}");
1148 }
1149 let mut both = omni.clone().with_transcribe(true);
1150 assert!(both.check_speech().is_err());
1151 both.transcribe = false;
1152 both.extra_args = vec!["--allowed-local-media-path=/".into()];
1153 assert!(both.check_speech().unwrap_err().contains("local media"));
1154 let p = SpeechProfile::new().with_max_input_chars(100);
1156 assert!(ModelLaunch::new("c", EngineKind::Llamacpp, "/m/c.gguf").with_speech(p.clone()).check_speech().is_err());
1157 assert!(kokoro.clone().with_speech(p.clone().with_presets(vec!["af_heart".into()])).check_speech().is_ok());
1158 let e = kokoro.clone().with_speech(SpeechProfile::new().with_presets(vec!["alloy".into()])).check_speech().unwrap_err();
1159 assert!(e.contains("widen") && e.contains("alloy"), "{e}");
1160 assert!(kokoro.clone().with_speech(SpeechProfile::new().with_design(true)).check_speech().is_err());
1161
1162 assert!(kokoro.cataloged_speech().unwrap().raw);
1164 let by_repo = ModelLaunch::new("tts", EngineKind::VllmOmni, "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign");
1165 let entry = weirdnet_model::hw::find(weirdnet_model::hw::QWEN3_TTS_1_7B_VOICEDESIGN).unwrap();
1166 assert_eq!(by_repo.cataloged_speech().is_some(), entry.spec.repo.eq_ignore_ascii_case("Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign"));
1167 let by_repo = ModelLaunch::new("tts", EngineKind::VllmOmni, entry.spec.repo.clone());
1168 assert!(by_repo.cataloged_speech().unwrap().design);
1169 let gguf = weirdnet_model::hw::find(weirdnet_model::hw::VOXCPM2).unwrap();
1170 let by_file = ModelLaunch::new("vox", EngineKind::Llamacpp, format!("/models/{}", gguf.spec.file));
1171 assert!(by_file.cataloged_speech().unwrap().design);
1172 assert!(ModelLaunch::new("kokoro-82m", EngineKind::VllmOmni, "x/y").cataloged_speech().is_none(), "a GGUF entry is not vLLM-Omni's");
1173 assert!(ModelLaunch::new("kokoro-82m", EngineKind::Vllm, "x/y").cataloged_speech().is_none());
1174
1175 let json = serde_json::to_value(kokoro.clone().with_speech(p.clone())).unwrap();
1176 assert_eq!((json["speak"].as_bool(), json["speech"]["max_input_chars"].as_u64()), (Some(true), Some(100)));
1177 let back: ModelLaunch = serde_json::from_value(json).unwrap();
1178 assert_eq!(back.speech, p);
1179 }
1180
1181 #[test]
1182 fn video_is_vllms_on_the_operators_word() {
1183 let vl = ModelLaunch::new("vl", EngineKind::Vllm, "Qwen/Qwen2.5-VL-7B-Instruct");
1184 assert!(!vl.capabilities().video);
1185 let vl = vl.with_video(true);
1186 let caps = vl.capabilities();
1187 assert!(caps.video && caps.chat && caps.vision, "a video model takes images too");
1188 assert_eq!(caps.inputs(), Modalities::new(true, false).with_video(true));
1189 assert_eq!(caps.lacking(Modalities::VIDEO), None);
1190 assert_eq!(Capabilities::text().lacking(Modalities::VIDEO), Some("video"));
1191 assert!(!ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf").with_mmproj("/m/p.gguf").with_video(true).capabilities().video);
1192 assert!(!ModelLaunch::new("m", EngineKind::Mlx, "/m/m").with_video(true).capabilities().video);
1193 assert!(!caps.intersect(Capabilities::text()).video);
1194 let limits = MediaLimits::new().with_video_max_seconds(120).with_video_frames_per_minute(120);
1195 let entry = caps.with_limits(limits).apply_to(CatalogModel::new("vl", Purpose::Chat, weirdnet_agent::remote::catalog::ModelState::Warm));
1196 assert!(entry.inputs.video);
1197 assert_eq!((entry.limits.video_max_seconds, entry.limits.video_frame_rate()), (Some(120), Some(2.0)));
1198 let json = serde_json::to_string(&caps).unwrap();
1199 assert!(json.contains(r#""video":true"#) && !json.contains("speak"));
1200 assert_eq!(serde_json::from_str::<Capabilities>(&json).unwrap(), caps);
1201 let cbor = weirdnet_agent::remote::to_cbor(&caps).unwrap();
1202 assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap(), caps);
1203 }
1204
1205 #[test]
1206 fn records_without_limits_read_as_before() {
1207 let old = r#"{"chat":true,"embeddings":false,"vision":true,"audio":false}"#;
1208 let c: Capabilities = serde_json::from_str(old).unwrap();
1209 assert_eq!(c, Capabilities::text().with_vision(true));
1210 assert!(c.limits.is_unknown());
1211 assert_eq!(serde_json::to_string(&c).unwrap(), old, "no limits: the record looks as before");
1212 let with: Capabilities = serde_json::from_str(&serde_json::to_string(&c.with_limits(limits())).unwrap()).unwrap();
1213 assert_eq!(with.limits, limits());
1214 let cbor = weirdnet_agent::remote::to_cbor(&c.with_limits(limits())).unwrap();
1215 assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap(), c.with_limits(limits()));
1216 assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&weirdnet_agent::remote::to_cbor(&c).unwrap()).unwrap(), c);
1217 let launch = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
1218 let json = serde_json::to_string(&launch).unwrap();
1219 assert!(!json.contains("limits"));
1220 let back: ModelLaunch = serde_json::from_str(&json).unwrap();
1221 assert_eq!(back, launch);
1222 let with = launch.with_limits(limits());
1223 assert_eq!(serde_json::from_str::<ModelLaunch>(&serde_json::to_string(&with).unwrap()).unwrap(), with);
1224 }
1225}