tessera-command 0.5.3

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
//! `serve`: answer OpenAI-shaped requests.

use crate::source::Source;
use std::sync::{Arc, Mutex};
use tessera_frontend::tasks::Error;
use tessera_frontend::tasks::api::watch::{self, End, Watch};
use tessera_frontend::tasks::task::{Run, Sink, Task};

/// Start or run a text model as an OpenAI-compatible server.
#[derive(Task)]
#[task(kind = "generate", example = "start {model} as a server")]
pub(crate) struct Serve {
    /// Flags for the server and the model load.
    #[arg(extra)]
    pub flags: Vec<String>,
}

impl Run<Source> for Serve {
    fn run(self, source: Source, _: &mut dyn Sink) -> Result<(), Error> {
        let options = source.options(&self.flags)?;
        // No-op when the Tern views already watch.
        let progress = options.progress.clone();
        watch::set(Arc::new(Lines {
            runs: Mutex::default(),
            print: Box::new(move |line| progress.note(line)),
        }));
        Ok(tessera_frontend::serve::start::run(options)?)
    }
}

crate::task::register!(Serve, crate::task::OnSource, "", true);

/// A line for each finished request, through the load's progress.
pub(crate) struct Lines {
    pub(crate) runs: Mutex<Vec<Arc<watch::Run>>>,
    pub(crate) print: Box<dyn Fn(&str) + Send + Sync>,
}

impl Watch for Lines {
    fn bound(&self, _addr: std::net::SocketAddr, _connections: usize) {}
    fn ready(&self, _model: &str, _seconds: f64) {}
    fn began(&self, run: Arc<watch::Run>) {
        self.runs.lock().expect("the request lines lock").push(run);
    }
    fn ended(&self) {
        let mut runs = self.runs.lock().expect("the request lines lock");
        let mut i = 0;
        while i < runs.len() {
            if runs[i].end().is_some() {
                let run = runs.remove(i);
                (self.print)(&line(&run));
            } else {
                i += 1;
            }
        }
    }
}

/// One finished request as words.
pub(crate) fn line(run: &watch::Run) -> String {
    let (end, end_kind) = run.end().expect("a finished run");
    let mut out = format!(
        "{} {} {} {}→{} tokens",
        run.name,
        run.route,
        run.model,
        run.prompt,
        run.tokens()
    );
    if run.cached() > 0 {
        out.push_str(&format!(" ({} cached)", run.cached()));
    }
    if let Some(first) = run.first() {
        let ms = first.duration_since(run.started).as_millis();
        out.push_str(&format!(", first {ms} ms"));
        let secs = end.duration_since(first).as_secs_f64();
        if secs > 0.0 {
            let toks = run.tokens() as f64;
            out.push_str(&format!(", {:.1} tok/s", toks / secs));
        }
    }
    let label = match end_kind {
        End::Stop => "stop",
        End::Length => "length",
        End::Early => "ended early",
    };
    out.push_str(&format!(", {label}"));
    out
}