tessera-command 0.4.18

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! A prompt or chat turn: a reply or a task.

use super::{ENTRIES, Entry, Print, describe, load, model};
use crate::source::{self, Source, Stop, kind};
use serde_json::{Map, Value, json};
use std::io::{BufRead, IsTerminal};
use std::sync::Arc;
use tessera_frontend::chat::{FunctionCall, Message, ToolCall};
use tessera_engine::progress::{Progress, Scope, Unit};
use tessera_frontend::frontend_settings::{KNOBS, knob_var};
use tessera_frontend::recipe::{Catalog, Recipe};
use tessera_frontend::serve::{Model, Slot};
use tessera_frontend::tasks::api::Format;
use tessera_frontend::tasks::task::{Chat, Collect, Sink, Task};

/// Whether this build can hold answers to a JSON schema.
const GUIDED: bool = cfg!(feature = "guided");

/// The most characters of a task's result the model reads.
const RESULT: usize = 2000;

/// The turn that asks for an answer from a result.
const AFTER: &str = "Tell me the result of that task in a sentence or two.";

/// A request for an outside model, and its words.
const HUB_EXAMPLE: (&str, &str) = ("run llama 3.2 1b from Hugging Face", "llama 3.2 1b");

/// Answer a prompt, or run the command the model picks.
#[derive(Task)]
struct Route {
    /// Run the picked command without asking.
    yes: bool,
    /// The most tokens in a reply.
    #[arg(value = "<n>")]
    max_tokens: Option<usize>,
    /// The request, from stdin if none.
    #[arg(positional)]
    request: String,
}

/// Catalog names of `kind`, or every name.
fn names(catalog: &[Recipe], of: Option<&str>) -> Vec<String> {
    let mut out = Vec::new();
    for r in catalog {
        if of.is_none_or(|k| k == kind(r)) {
            out.push(r.name.clone());
        }
    }
    out
}

/// Entries with an example and a catalog model to run.
pub fn tools(catalog: &[Recipe]) -> Vec<&'static Entry> {
    let mut out = Vec::new();
    for e in &ENTRIES {
        if e.example.is_some() && (!e.source || !names(catalog, e.kind).is_empty()) {
            out.push(e);
        }
    }
    out
}

/// JSON for a reply, or a tool and its arguments.
pub fn schema(catalog: &[Recipe], tools: &[&Entry]) -> Value {
    let only = |word: &str| json!({ "enum": [word] });
    let mut branches = vec![json!({
        "type": "object",
        "properties": { "tool": only("reply") },
        "required": ["tool"],
        "additionalProperties": false,
    })];
    for t in tools {
        if !t.source {
            branches.push(branch(t, None));
            continue;
        }
        let words = json!({ "type": "string", "minLength": 2, "maxLength": 60 });
        let models = json!({ "enum": names(catalog, t.kind) });
        for (key, value) in [("model", models), ("hub", words)] {
            branches.push(branch(t, Some((key, value))));
        }
    }
    json!({ "anyOf": branches })
}

/// The optional `knobs` object, with a value pattern per knob.
fn knobs_schema() -> Value {
    let mut props = Map::new();
    for k in &KNOBS {
        props.insert(
            k.name.into(),
            json!({ "type": "string", "pattern": k.pattern }),
        );
    }
    json!({ "type": "object", "properties": props, "additionalProperties": false })
}

/// Tool `t` with its model, knobs and arguments.
fn branch(t: &Entry, model: Option<(&str, Value)>) -> Value {
    let mut schema = (t.schema)();
    let mut props = Map::new();
    props.insert("tool".into(), json!({ "enum": [t.name] }));
    let mut required = vec![json!("tool")];
    if let Some((key, model)) = model {
        props.insert(key.into(), model);
        required.push(json!(key));
    }
    props.insert("knobs".into(), knobs_schema());
    if let Value::Object(args) = schema["properties"].take() {
        props.extend(args);
    }
    if let Value::Array(args) = schema["required"].take() {
        required.extend(args);
    }
    schema["properties"] = Value::Object(props);
    schema["required"] = Value::Array(required);
    schema
}

/// `t`'s example request, and the pick it makes.
fn example(catalog: &[Recipe], t: &Entry) -> (String, Value) {
    let asked = t.example.unwrap_or_default();
    if !t.source {
        let mut pick = json!({ "tool": t.name });
        if let (Value::Object(fields), Value::Object(args)) = (&mut pick, (t.example_args)()) {
            fields.extend(args);
        }
        return (asked.into(), pick);
    }
    let mut models: Vec<&Recipe> = Vec::new();
    for r in catalog {
        if t.kind.is_none_or(|k| k == kind(r)) {
            models.push(r);
        }
    }
    // A request by kind names the last model.
    let by_kind = asked.contains("{kind}");
    let recipe = if by_kind {
        models.last()
    } else {
        models.first()
    };
    let Some(recipe) = recipe else {
        return (asked.into(), json!({ "tool": "reply" }));
    };
    let model = recipe.name.clone();
    let mut pick = Map::new();
    pick.insert("tool".into(), t.name.into());
    pick.insert("model".into(), model.clone().into());
    if let Value::Object(args) = (t.example_args)() {
        pick.extend(args);
    }
    let asked = asked.replace("{kind}", kind(recipe));
    (asked.replace("{model}", &model), Value::Object(pick))
}

/// The routing prompt for `request`.
pub fn prompt(catalog: &[Recipe], known: &Catalog, tools: &[&Entry], request: &str) -> String {
    let mut out = String::from("Turn the request into one tesserax command, as JSON.\nTools:\n");
    out += "- reply: answer in text. Use it for questions, chat and anything else.\n";
    for t in tools {
        let mut args = Vec::new();
        if t.source {
            args.push("model or hub".to_string());
        }
        if let Value::Object(props) = &(t.schema)()["properties"] {
            args.extend(props.keys().cloned());
        }
        out += &format!("- {} ({}): {}\n", t.name, args.join(", "), t.about);
    }
    out += "Models:\n";
    for r in catalog {
        let about = r.about.as_deref().unwrap_or_default();
        out += &format!("- {} ({}): {about}\n", r.name, kind(r));
    }
    for family in &known.families {
        if catalog.iter().all(|r| r.name != family.family) {
            out += &format!("- {} (also {})\n", family.family, family.aliases.join(", "));
        }
    }
    out += "model is a name from this list. For any other model, hub holds the words\n";
    out += "the request uses for it, and tesserax finds it on Hugging Face.\n";
    out += "A request for a kind of model, such as an image model, takes model.\n";
    out += "knobs is optional. Set a knob only when the request asks for it:\n";
    for k in &KNOBS {
        out += &format!("- {}: {}\n", k.name, k.about);
    }
    out += "Request: what is the capital of France?\n{\"tool\":\"reply\"}\n";
    for t in tools {
        let (asked, pick) = example(catalog, t);
        out += &format!("Request: {asked}\n{pick}\n");
    }
    if let Some(serve) = tools.iter().find(|t| t.kind == Some("generate")) {
        let pick = json!({ "tool": serve.name, "hub": HUB_EXAMPLE.1 });
        out += &format!("Request: {}\n{pick}\n", HUB_EXAMPLE.0);
        let (_, mut pick) = example(catalog, serve);
        if let Some(model) = pick["model"].as_str().map(str::to_string) {
            pick["knobs"] = json!({ "profile": "1" });
            out += &format!("Request: profile the {model} boot\n{pick}\n");
        }
    }
    out + &format!("Request: {request}\n")
}

/// The catalog model that words such as "image model" name.
fn by_kind<'a>(catalog: &'a [Recipe], words: &str) -> Option<&'a str> {
    if let Some(r) = catalog.iter().find(|r| r.name == words.trim()) {
        return Some(&r.name);
    }
    let mut named = Vec::new();
    for word in words.split_whitespace() {
        let word = word.to_lowercase();
        if !["a", "an", "the", "model", "models"].contains(&word.as_str()) {
            named.push(word);
        }
    }
    let [word] = named.as_slice() else {
        return None;
    };
    for r in catalog {
        let k = kind(r);
        if word.starts_with(k) || k.starts_with(word.as_str()) {
            return Some(&r.name);
        }
    }
    None
}

/// Arguments for `pick`, or `None` for a reply.
pub fn argv(
    pick: &Value,
    catalog: &[Recipe],
    find: impl Fn(&str) -> Result<Vec<String>, Stop>,
) -> Result<Option<Vec<String>>, Stop> {
    let field = |k: &str| pick.get(k).and_then(Value::as_str);
    let bad = || Stop::Failed(format!("the model picked {pick}"));
    let name = field("tool").ok_or_else(bad)?;
    if name == "reply" {
        return Ok(None);
    }
    let tool = ENTRIES
        .iter()
        .find(|t| t.name == name && t.example.is_some());
    let tool = tool.ok_or_else(bad)?;
    let mut out = match (field("model"), field("hub")) {
        _ if !tool.source => Vec::new(),
        (Some(model), _) if catalog.iter().any(|r| r.name == model) => {
            vec!["--recipe".to_string(), model.to_string()]
        }
        (_, Some(hub)) => match by_kind(catalog, hub) {
            Some(name) => vec!["--recipe".to_string(), name.to_string()],
            // `find` turns outside words into a Hub id.
            None => find(hub)?,
        },
        (Some(model), None) => find(model)?,
        _ => return Err(bad()),
    };
    out.extend(tool.words());
    let mut args = pick.as_object().cloned().unwrap_or_default();
    for key in ["tool", "model", "hub", "knobs"] {
        args.remove(key);
    }
    let args = (tool.tool_args)(&Value::Object(args));
    out.extend(args.map_err(|e| Stop::Failed(format!("the model picked {pick}: {e}")))?);
    Ok(Some(out))
}

/// The knobs in `pick`, as names and values.
pub fn knobs(pick: &Value) -> Vec<(String, String)> {
    let mut out = Vec::new();
    if let Some(Value::Object(set)) = pick.get("knobs") {
        for (name, value) in set {
            if let Some(value) = value.as_str() {
                out.push((name.clone(), value.to_string()));
            }
        }
    }
    out
}

/// Answers `words`, or runs the task the default model picks.
pub fn run(words: &[String]) -> Result<(), Stop> {
    let route = Route::parse(words, &|_| None).map_err(|_| Stop::Usage)?;
    let mut session = Session::open(route.max_tokens, route.yes)?;
    session.turn(route.request.trim())
}

/// `task chat` without a model flag. Turns may run tasks.
pub fn chat(args: &[String]) -> Result<(), Stop> {
    let chat = Chat::parse(args, &|_| None).map_err(|_| Stop::Usage)?;
    let mut session = Session::open(chat.max_tokens, false)?;
    let mut print = Print::default();
    while let Some(line) = print.turn() {
        let line = line.trim();
        if line.is_empty() {
            break;
        }
        let mark = session.history.len();
        if let Err(e) = session.turn(line) {
            session.history.truncate(mark);
            print.note(&describe(&e));
        }
    }
    Ok(())
}

/// The default model, the chat so far, and settings.
struct Session {
    slot: Slot,
    /// One sink for load, picks and kernel builds.
    progress: Progress,
    /// Where kernel builds nest while a command is picked.
    scope: Arc<Scope>,
    max_tokens: Option<usize>,
    yes: bool,
    token: Option<String>,
    catalog: Vec<Recipe>,
    history: Vec<Message>,
}

impl Session {
    fn open(max_tokens: Option<usize>, yes: bool) -> Result<Self, Stop> {
        let scope = Arc::new(Scope::default());
        let progress = Print::default().progress().within(scope.clone());
        let source = Source::open_or_kind(None, None, progress.clone())?;
        let switches: &[String] = if GUIDED { &["--guided".into()] } else { &[] };
        let mut options = source.options(switches)?;
        options.slots = 1;
        options.warm = false;
        Ok(Session {
            slot: load(options)?,
            progress,
            scope,
            max_tokens,
            yes,
            token: source.token.clone(),
            catalog: source::catalog(),
            history: Vec::new(),
        })
    }

    /// One request: a reply, or a task, then a reply.
    fn turn(&mut self, request: &str) -> Result<(), Stop> {
        let pick = match GUIDED {
            true => {
                let step = self
                    .progress
                    .step("picking a command...", Unit::Items, None);
                self.scope.enter(&step);
                let pick = pick(model(&self.slot), self.max_tokens, request);
                self.scope.clear();
                step.rename("picked a command");
                step.finish();
                pick?
            }
            false => json!({ "tool": "reply" }),
        };
        let token = self.token.as_deref();
        let args = argv(&pick, &self.catalog, |words| find(words, token))?;
        self.history.push(Message::text("user", request));
        if let Some(args) = args
            && !self.call(&pick, &args)?
        {
            self.history.pop();
            return Ok(());
        }
        self.reply()
    }

    /// Runs the picked task. `false` when the person declines.
    fn call(&mut self, pick: &Value, args: &[String]) -> Result<bool, Stop> {
        let name = pick.get("tool").and_then(Value::as_str).unwrap_or_default();
        let entry = ENTRIES.iter().find(|e| e.name == name);
        let entry = entry.ok_or_else(|| Stop::Failed(format!("the model picked {pick}")))?;
        let knobs = knobs(pick);
        if !confirm(&knobs, args, self.yes)? {
            return Ok(false);
        }
        if entry.stays {
            return replace(&knobs, args).map(|()| true);
        }
        let (origin, words) = source::split(args)?;
        let rest = words.get(entry.words().len()..).unwrap_or_default();
        let mut out = Both::default();
        tessera_frontend::frontend_settings::knobs(&knobs).map_err(Stop::Failed)?;
        let called = (entry.call)(origin, rest, &mut out);
        tessera_frontend::frontend_settings::knobs(&[]).map_err(Stop::Failed)?;
        let result = match called {
            Ok(()) => out.collect.value(),
            Err(e) => json!({ "error": describe(&e) }),
        };
        let mut arguments = pick.clone();
        if let Value::Object(fields) = &mut arguments {
            fields.remove("tool");
        }
        // The call and its result join the chat.
        let id = format!("call_{}", self.history.len());
        let call = ToolCall {
            id: Some(id.clone()),
            kind: "function".into(),
            function: FunctionCall {
                name: name.into(),
                arguments,
            },
        };
        self.history.push(Message {
            role: "assistant".into(),
            tool_calls: Some(vec![call]),
            ..Message::default()
        });
        self.history.push(Message {
            role: "tool".into(),
            content: Some(short(&result)),
            tool_call_id: Some(id),
            name: Some(name.into()),
            ..Message::default()
        });
        self.history.push(Message::text("user", AFTER));
        Ok(true)
    }

    /// Prints the model's answer to the chat so far.
    fn reply(&mut self) -> Result<(), Stop> {
        let model = model(&self.slot);
        let failed = |e: tessera_frontend::tasks::Error| Stop::Failed(e.to_string());
        let text = model.render(&self.history).map_err(failed)?;
        let mut print = Print::default();
        let answer = model.answer(&text, self.max_tokens, None, &mut |t| print.text(t));
        let answer = answer.map_err(failed)?;
        self.history.push(Message::text("assistant", answer.trim()));
        Ok(())
    }
}

/// Output for the person, also kept for the model.
#[derive(Default)]
struct Both {
    print: Print,
    collect: Collect,
}

impl Sink for Both {
    fn text(&mut self, piece: &str) {
        self.print.text(piece);
        self.collect.text(piece);
    }

    fn record(&mut self, record: Value) {
        self.print.record(record.clone());
        self.collect.record(record);
    }

    fn file(&mut self, path: &std::path::Path) {
        self.print.file(path);
        self.collect.file(path);
    }

    fn note(&mut self, text: &str) {
        self.print.note(text);
        self.collect.note(text);
    }
}

/// The most items of a list the model reads.
const ITEMS: usize = 8;

/// `value` with long lists cut to [`ITEMS`] and a count.
pub(crate) fn brief(value: &Value) -> Value {
    match value {
        Value::Array(items) if items.len() > ITEMS => {
            let mut out: Vec<Value> = items[..ITEMS].iter().map(brief).collect();
            let rest = items.len() - ITEMS;
            out.push(json!(format!("{rest} more, {} in all", items.len())));
            Value::Array(out)
        }
        Value::Array(items) => Value::Array(items.iter().map(brief).collect()),
        Value::Object(fields) => {
            let fields = fields.iter().map(|(k, v)| (k.clone(), brief(v)));
            Value::Object(fields.collect())
        }
        other => other.clone(),
    }
}

/// The result text the model reads, cut at [`RESULT`].
fn short(result: &Value) -> String {
    let text = brief(result).to_string();
    match text.char_indices().nth(RESULT) {
        Some((at, _)) => format!("{}…", &text[..at]),
        None => text,
    }
}

/// Model arguments for `words`: catalog family or Hub id.
fn find(words: &str, token: Option<&str>) -> Result<Vec<String>, Stop> {
    let words = words.trim();
    if !words.starts_with("hf:")
        && let Some(family) = Catalog::current().find(words)
    {
        let (pick, recipe) = source::choose(&family.family)?;
        let size = source::gb(pick.needs.bytes);
        let tested = match pick.tested.is_empty() {
            true => "no test on record".to_string(),
            false => format!("tested on {}", pick.tested.join(", ")),
        };
        eprintln!(
            "tesserax: {words:?} is {} from the model catalog: {} ({size:.1} GB, {tested})",
            family.family,
            recipe.weights.hf.as_deref().unwrap_or_default(),
        );
        return Ok(vec![
            "--recipe".into(),
            format!("{}{}", source::CATALOG_PREFIX, family.family),
        ]);
    }
    let words = words.trim_start_matches("hf:");
    if words.contains('/') && !words.contains(' ') {
        tessera_frontend::recipe::check_hf(words, token)?;
        return Ok(vec!["--model".into(), format!("hf:{words}")]);
    }
    let found = tessera_frontend::recipe::search_hf(words, token)?;
    let none = || {
        Stop::Failed(format!(
            "the Hugging Face search for {words:?} found nothing"
        ))
    };
    let id = found.ok_or_else(none)?;
    eprintln!("tesserax: {words:?} is {id} on Hugging Face, not in the model catalog (untested)");
    Ok(vec!["--model".into(), format!("hf:{id}")])
}

/// The default model's pick. A bad pick is a reply.
fn pick(model: &Model, max_tokens: Option<usize>, request: &str) -> Result<Value, Stop> {
    let catalog = source::catalog();
    let tools = tools(&catalog);
    let known = Catalog::current();
    let user = Message::text("user", prompt(&catalog, known, &tools, request));
    let format = Some(Format::Schema(schema(&catalog, &tools)));
    let failed = |e: tessera_frontend::tasks::Error| Stop::Failed(e.to_string());
    let text = model.render(&[user]).map_err(failed)?;
    let json = model.answer(&text, max_tokens, format, &mut |_| {});
    let json = json.map_err(failed)?;
    Ok(serde_json::from_str(json.trim()).unwrap_or_else(|_| json!({ "tool": "reply" })))
}

/// Shows the command. Asks on a terminal, fails without one.
fn confirm(knobs: &[(String, String)], args: &[String], yes: bool) -> Result<bool, Stop> {
    let quoted = |a: &String| match a.contains(' ') {
        true => format!("{a:?}"),
        false => a.clone(),
    };
    let mut shown: Vec<String> = knobs
        .iter()
        .map(|(k, v)| format!("{}={v}", knob_var(k)))
        .collect();
    shown.push("tesserax".into());
    shown.extend(args.iter().map(quoted));
    eprintln!("tesserax: the model picked `{}`", shown.join(" "));
    let stdin = std::io::stdin();
    if yes {
        return Ok(true);
    }
    if !stdin.is_terminal() {
        return Err(Stop::Failed(
            "no terminal to confirm the command, pass --yes to run it".into(),
        ));
    }
    eprint!("run it? [y/N] ");
    let mut line = String::new();
    stdin
        .lock()
        .read_line(&mut line)
        .map_err(|e| Stop::Failed(e.to_string()))?;
    Ok(matches!(line.trim(), "y" | "Y" | "yes"))
}

/// Replaces this process with tesserax `args` to free the model.
#[cfg(unix)]
fn replace(knobs: &[(String, String)], args: &[String]) -> Result<(), Stop> {
    use std::os::unix::process::CommandExt;
    Err(Stop::Failed(command(knobs, args)?.exec().to_string()))
}

/// Tesserax with `args`, and `knobs` in its environment.
fn command(knobs: &[(String, String)], args: &[String]) -> Result<std::process::Command, Stop> {
    let exe = std::env::current_exe().map_err(|e| Stop::Failed(e.to_string()))?;
    let mut command = std::process::Command::new(exe);
    command.args(args);
    for (name, value) in knobs {
        command.env(knob_var(name), value);
    }
    Ok(command)
}

#[cfg(not(unix))]
fn replace(knobs: &[(String, String)], args: &[String]) -> Result<(), Stop> {
    let status = command(knobs, args)?.status();
    let status = status.map_err(|e| Stop::Failed(e.to_string()))?;
    match status.success() {
        true => Ok(()),
        false => Err(Stop::Failed(format!("the picked command failed: {status}"))),
    }
}