use super::{ENTRIES, Entry, describe, entries, 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};
const GUIDED: bool = cfg!(feature = "guided");
const RESULT: usize = 2000;
const AFTER: &str = "Tell me the result of that task in a sentence or two.";
const HUB_EXAMPLE: (&str, &str) = ("run llama 3.2 1b from Hugging Face", "llama 3.2 1b");
#[derive(Task)]
struct Route {
yes: bool,
#[arg(value = "<n>")]
max_tokens: Option<usize>,
#[arg(positional)]
request: String,
}
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
}
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
}
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 })
}
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 })
}
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
}
pub(super) 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);
}
}
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))
}
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")
}
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
}
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()],
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))
}
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
}
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())
}
pub fn chat(args: &[String]) -> Result<(), Stop> {
if args.iter().any(|a| a == "--script") {
return super::agent::chat(args);
}
let chat = Chat::parse(args, &|_| None).map_err(|_| Stop::Usage)?;
let mut session = Session::open(chat.max_tokens, false)?;
let mut print = super::terminal();
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(())
}
pub(super) struct Session {
pub slot: Slot,
progress: Progress,
scope: Arc<Scope>,
pub max_tokens: Option<usize>,
yes: bool,
pub token: Option<String>,
pub catalog: Vec<Recipe>,
history: Vec<Message>,
}
impl Session {
pub(super) fn open(max_tokens: Option<usize>, yes: bool) -> Result<Self, Stop> {
let scope = Arc::new(Scope::default());
let progress = super::terminal().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(),
})
}
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()
}
pub(super) fn entry(pick: &Value) -> Result<&'static Entry, Stop> {
let name = pick.get("tool").and_then(Value::as_str).unwrap_or_default();
let entry = ENTRIES.iter().find(|e| e.name == name);
entry.ok_or_else(|| Stop::Failed(format!("the model picked {pick}")))
}
pub(super) fn execute(&self, pick: &Value, args: &[String]) -> Result<Option<Value>, Stop> {
let entry = Self::entry(pick)?;
let knobs = knobs(pick);
if !confirm(&knobs, args, self.yes)? {
return Ok(None);
}
if entry.stays {
return replace(&knobs, args).map(|()| Some(Value::Null));
}
let (origin, words) = source::split(args)?;
let rest = words.get(entry.words().len()..).unwrap_or_default();
let mut out = Both {
print: super::terminal(),
collect: Collect::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)?;
Ok(Some(match called {
Ok(()) => out.collect.value(),
Err(e) => json!({ "error": describe(&e) }),
}))
}
fn call(&mut self, pick: &Value, args: &[String]) -> Result<bool, Stop> {
let Some(result) = self.execute(pick, args)? else {
return Ok(false);
};
let name = pick.get("tool").and_then(Value::as_str).unwrap_or_default();
let mut arguments = pick.clone();
if let Value::Object(fields) = &mut arguments {
fields.remove("tool");
}
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)
}
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 = super::terminal();
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(())
}
}
struct Both {
print: Box<dyn Sink>,
collect: Collect,
}
impl Sink for Both {
fn progress(&self) -> Progress {
self.print.progress()
}
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);
}
}
const ITEMS: usize = 8;
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(),
}
}
fn short(result: &Value) -> String {
let text = brief(result).to_string();
match text.char_indices().nth(RESULT) {
Some((at, _)) => format!("{}…", &text[..at]),
None => text,
}
}
pub(super) 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(", ")),
};
super::terminal().note(&format!(
"{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)?;
super::terminal().note(&format!(
"{words:?} is {id} on Hugging Face, not in the model catalog (untested)"
));
Ok(vec!["--model".into(), format!("hf:{id}")])
}
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" })))
}
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));
let command = shown.join(" ");
if !yes && let Some(answer) = super::terminal().confirm(&command) {
return Ok(answer);
}
super::terminal().note(&format!("the model picked `{command}`"));
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"))
}
#[cfg(unix)]
fn replace(knobs: &[(String, String)], args: &[String]) -> Result<(), Stop> {
use std::os::unix::process::CommandExt;
super::leave();
Err(Stop::Failed(command(knobs, args)?.exec().to_string()))
}
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}"))),
}
}