Skip to main content

weirdnet_backends/
host.rs

1//! The model node's inference side: a `weirdnet-agent` [`InferHost`] over the [`Supervisor`],
2//! serving raw infer/2 (assembled messages in, tokens out; cancel aborts the engine request),
3//! transcription (infer/2 `Transcribe`) and speech out (infer/2 `Speak`).
4
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Mutex};
7use std::time::Instant;
8
9use async_trait::async_trait;
10use futures::StreamExt;
11use weirdnet_agent::remote::infer::InferHost;
12use weirdnet_agent::remote::infer::v2::{
13    self, AudioStream, EmbedBackend, Finish, InferBackend, Input, Output, Request, SpeakBackend, SpeakRequest, TranscribeBackend, TranscribeRequest,
14    Transcript, Usage,
15};
16use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError};
17use weirdnet_agent::{CancelToken, Modalities, ModelBackend};
18
19use crate::error::{bad_request, engine_error, unavailable};
20use crate::sse::{Chunk, ToolCalls};
21use crate::supervisor::{ModelState, Supervisor};
22
23/// Measured speed, for the capability record.
24#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)]
25pub struct Speed {
26    /// Exponentially weighted decode tokens per second.
27    pub decode_tps: Option<f32>,
28    /// Exponentially weighted prefill tokens per second (prompt tokens over time to first token).
29    pub prefill_tps: Option<f32>,
30    /// The last time to first token.
31    pub ttft_ms: Option<u64>,
32}
33
34impl Speed {
35    fn ewma(old: Option<f32>, new: f32) -> Option<f32> {
36        Some(match old {
37            Some(o) => o * 0.8 + new * 0.2,
38            None => new,
39        })
40    }
41
42    fn record(&mut self, ttft: Option<f64>, total: f64, prompt: u64, completion: u64) {
43        if let Some(t) = ttft {
44            self.ttft_ms = Some((t * 1000.0) as u64);
45            if t > 0.0 && prompt > 0 {
46                self.prefill_tps = Self::ewma(self.prefill_tps, prompt as f32 / t as f32);
47            }
48            let decode = total - t;
49            if decode > 0.0 && completion > 1 {
50                self.decode_tps = Self::ewma(self.decode_tps, (completion - 1) as f32 / decode as f32);
51            }
52        }
53    }
54}
55
56/// Serves the supervisor's models over infer/2. Requests name a model by its launch id (or get
57/// the default). A request with image or audio parts is refused (`Unsupported`, so a pool tries
58/// elsewhere) unless the model takes them ([`ModelLaunch::capabilities`](crate::ModelLaunch::capabilities));
59/// remote image URLs are a `BadRequest`. A model that is not ready is refused as unavailable unless the request has
60/// `wait_for_model` or the host loads on demand. While draining or reserved
61/// ([`Supervisor::reserve`](crate::Supervisor::reserve)), new requests are refused.
62pub struct ModelHost {
63    supervisor: Supervisor,
64    auth: Arc<dyn Authorize>,
65    default_model: Option<String>,
66    load_on_demand: bool,
67    draining: AtomicBool,
68    speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
69}
70
71impl ModelHost {
72    pub fn new(supervisor: Supervisor, auth: Arc<dyn Authorize>) -> Self {
73        Self { supervisor, auth, default_model: None, load_on_demand: false, draining: AtomicBool::new(false), speed: Default::default() }
74    }
75
76    /// The model for requests that name none.
77    pub fn with_default(mut self, model: impl Into<String>) -> Self {
78        self.default_model = Some(model.into());
79        self
80    }
81
82    /// Load a model that is not ready instead of refusing (a single box with no coordinator).
83    pub fn with_load_on_demand(mut self, on: bool) -> Self {
84        self.load_on_demand = on;
85        self
86    }
87
88    pub fn supervisor(&self) -> &Supervisor {
89        &self.supervisor
90    }
91
92    /// Stop (or resume) taking new requests; requests under way finish.
93    pub fn set_draining(&self, on: bool) {
94        self.draining.store(on, Ordering::SeqCst);
95    }
96
97    pub fn draining(&self) -> bool {
98        self.draining.load(Ordering::SeqCst)
99    }
100
101    /// Measured speed per model.
102    pub fn speed(&self, model: &str) -> Speed {
103        self.speed.lock().unwrap_or_else(|e| e.into_inner()).get(model).copied().unwrap_or_default()
104    }
105
106    fn pick(&self, model: Option<&str>, wait: bool, needed: Modalities) -> Result<(String, bool), RemoteError> {
107        if self.draining() {
108            return Err(unavailable("this node is draining"));
109        }
110        if let Some(r) = self.supervisor.reservation() {
111            return Err(unavailable(format!("this node is reserved by {}", r.holder)));
112        }
113        let id = model.map(str::to_string).or_else(|| self.default_model.clone()).ok_or_else(|| bad_request("no model named and no default"))?;
114        if let Some(what) = self.supervisor.capabilities(&id).and_then(|c| c.lacking(needed)) {
115            let fallback = if needed.video { format!("; {}", weirdnet_agent::remote::catalog::VIDEO_FALLBACK) } else { String::new() };
116            return Err(RemoteError::Unsupported { message: format!("model `{id}` does not take {what} on this node{fallback}") });
117        }
118        match self.supervisor.state(&id) {
119            None => Err(crate::error::unknown_model(&id)),
120            Some(ModelState::Ready) => Ok((id, false)),
121            Some(_) if wait || self.load_on_demand => Ok((id, true)),
122            Some(state) => Err(unavailable(format!("{id} is not loaded ({state:?})"))),
123        }
124    }
125
126    /// The model for a transcription request: a named one must transcribe here
127    /// ([`Capabilities::transcribe`](crate::Capabilities::transcribe)); with none named, the
128    /// ready one first by id, else (loading on demand) the first by id.
129    fn pick_transcriber(&self, model: Option<&str>) -> Result<(String, bool), RemoteError> {
130        let transcribes = |id: &str| self.supervisor.capabilities(id).is_some_and(|c| c.transcribe);
131        let id = match model {
132            Some(id) => {
133                if self.supervisor.state(id).is_none() {
134                    return Err(crate::error::unknown_model(id));
135                }
136                if !transcribes(id) {
137                    return Err(RemoteError::Unsupported { message: format!("model `{id}` does not transcribe on this node") });
138                }
139                id.to_string()
140            }
141            None => {
142                let ids: Vec<String> = self.supervisor.launches().into_iter().map(|l| l.id).filter(|id| transcribes(id)).collect();
143                let ready = ids.iter().find(|id| self.supervisor.state(id) == Some(ModelState::Ready));
144                match ready.or(ids.first().filter(|_| self.load_on_demand)) {
145                    Some(id) => id.clone(),
146                    None if ids.is_empty() => return Err(unavailable("no transcription model on this node")),
147                    None => return Err(unavailable(format!("no transcription model is loaded on this node ({})", ids.join(", ")))),
148                }
149            }
150        };
151        self.pick(Some(&id), false, Modalities::TEXT)
152    }
153
154    /// The model for a speech request: a named one must speak here
155    /// ([`Capabilities::speak`](crate::Capabilities::speak)) and its profile cover the request
156    /// (what it lacks is a `BadRequest`; an output format this engine doesn't make is
157    /// `Unsupported`, as are models that don't speak here, so a pool tries elsewhere). With none
158    /// named, the speakers whose profile covers the request, the ready one first by id, else
159    /// (loading on demand) the first by id.
160    fn pick_speaker(&self, request: &SpeakRequest) -> Result<(String, bool), RemoteError> {
161        let speaks = |id: &str| self.supervisor.capabilities(id).is_some_and(|c| c.speak);
162        let needs = request.needs();
163        let covers = |id: &str| -> Result<(), String> {
164            match self.supervisor.speech(id) {
165                Some(p) => p.covers(&needs),
166                None => Err("has speech settings that widen what its engine reports".into()),
167            }
168        };
169        let id = match request.model.as_deref() {
170            Some(id) => {
171                if self.supervisor.state(id).is_none() {
172                    return Err(crate::error::unknown_model(id));
173                }
174                if !speaks(id) {
175                    return Err(RemoteError::Unsupported { message: format!("model `{id}` does not speak on this node") });
176                }
177                if let Err(why) = covers(id) {
178                    let mut other_format = needs.clone();
179                    other_format.format = None;
180                    let format_only = needs.format.is_some() && self.supervisor.speech(id).is_some_and(|p| p.covers(&other_format).is_ok());
181                    return Err(if format_only {
182                        RemoteError::Unsupported { message: format!("model `{id}` {why} on this node") }
183                    } else {
184                        bad_request(format!("model `{id}` {why}"))
185                    });
186                }
187                id.to_string()
188            }
189            None => {
190                let all: Vec<String> = self.supervisor.launches().into_iter().map(|l| l.id).filter(|id| speaks(id)).collect();
191                if all.is_empty() {
192                    return Err(unavailable("no speech model on this node"));
193                }
194                let mut why = None;
195                let ids: Vec<&String> = all
196                    .iter()
197                    .filter(|id| match covers(id) {
198                        Ok(()) => true,
199                        Err(w) => {
200                            why.get_or_insert_with(|| format!("`{id}` {w}"));
201                            false
202                        }
203                    })
204                    .collect();
205                let ready = ids.iter().find(|id| self.supervisor.state(id) == Some(ModelState::Ready));
206                match ready.or(ids.first().filter(|_| self.load_on_demand)) {
207                    Some(id) => (*id).clone(),
208                    None if ids.is_empty() => {
209                        return Err(RemoteError::Unsupported {
210                            message: format!("no speech model on this node covers the request ({})", why.unwrap_or_default()),
211                        });
212                    }
213                    None => {
214                        let names: Vec<&str> = ids.iter().map(|s| s.as_str()).collect();
215                        return Err(unavailable(format!("no speech model is loaded on this node ({})", names.join(", "))));
216                    }
217                }
218            }
219        };
220        self.pick(Some(&id), false, Modalities::TEXT)
221    }
222
223    fn backend(&self, id: String, load: bool) -> EngineModel {
224        EngineModel { supervisor: self.supervisor.clone(), id, load, speed: self.speed.clone() }
225    }
226}
227
228impl InferHost for ModelHost {
229    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
230        self.auth.authorize(caller)
231    }
232
233    /// Model nodes serve infer/2 only.
234    fn open(&self, _caller: &Caller, _model: Option<&str>) -> Result<Arc<dyn ModelBackend>, RemoteError> {
235        Err(RemoteError::Unsupported { message: "model nodes serve /weirdnet-agent/infer/2".into() })
236    }
237
238    fn open_request(&self, _caller: &Caller, request: &Request) -> Result<Arc<dyn InferBackend>, RemoteError> {
239        let needed = request.needs();
240        if let Some(Err(message)) = request.inline_messages().unwrap_or_default().iter().map(|m| m.content.check()).find(Result::is_err) {
241            return Err(bad_request(message));
242        }
243        let (id, load) = self.pick(request.model.as_deref(), request.wait_for_model, needed)?;
244        Ok(Arc::new(self.backend(id, load)))
245    }
246
247    fn open_embed(&self, _caller: &Caller, model: Option<&str>) -> Result<Arc<dyn EmbedBackend>, RemoteError> {
248        let (id, load) = self.pick(model, false, Modalities::TEXT)?;
249        Ok(Arc::new(self.backend(id, load)))
250    }
251
252    /// A speech-to-text model on this node ([`Capabilities::transcribe`](crate::Capabilities::transcribe)):
253    /// the named one, or with none named the loaded one (first by id; with load on demand, the
254    /// first by id even when not loaded). A named model that doesn't transcribe here is
255    /// `Unsupported` (a pool tries elsewhere); none at all is unavailable. Served by
256    /// [`Supervisor::transcribe`](crate::Supervisor::transcribe).
257    fn open_transcribe(&self, _caller: &Caller, model: Option<&str>) -> Result<Arc<dyn TranscribeBackend>, RemoteError> {
258        let (id, load) = self.pick_transcriber(model)?;
259        Ok(Arc::new(self.backend(id, load)))
260    }
261
262    /// A speaking model on this node ([`Capabilities::speak`](crate::Capabilities::speak))
263    /// whose speech profile covers the request: the named one, or with none named the loaded one
264    /// (first by id; with load on demand, the first by id even when not loaded). A named model
265    /// that lacks what the request needs is a `BadRequest` that says what; one that doesn't speak
266    /// here is `Unsupported` (a pool tries elsewhere); none at all is unavailable. Served by
267    /// [`Supervisor::speak`](crate::Supervisor::speak). Since 0.4.10.
268    fn open_speak(&self, _caller: &Caller, request: &SpeakRequest) -> Result<Arc<dyn SpeakBackend>, RemoteError> {
269        let (id, load) = self.pick_speaker(request)?;
270        Ok(Arc::new(self.backend(id, load)))
271    }
272}
273
274/// One supervised model as an infer/2 backend.
275pub struct EngineModel {
276    supervisor: Supervisor,
277    id: String,
278    load: bool,
279    speed: Arc<Mutex<std::collections::HashMap<String, Speed>>>,
280}
281
282impl EngineModel {
283    async fn ready(&self) -> Result<(), RemoteError> {
284        if self.load { self.supervisor.load(&self.id).await } else { Ok(()) }
285    }
286}
287
288#[async_trait]
289impl InferBackend for EngineModel {
290    fn name(&self) -> String {
291        self.id.clone()
292    }
293
294    /// Both engines continue an assistant prefix (chat) or the prompt plus the prefix (a raw
295    /// prompt, through `/v1/completions`).
296    fn resumes(&self) -> bool {
297        true
298    }
299
300    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
301        self.ready().await?;
302        let started = Instant::now();
303        let mut stream = match &request.input {
304            Input::Prompt(prompt) => {
305                let mut prompt = prompt.clone();
306                if let Some(p) = &request.assistant_prefix {
307                    prompt.push_str(&p.text);
308                }
309                self.supervisor.complete_scaled(&self.id, &prompt, &request.sampling, request.seed, request.adapter_scale).await?
310            }
311            _ => self.supervisor.chat(&self.id, request).await?,
312        };
313        let mut calls = ToolCalls::default();
314        let mut first: Option<f64> = None;
315        loop {
316            let next = tokio::select! {
317                _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
318                n = stream.next() => n,
319            };
320            let chunk = match next {
321                Some(c) => c?,
322                None => return Err(engine_error("engine stream ended early")),
323            };
324            if first.is_none() && matches!(chunk, Chunk::Text(_) | Chunk::Reasoning(_) | Chunk::ToolCall { .. }) {
325                first = Some(started.elapsed().as_secs_f64());
326            }
327            match chunk {
328                Chunk::Text(t) => out.text(t),
329                Chunk::Reasoning(t) => out.reasoning(t),
330                Chunk::ToolCall { index, id, name, arguments } => calls.push(index, id, name, &arguments),
331                Chunk::Done { finish_reason, usage } => {
332                    let had_calls = !calls.is_empty();
333                    for call in calls.finish() {
334                        out.tool_call(call);
335                    }
336                    let reason = finish_reason.unwrap_or_else(|| if had_calls { "tool_calls".into() } else { "stop".into() });
337                    let mut finish = Finish::new(reason);
338                    if let Some(u) = usage {
339                        out.usage(u);
340                        finish = finish.with_usage(u);
341                        let total = started.elapsed().as_secs_f64();
342                        self.speed.lock().unwrap_or_else(|e| e.into_inner()).entry(self.id.clone()).or_default().record(
343                            first,
344                            total,
345                            u.prompt_tokens,
346                            u.completion_tokens,
347                        );
348                    }
349                    return Ok(finish);
350                }
351            }
352        }
353    }
354}
355
356#[async_trait]
357impl EmbedBackend for EngineModel {
358    fn name(&self) -> String {
359        self.id.clone()
360    }
361
362    async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError> {
363        Ok(self.embed_counted(input, cancel).await?.0)
364    }
365
366    /// The vector and the engine's `usage.prompt_tokens`.
367    async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
368        self.ready().await?;
369        let inputs = [input.to_string()];
370        let call = self.supervisor.embed(&self.id, &inputs);
371        let (mut vectors, tokens) = tokio::select! {
372            _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
373            r = call => r?,
374        };
375        Ok((vectors.pop().ok_or_else(|| engine_error("no embedding"))?, Some(tokens)))
376    }
377}
378
379#[async_trait]
380impl TranscribeBackend for EngineModel {
381    fn name(&self) -> String {
382        self.id.clone()
383    }
384
385    async fn transcribe(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<Transcript, RemoteError> {
386        Ok(self.transcribe_counted(request, cancel).await?.0)
387    }
388
389    /// The transcript and the engine's token counts ([`Supervisor::transcribe`](crate::Supervisor::transcribe)).
390    async fn transcribe_counted(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<(Transcript, Option<Usage>), RemoteError> {
391        self.ready().await?;
392        tokio::select! {
393            _ = cancel.cancelled() => Err(RemoteError::Cancelled),
394            r = self.supervisor.transcribe(&self.id, request) => r,
395        }
396    }
397}
398
399#[async_trait]
400impl SpeakBackend for EngineModel {
401    fn name(&self) -> String {
402        self.id.clone()
403    }
404
405    /// The speech from [`Supervisor::speak`](crate::Supervisor::speak), loading the model first
406    /// when it was picked cold. Cancelling stops the engine request.
407    async fn speak(&self, request: &SpeakRequest, cancel: &CancelToken) -> Result<AudioStream, RemoteError> {
408        tokio::select! {
409            _ = cancel.cancelled() => return Err(RemoteError::Cancelled),
410            r = self.ready() => r?,
411        }
412        tokio::select! {
413            _ = cancel.cancelled() => Err(RemoteError::Cancelled),
414            r = self.supervisor.speak(&self.id, request) => r,
415        }
416    }
417}
418
419/// The protocol id model nodes serve raw infer on: the `/weirdnet-agent/infer/2` framing under
420/// its own id, so one node can be an inference node (which serves infer/2 to apps) and a model
421/// node at once. `NodeServer` (`node` feature) always serves it; [`RawInferDialer`] prefers it.
422pub const RAW_INFER_PROTOCOL: &str = "/weirdnet-backends/infer/1";
423
424/// A [`Dialer`] for inference nodes talking to model nodes: opening
425/// `/weirdnet-agent/infer/2` tries [`RAW_INFER_PROTOCOL`] first and falls back to infer/2 on
426/// nodes that don't accept it (backends 0.1.0). Nodes that fell back are remembered. Other
427/// protocols pass through. Wrap the dialer given to the `Pool` of model nodes.
428pub struct RawInferDialer {
429    inner: Arc<dyn Dialer>,
430    legacy: Mutex<std::collections::HashSet<String>>,
431}
432
433impl RawInferDialer {
434    pub fn new(inner: Arc<dyn Dialer>) -> Self {
435        Self { inner, legacy: Mutex::new(Default::default()) }
436    }
437
438    /// Whether `node` answered only on infer/2.
439    pub fn is_legacy(&self, node: &str) -> bool {
440        self.legacy.lock().unwrap_or_else(|e| e.into_inner()).contains(node)
441    }
442}
443
444#[async_trait]
445impl Dialer for RawInferDialer {
446    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
447        if protocol != v2::PROTOCOL {
448            return self.inner.open(node, protocol).await;
449        }
450        if !self.is_legacy(node) {
451            match self.inner.open(node, RAW_INFER_PROTOCOL).await {
452                Err(RemoteError::Unsupported { .. }) => {}
453                other => return other,
454            }
455        }
456        let ch = self.inner.open(node, v2::PROTOCOL).await?;
457        self.legacy.lock().unwrap_or_else(|e| e.into_inner()).insert(node.to_string());
458        Ok(ch)
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465
466    #[test]
467    fn speed_is_smoothed() {
468        let mut s = Speed::default();
469        s.record(Some(0.5), 1.5, 100, 11);
470        assert_eq!((s.ttft_ms, s.prefill_tps, s.decode_tps), (Some(500), Some(200.0), Some(10.0)));
471        s.record(Some(0.5), 0.5, 100, 11);
472        assert_eq!(s.decode_tps, Some(10.0), "no decode time: unchanged");
473    }
474}