Skip to main content

cortiq_engine/
tools.rs

1//! Built-in tools: exact functions the engine runs itself when a model calls
2//! them in the Hermes function-calling contract of the Embryo cores
3//! (`<tool_call>{"name": …, "arguments": …}</tool_call>` in an assistant
4//! turn, the result back as `<tool_response>…</tool_response>` in a `tool`
5//! turn). A small model fills the call's fields the way it fills a card's
6//! placeholders; the counting and the arithmetic, which it does badly, are
7//! done here, exactly.
8//!
9//! - `calc`: an expression over exact rationals (`i128` numerator and
10//!   denominator, overflow is an error, never a rounded result): `+ - * / % ^`,
11//!   parentheses, `sum min max mean abs round floor ceil`.
12//! - `table`: the last command output read as a [`Table`]: `count sum min max
13//!   mean get argmax argmin diff` over a column, with a row-name filter
14//!   (`rows`) and a cell test (`where`).
15//!
16//! [`round`] runs the calls of one assistant turn when every one of them is
17//! built in and renders the tool turns that follow it; the server loops on it
18//! (`/v1/completions` with `builtin_tools`). The descriptions the model is
19//! shown are `tools.json` ([`descriptions`]); the trace generators read the
20//! same file.
21
22use serde_json::Value;
23use std::cmp::Ordering;
24
25/// The model-facing descriptions (`{"name", "description", "parameters"}`).
26pub const TOOLS_JSON: &str = include_str!("tools.json");
27
28pub fn descriptions() -> Vec<Value> {
29    serde_json::from_str(TOOLS_JSON).expect("tools.json is valid JSON")
30}
31
32pub fn is_builtin(name: &str) -> bool {
33    matches!(name, "calc" | "table")
34}
35
36/// Runs a built-in tool. `input` is the text `table` reads (see
37/// [`last_output`]); `calc` ignores it.
38pub fn call(name: &str, args: &Value, input: &str) -> Result<String, String> {
39    match name {
40        "calc" => {
41            let e = args
42                .get("expression")
43                .or_else(|| args.get("expr"))
44                .and_then(Value::as_str)
45                .ok_or("calc needs an expression")?;
46            Ok(calc(e)?.show())
47        }
48        "table" => table(args, input),
49        other => Err(format!("{other} is not a built-in tool")),
50    }
51}
52
53// ---------------------------------------------------------------- rationals
54
55/// An exact rational: `n / d`, `d > 0`, reduced.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct Q {
58    n: i128,
59    d: i128,
60}
61
62fn gcd(mut a: i128, mut b: i128) -> i128 {
63    a = a.abs();
64    b = b.abs();
65    while b != 0 {
66        (a, b) = (b, a % b);
67    }
68    a
69}
70
71const OVERFLOW: &str = "the number is too large for exact arithmetic";
72
73impl Q {
74    pub fn int(n: i128) -> Q {
75        Q { n, d: 1 }
76    }
77
78    pub fn new(n: i128, d: i128) -> Result<Q, String> {
79        if d == 0 {
80            return Err("division by zero".into());
81        }
82        let g = gcd(n, d).max(1);
83        let (mut n, mut d) = (n / g, d / g);
84        if d < 0 {
85            n = n.checked_neg().ok_or(OVERFLOW)?;
86            d = d.checked_neg().ok_or(OVERFLOW)?;
87        }
88        Ok(Q { n, d })
89    }
90
91    fn add(self, o: Q) -> Result<Q, String> {
92        let n = self
93            .n
94            .checked_mul(o.d)
95            .and_then(|a| o.n.checked_mul(self.d).and_then(|b| a.checked_add(b)))
96            .ok_or(OVERFLOW)?;
97        Q::new(n, self.d.checked_mul(o.d).ok_or(OVERFLOW)?)
98    }
99
100    fn neg(self) -> Result<Q, String> {
101        Ok(Q { n: self.n.checked_neg().ok_or(OVERFLOW)?, d: self.d })
102    }
103
104    fn sub(self, o: Q) -> Result<Q, String> {
105        self.add(o.neg()?)
106    }
107
108    fn mul(self, o: Q) -> Result<Q, String> {
109        let g1 = gcd(self.n, o.d).max(1);
110        let g2 = gcd(o.n, self.d).max(1);
111        let n = (self.n / g1).checked_mul(o.n / g2).ok_or(OVERFLOW)?;
112        let d = (self.d / g2).checked_mul(o.d / g1).ok_or(OVERFLOW)?;
113        Q::new(n, d)
114    }
115
116    fn div(self, o: Q) -> Result<Q, String> {
117        if o.n == 0 {
118            return Err("division by zero".into());
119        }
120        self.mul(Q::new(o.d, o.n)?)
121    }
122
123    fn floor(self) -> Q {
124        Q::int(self.n.div_euclid(self.d))
125    }
126
127    fn ceil(self) -> Q {
128        let f = self.n.div_euclid(self.d);
129        Q::int(if f * self.d == self.n { f } else { f + 1 })
130    }
131
132    fn rem(self, o: Q) -> Result<Q, String> {
133        if o.n == 0 {
134            return Err("modulo by zero".into());
135        }
136        self.sub(o.mul(self.div(o)?.floor())?)
137    }
138
139    fn pow(self, e: Q) -> Result<Q, String> {
140        if e.d != 1 {
141            return Err("the exponent must be a whole number".into());
142        }
143        if e.n.abs() > 256 {
144            return Err(OVERFLOW.into());
145        }
146        let mut r = Q::int(1);
147        for _ in 0..e.n.abs() {
148            r = r.mul(self)?;
149        }
150        if e.n < 0 { Q::int(1).div(r) } else { Ok(r) }
151    }
152
153    fn abs(self) -> Q {
154        Q { n: self.n.abs(), d: self.d }
155    }
156
157    /// Half away from zero to `digits` decimals.
158    fn round(self, digits: i128) -> Result<Q, String> {
159        if !(0..=18).contains(&digits) {
160            return Err("round takes 0 to 18 decimals".into());
161        }
162        let s = 10i128.pow(digits as u32);
163        let x = self.mul(Q::int(s))?;
164        let half = Q::new(1, 2)?;
165        let r = if x.n >= 0 { x.add(half)?.floor() } else { x.neg()?.add(half)?.floor().neg()? };
166        r.div(Q::int(s))
167    }
168
169    fn to_f64(self) -> f64 {
170        self.n as f64 / self.d as f64
171    }
172
173    /// An integer as itself, a finite decimal exactly, any other fraction as
174    /// `n/d ≈ decimal`.
175    pub fn show(self) -> String {
176        if self.d == 1 {
177            return self.n.to_string();
178        }
179        let (mut d, mut k2, mut k5) = (self.d, 0u32, 0u32);
180        while d % 2 == 0 {
181            d /= 2;
182            k2 += 1;
183        }
184        while d % 5 == 0 {
185            d /= 5;
186            k5 += 1;
187        }
188        let k = k2.max(k5);
189        if d == 1 && k <= 30 {
190            if let Some(scaled) = 10i128.checked_pow(k).and_then(|p| self.n.checked_mul(p / self.d)) {
191                let neg = scaled < 0;
192                let digits = scaled.unsigned_abs().to_string();
193                let digits = format!("{digits:0>width$}", width = k as usize + 1);
194                let (int, frac) = digits.split_at(digits.len() - k as usize);
195                let frac = frac.trim_end_matches('0');
196                return format!("{}{int}{}{frac}", if neg { "-" } else { "" }, if frac.is_empty() { "" } else { "." });
197            }
198        }
199        format!("{}/{} ≈ {}", self.n, self.d, trim_f64(self.to_f64()))
200    }
201}
202
203fn trim_f64(x: f64) -> String {
204    let s = format!("{x:.10}");
205    let s = s.trim_end_matches('0').trim_end_matches('.');
206    s.to_string()
207}
208
209impl PartialOrd for Q {
210    fn partial_cmp(&self, o: &Q) -> Option<Ordering> {
211        Some(self.cmp(o))
212    }
213}
214
215impl Ord for Q {
216    fn cmp(&self, o: &Q) -> Ordering {
217        // n1/d1 vs n2/d2 with d > 0: n1*d2 vs n2*d1 (i128 overflow falls back to f64)
218        match (self.n.checked_mul(o.d), o.n.checked_mul(self.d)) {
219            (Some(a), Some(b)) => a.cmp(&b),
220            _ => self.to_f64().partial_cmp(&o.to_f64()).unwrap_or(Ordering::Equal),
221        }
222    }
223}
224
225/// A decimal literal (`12`, `-3.25`, `.5`) as an exact rational.
226pub fn parse_number(s: &str) -> Option<Q> {
227    let s = s.trim();
228    let (neg, body) = match s.strip_prefix('-') {
229        Some(b) => (true, b),
230        None => (false, s.strip_prefix('+').unwrap_or(s)),
231    };
232    if body.is_empty() || !body.chars().all(|c| c.is_ascii_digit() || c == '.') || body.matches('.').count() > 1 {
233        return None;
234    }
235    let (int, frac) = body.split_once('.').unwrap_or((body, ""));
236    if int.is_empty() && frac.is_empty() {
237        return None;
238    }
239    let digits = format!("{int}{frac}");
240    let n: i128 = digits.parse().ok()?;
241    let d = 10i128.checked_pow(frac.len() as u32)?;
242    let q = Q::new(n, d).ok()?;
243    if neg { q.neg().ok() } else { Some(q) }
244}
245
246// --------------------------------------------------------------------- calc
247
248#[derive(Clone, Debug, PartialEq)]
249enum Tok {
250    Num(Q),
251    Id(String),
252    Op(char),
253}
254
255fn lex(s: &str) -> Result<Vec<Tok>, String> {
256    let cs: Vec<char> = s.chars().collect();
257    let mut out = Vec::new();
258    let mut i = 0;
259    while i < cs.len() {
260        let c = cs[i];
261        if c.is_whitespace() {
262            i += 1;
263        } else if c.is_ascii_digit() || c == '.' {
264            let j = (i..cs.len()).find(|&j| !(cs[j].is_ascii_digit() || cs[j] == '.')).unwrap_or(cs.len());
265            let lit: String = cs[i..j].iter().collect();
266            out.push(Tok::Num(parse_number(&lit).ok_or_else(|| format!("not a number: {lit}"))?));
267            i = j;
268        } else if c.is_alphabetic() || c == '_' {
269            let j = (i..cs.len()).find(|&j| !(cs[j].is_alphanumeric() || cs[j] == '_')).unwrap_or(cs.len());
270            out.push(Tok::Id(cs[i..j].iter().collect::<String>().to_lowercase()));
271            i = j;
272        } else {
273            let op = match c {
274                '×' => '*',
275                '÷' => '/',
276                '−' => '-',
277                '*' if cs.get(i + 1) == Some(&'*') => {
278                    i += 1;
279                    '^'
280                }
281                '+' | '-' | '*' | '/' | '%' | '^' | '(' | ')' | ',' => c,
282                _ => return Err(format!("unexpected character {c:?}")),
283            };
284            out.push(Tok::Op(op));
285            i += 1;
286        }
287    }
288    Ok(out)
289}
290
291struct Parser {
292    t: Vec<Tok>,
293    i: usize,
294}
295
296impl Parser {
297    fn peek(&self) -> Option<&Tok> {
298        self.t.get(self.i)
299    }
300
301    fn eat(&mut self, op: char) -> bool {
302        if self.peek() == Some(&Tok::Op(op)) {
303            self.i += 1;
304            true
305        } else {
306            false
307        }
308    }
309
310    fn expr(&mut self) -> Result<Q, String> {
311        let mut v = self.term()?;
312        loop {
313            if self.eat('+') {
314                v = v.add(self.term()?)?;
315            } else if self.eat('-') {
316                v = v.sub(self.term()?)?;
317            } else {
318                return Ok(v);
319            }
320        }
321    }
322
323    fn term(&mut self) -> Result<Q, String> {
324        let mut v = self.unary()?;
325        loop {
326            if self.eat('*') {
327                v = v.mul(self.unary()?)?;
328            } else if self.eat('/') {
329                v = v.div(self.unary()?)?;
330            } else if self.eat('%') {
331                v = v.rem(self.unary()?)?;
332            } else {
333                return Ok(v);
334            }
335        }
336    }
337
338    fn unary(&mut self) -> Result<Q, String> {
339        if self.eat('-') {
340            return self.unary()?.neg();
341        }
342        if self.eat('+') {
343            return self.unary();
344        }
345        let base = self.primary()?;
346        if self.eat('^') {
347            // right-associative, binds tighter than unary minus on its right
348            let e = self.unary()?;
349            return base.pow(e);
350        }
351        Ok(base)
352    }
353
354    fn primary(&mut self) -> Result<Q, String> {
355        match self.t.get(self.i).cloned() {
356            Some(Tok::Num(q)) => {
357                self.i += 1;
358                Ok(q)
359            }
360            Some(Tok::Op('(')) => {
361                self.i += 1;
362                let v = self.expr()?;
363                if !self.eat(')') {
364                    return Err("a ( is not closed".into());
365                }
366                Ok(v)
367            }
368            Some(Tok::Id(f)) => {
369                self.i += 1;
370                if !self.eat('(') {
371                    return Err(format!("{f} needs (…)"));
372                }
373                let mut args = Vec::new();
374                if !self.eat(')') {
375                    loop {
376                        args.push(self.expr()?);
377                        if self.eat(')') {
378                            break;
379                        }
380                        if !self.eat(',') {
381                            return Err(format!("{f}(…): a , or ) is missing"));
382                        }
383                    }
384                }
385                func(&f, &args)
386            }
387            Some(t) => Err(format!("unexpected {t:?}")),
388            None => Err("the expression ends too early".into()),
389        }
390    }
391}
392
393fn func(f: &str, a: &[Q]) -> Result<Q, String> {
394    let one = |a: &[Q]| -> Result<Q, String> {
395        if a.len() == 1 { Ok(a[0]) } else { Err(format!("{f} takes one value")) }
396    };
397    let some = |a: &[Q]| -> Result<(), String> {
398        if a.is_empty() { Err(format!("{f} needs at least one value")) } else { Ok(()) }
399    };
400    match f {
401        "sum" => a.iter().try_fold(Q::int(0), |s, x| s.add(*x)),
402        "min" => {
403            some(a)?;
404            Ok(*a.iter().min().unwrap())
405        }
406        "max" => {
407            some(a)?;
408            Ok(*a.iter().max().unwrap())
409        }
410        "mean" | "avg" | "average" => {
411            some(a)?;
412            a.iter().try_fold(Q::int(0), |s, x| s.add(*x))?.div(Q::int(a.len() as i128))
413        }
414        "abs" => Ok(one(a)?.abs()),
415        "floor" => Ok(one(a)?.floor()),
416        "ceil" => Ok(one(a)?.ceil()),
417        "round" => match a {
418            [x] => x.round(0),
419            [x, d] if d.d == 1 => x.round(d.n),
420            _ => Err("round takes a value and a whole number of decimals".into()),
421        },
422        other => Err(format!("unknown function {other}")),
423    }
424}
425
426/// Evaluates an arithmetic expression exactly.
427pub fn calc(expr: &str) -> Result<Q, String> {
428    let t = lex(expr)?;
429    if t.is_empty() {
430        return Err("the expression is empty".into());
431    }
432    let mut p = Parser { t, i: 0 };
433    let v = p.expr()?;
434    if p.i != p.t.len() {
435        return Err(format!("unexpected {:?} after the expression", p.t[p.i]));
436    }
437    Ok(v)
438}
439
440// -------------------------------------------------------------------- table
441
442/// A command output as a table: one row a line, cells split by whitespace,
443/// an optional header row; total lines (`1425 total`, `total 48`) are not rows.
444#[derive(Debug)]
445pub struct Table {
446    pub header: Option<Vec<String>>,
447    pub rows: Vec<Vec<String>>,
448}
449
450/// A cell's number: `8345`, `27G`, `1.5Gi`, `46%`, `3KB` (the unit or `%` dropped).
451pub fn cell_number(s: &str) -> Option<Q> {
452    let mut t = s.trim().trim_end_matches('%');
453    for unit in ["iB", "B", "i"] {
454        if let Some(x) = t.strip_suffix(unit) {
455            if x.ends_with(|c: char| "KMGTPEkmgtpe".contains(c)) || unit == "B" {
456                t = x;
457                break;
458            }
459        }
460    }
461    let t = t.strip_suffix(|c: char| "KMGTPEkmgtpe".contains(c)).unwrap_or(t);
462    parse_number(t)
463}
464
465fn is_aggregate(row: &[String]) -> bool {
466    row.first().map(|c| c == "total").unwrap_or(false) || row.last().map(|c| c == "total").unwrap_or(false)
467}
468
469impl Table {
470    /// The table in `text`: of the blank-line separated blocks (a leading
471    /// `Output of …:` line and `Question:`/`Task:` lines left out), the
472    /// longest one whose lines mostly have two or more cells.
473    pub fn parse(text: &str) -> Result<Table, String> {
474        let mut best: Vec<Vec<String>> = Vec::new();
475        for block in text.split("\n\n") {
476            let mut lines: Vec<&str> = block
477                .lines()
478                .map(str::trim_end)
479                .filter(|l| !l.trim().is_empty())
480                .filter(|l| {
481                    let t = l.trim_start();
482                    !(t.starts_with("Question:") || t.starts_with("Task:") || t.starts_with("Answer "))
483                })
484                .collect();
485            if lines.first().map(|l| l.trim_end().ends_with(':')).unwrap_or(false) {
486                lines.remove(0);
487            }
488            let rows: Vec<Vec<String>> =
489                lines.iter().map(|l| l.split_whitespace().map(String::from).collect()).collect();
490            let wide = rows.iter().filter(|r| r.len() >= 2).count();
491            if !rows.is_empty() && 2 * wide >= rows.len() && rows.len() > best.len() {
492                best = rows;
493            }
494        }
495        if best.is_empty() {
496            return Err("no table in the last output".into());
497        }
498        let mut rows: Vec<Vec<String>> = best.into_iter().filter(|r| !is_aggregate(r)).collect();
499        let header_like = |r: &[String]| r.iter().all(|c| cell_number(c).is_none());
500        let mut header = None;
501        if rows.len() >= 2 && header_like(&rows[0]) && rows[1..].iter().any(|r| !header_like(r)) {
502            let mut h = rows.remove(0);
503            // the usual width of a row; trailing header words of a wider header name one column ("Mounted on")
504            let mut widths: Vec<usize> = rows.iter().map(Vec::len).collect();
505            widths.sort_unstable();
506            let w = widths[widths.len() / 2];
507            if h.len() > w && w >= 1 {
508                let tail = h.split_off(w - 1).join(" ");
509                h.push(tail);
510            }
511            header = Some(h);
512        }
513        if rows.is_empty() {
514            return Err("the table has no rows".into());
515        }
516        Ok(Table { header, rows })
517    }
518
519    /// A column given as its header name or as a number from 1.
520    fn col(&self, c: &Value) -> Result<usize, String> {
521        let width = self.rows.iter().map(Vec::len).max().unwrap_or(0);
522        let by_number = |n: i64| -> Result<usize, String> {
523            if n >= 1 && (n as usize) <= width {
524                Ok(n as usize - 1)
525            } else {
526                Err(format!("no column {n}: the rows have {width}"))
527            }
528        };
529        match c {
530            Value::Number(n) => by_number(n.as_i64().ok_or("a column number is a whole number")?),
531            Value::String(s) => {
532                if let Ok(n) = s.trim().parse::<i64>() {
533                    return by_number(n);
534                }
535                let h = self.header.as_ref().ok_or_else(|| format!("no column named {s}: the table has no header"))?;
536                h.iter()
537                    .position(|x| x.eq_ignore_ascii_case(s.trim()))
538                    .ok_or_else(|| format!("no column named {s} (columns: {})", h.join(", ")))
539            }
540            _ => Err("column: a header name or a number from 1".into()),
541        }
542    }
543
544    fn name(row: &[String]) -> &str {
545        row.last().map(String::as_str).unwrap_or("")
546    }
547
548    fn cell<'a>(row: &'a [String], c: usize) -> Result<&'a str, String> {
549        row.get(c)
550            .map(String::as_str)
551            .ok_or_else(|| format!("row {} has no column {}", Table::name(row), c + 1))
552    }
553
554    fn number(row: &[String], c: usize) -> Result<Q, String> {
555        let s = Table::cell(row, c)?;
556        cell_number(s).ok_or_else(|| format!("{s} (row {}) is not a number", Table::name(row)))
557    }
558}
559
560fn value_text(v: &Value) -> String {
561    match v {
562        Value::String(s) => s.clone(),
563        other => other.to_string(),
564    }
565}
566
567fn passes(t: &Table, row: &[String], test: &Value) -> Result<bool, String> {
568    let c = t.col(test.get("column").ok_or("where needs a column")?)?;
569    let op = test.get("op").and_then(Value::as_str).unwrap_or("=");
570    let want = value_text(test.get("value").ok_or("where needs a value")?).trim().to_string();
571    let cell = Table::cell(row, c).unwrap_or("");
572    let nums = (cell_number(cell), cell_number(&want));
573    Ok(match op {
574        "=" | "==" => match nums {
575            (Some(a), Some(b)) => a == b,
576            _ => cell == want,
577        },
578        "!=" => match nums {
579            (Some(a), Some(b)) => a != b,
580            _ => cell != want,
581        },
582        "contains" => cell.contains(&want),
583        ">" | "<" | ">=" | "<=" => {
584            let (Some(a), Some(b)) = nums else {
585                return Err(format!("{op} compares numbers: {cell} and {want}"));
586            };
587            match op {
588                ">" => a > b,
589                "<" => a < b,
590                ">=" => a >= b,
591                _ => a <= b,
592            }
593        }
594        other => return Err(format!("unknown test {other}")),
595    })
596}
597
598/// The `table` tool over `input` (see [`Table::parse`]).
599pub fn table(args: &Value, input: &str) -> Result<String, String> {
600    let t = Table::parse(input)?;
601    let op = args.get("op").and_then(Value::as_str).ok_or("table needs an op")?;
602    // rows by name, in the order asked (diff reads the order)
603    let mut rows: Vec<&Vec<String>> = match args.get("rows") {
604        None | Some(Value::Null) => t.rows.iter().collect(),
605        Some(Value::Array(names)) if !names.is_empty() => {
606            let mut out = Vec::new();
607            for n in names {
608                let n = value_text(n).trim().to_string();
609                let r = t
610                    .rows
611                    .iter()
612                    .find(|r| Table::name(r) == n)
613                    .ok_or_else(|| format!("no row named {n}"))?;
614                out.push(r);
615            }
616            out
617        }
618        Some(Value::String(n)) => {
619            let n = n.trim();
620            vec![t.rows.iter().find(|r| Table::name(r) == n).ok_or_else(|| format!("no row named {n}"))?]
621        }
622        _ => return Err("rows: a list of row names".into()),
623    };
624    if let Some(w) = args.get("where").filter(|w| !w.is_null()) {
625        let tests: Vec<&Value> = match w {
626            Value::Array(a) => a.iter().collect(),
627            other => vec![other],
628        };
629        let mut kept = Vec::new();
630        for r in rows {
631            let mut ok = true;
632            for test in &tests {
633                ok &= passes(&t, r, test)?;
634            }
635            if ok {
636                kept.push(r);
637            }
638        }
639        rows = kept;
640    }
641    if op == "count" {
642        return Ok(rows.len().to_string());
643    }
644    let c = t.col(args.get("column").ok_or_else(|| format!("{op} needs a column"))?)?;
645    if rows.is_empty() {
646        return Err("no row passes".into());
647    }
648    match op {
649        "sum" | "min" | "max" | "mean" => {
650            let v: Vec<Q> = rows.iter().map(|r| Table::number(r, c)).collect::<Result<_, _>>()?;
651            Ok(func(op, &v)?.show())
652        }
653        "get" => {
654            if rows.len() != 1 {
655                return Err(format!("{} rows pass; get reads one", rows.len()));
656            }
657            let s = Table::cell(rows[0], c)?;
658            Ok(cell_number(s).map(Q::show).unwrap_or_else(|| s.to_string()))
659        }
660        "argmax" | "argmin" => {
661            let v: Vec<Q> = rows.iter().map(|r| Table::number(r, c)).collect::<Result<_, _>>()?;
662            let best = if op == "argmax" { v.iter().max() } else { v.iter().min() }.copied().unwrap();
663            let names: Vec<&str> = rows.iter().zip(&v).filter(|(_, x)| **x == best).map(|(r, _)| Table::name(r)).collect();
664            Ok(names.join(", "))
665        }
666        "diff" => {
667            if rows.len() != 2 {
668                return Err("diff reads two rows: the first minus the second".into());
669            }
670            Ok(Table::number(rows[0], c)?.sub(Table::number(rows[1], c)?)?.show())
671        }
672        other => Err(format!("unknown op {other}")),
673    }
674}
675
676// ------------------------------------------------------------- the contract
677
678/// The text `table` reads at the end of `prompt` (a cmf-im-v1 transcript):
679/// the last tool response after the last user turn, else that user turn;
680/// a prompt without turns is read whole.
681pub fn last_output(prompt: &str) -> String {
682    const USER: &str = "<|im_start|>user\n";
683    const TOOL: &str = "<|im_start|>tool\n";
684    const END: &str = "<|im_end|>";
685    let Some(u) = prompt.rfind(USER) else {
686        return prompt.to_string();
687    };
688    let after = &prompt[u..];
689    if let Some(t) = after.rfind(TOOL) {
690        let body = &after[t + TOOL.len()..];
691        let body = body.split(END).next().unwrap_or(body);
692        let body = body.trim();
693        let body = body.strip_prefix("<tool_response>").unwrap_or(body);
694        let body = body.strip_suffix("</tool_response>").unwrap_or(body);
695        return body.trim().to_string();
696    }
697    let body = &after[USER.len()..];
698    body.split(END).next().unwrap_or(body).trim().to_string()
699}
700
701/// The texts `table` may read at the end of `prompt`, newest first: the tool
702/// responses after the last user turn, then that user turn (a prompt without
703/// turns is one text). A second `table` call after a result reads the table
704/// again, not the previous result.
705pub fn outputs(prompt: &str) -> Vec<String> {
706    const USER: &str = "<|im_start|>user\n";
707    const TOOL: &str = "<|im_start|>tool\n";
708    const END: &str = "<|im_end|>";
709    let Some(u) = prompt.rfind(USER) else {
710        return vec![prompt.to_string()];
711    };
712    let after = &prompt[u..];
713    let mut out: Vec<String> = after
714        .split(TOOL)
715        .skip(1)
716        .map(|t| {
717            let body = t.split(END).next().unwrap_or(t).trim();
718            let body = body.strip_prefix("<tool_response>").unwrap_or(body);
719            body.strip_suffix("</tool_response>").unwrap_or(body).trim().to_string()
720        })
721        .collect();
722    out.reverse();
723    let body = &after[USER.len()..];
724    out.push(body.split(END).next().unwrap_or(body).trim().to_string());
725    out
726}
727
728/// `table` over the newest of `texts` that holds a table (the error of the
729/// newest when none does); any other tool over the newest text.
730fn call_on(name: &str, args: &Value, texts: &[String]) -> Result<String, String> {
731    if name == "table" {
732        // a tool's own error line is not an output to read
733        if let Some(t) = texts.iter().find(|t| !t.starts_with("error:") && Table::parse(t).is_ok()) {
734            return call(name, args, t);
735        }
736    }
737    call(name, args, texts.first().map(String::as_str).unwrap_or(""))
738}
739
740/// The `<tool_call>` blocks of an assistant turn: (name, arguments), `None`
741/// for a block that is not a call object.
742pub fn turn_calls(text: &str) -> Vec<Option<(String, Value)>> {
743    let mut out = Vec::new();
744    let mut rest = text;
745    while let Some(s) = rest.find("<tool_call>") {
746        let after = &rest[s + "<tool_call>".len()..];
747        let Some(e) = after.find("</tool_call>") else {
748            out.push(None);
749            break;
750        };
751        let body = after[..e].trim();
752        out.push(serde_json::from_str::<Value>(body).ok().and_then(|v| {
753            let name = v.get("name")?.as_str()?.to_string();
754            let args = match v.get("arguments") {
755                Some(Value::String(s)) => serde_json::from_str(s).unwrap_or(Value::Null),
756                Some(a) => a.clone(),
757                None => Value::Object(Default::default()),
758            };
759            Some((name, args))
760        }));
761        rest = &after[e + "</tool_call>".len()..];
762    }
763    out
764}
765
766/// One built-in round: the calls run and the tool turns that answer them.
767#[derive(Debug)]
768pub struct Round {
769    /// (name, arguments, result) of every call, in order.
770    pub calls: Vec<(String, Value, String)>,
771    /// `<|im_start|>tool\n<tool_response>\n…\n</tool_response><|im_end|>\n` per call.
772    pub tool_turns: String,
773}
774
775/// Runs the calls of the assistant turn `generated` (continuing `prompt`)
776/// when it has calls and every one is built in; `None` otherwise (no call,
777/// a malformed block, or a call the client serves). A failing call answers
778/// `error: …`, which the model reads like any tool result.
779pub fn round(prompt: &str, generated: &str) -> Option<Round> {
780    let calls = turn_calls(generated);
781    if calls.is_empty() || calls.iter().any(|c| !matches!(c, Some((n, _)) if is_builtin(n))) {
782        return None;
783    }
784    let texts = outputs(prompt);
785    let mut done = Vec::new();
786    let mut tool_turns = String::new();
787    for (name, args) in calls.into_iter().flatten() {
788        let r = call_on(&name, &args, &texts).unwrap_or_else(|e| format!("error: {e}"));
789        tool_turns.push_str("<|im_start|>tool\n<tool_response>\n");
790        tool_turns.push_str(&r);
791        tool_turns.push_str("\n</tool_response><|im_end|>\n");
792        done.push((name, args, r));
793    }
794    Some(Round { calls: done, tool_turns })
795}
796
797/// The prompt that continues after a built-in round: the assistant turn
798/// closed, the tool turns, a new assistant turn opened.
799pub fn continue_prompt(prompt: &str, generated: &str, r: &Round) -> String {
800    format!("{prompt}{}<|im_end|>\n{}<|im_start|>assistant\n", generated.trim_end(), r.tool_turns)
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806    use serde_json::json;
807
808    fn c(e: &str) -> String {
809        calc(e).map(Q::show).unwrap_or_else(|x| format!("ERR {x}"))
810    }
811
812    #[test]
813    fn calc_is_exact() {
814        assert_eq!(c("7243 + 2719"), "9962");
815        assert_eq!(c("75066 - 22301"), "52765");
816        assert_eq!(c("(3 + 4) * 12 / 5"), "16.8");
817        assert_eq!(c("1/3"), "1/3 ≈ 0.3333333333");
818        assert_eq!(c("1/3 * 3"), "1");
819        assert_eq!(c("0.1 + 0.2"), "0.3");
820        assert_eq!(c("2^10"), "1024");
821        assert_eq!(c("2**-2"), "0.25");
822        assert_eq!(c("-2^2"), "-4");
823        assert_eq!(c("7 % 3"), "1");
824        assert_eq!(c("-7 % 3"), "2");
825        assert_eq!(c("sum(1, 2, 3.5)"), "6.5");
826        assert_eq!(c("mean(542, 391, 272, 220)"), "356.25");
827        assert_eq!(c("max(3, 9, 4) - min(3, 9, 4)"), "6");
828        assert_eq!(c("round(2.345, 2)"), "2.35");
829        assert_eq!(c("round(-2.5)"), "-3");
830        assert_eq!(c("12 × 3 ÷ 4"), "9");
831        assert_eq!(c("170141183460469231731687303715884105727 + 1"), format!("ERR {OVERFLOW}"));
832        assert_eq!(c("1/0"), "ERR division by zero");
833        assert_eq!(c("2 +"), "ERR the expression ends too early");
834        assert_eq!(c("foo(1)"), "ERR unknown function foo");
835    }
836
837    const LS: &str = "Output of `ls -l /var/log/app`:\n-rw-r--r-- 1 user user  8345 Jan 15 10:00 error.log\n\
838-rw-r--r-- 1 user user   602 Jan 15 10:00 debug.log\n-rw-r--r-- 1 user user  7369 Jan 15 10:00 cron.log\n\
839-rw-r--r-- 1 user user  4072 Jan 15 10:00 mail.log\n-rw-r--r-- 1 user user  7243 Jan 15 10:00 db.log\n\
840-rw-r--r-- 1 user user  2719 Jan 15 10:00 boot.log\n\nQuestion: How many of these files are larger than 2692 bytes?\nAnswer with a number.";
841    const WC: &str = "Output of `wc -l *.log`:\n  542 db.log\n  391 debug.log\n  272 mail.log\n  220 boot.log\n 1425 total\n\n\
842Question: Which file has the most lines?\nAnswer with the file name.";
843    const DF: &str = "Output of `df -h`:\nFilesystem      Size  Used Avail Use% Mounted on\n/dev/sda1        50G   23G   27G  46% /var\n\
844/dev/sdb1       200G   32G  168G  16% /data\n/dev/sdc1       250G   87G  163G  34% /\n/dev/sdd1       100G   12G   88G  12% /backup\n\n\
845Question: How many GB are available on /data?\nAnswer with a number.";
846    const DU: &str = "Output of `du -sk /opt/app /srv/www /var/log`:\n75066\t/opt/app\n22301\t/srv/www\n60284\t/var/log\n\n\
847Question: How many KB larger is /opt/app than /srv/www?\nAnswer with a number.";
848    const PS: &str = "Output of `ps -eo user,pid,comm`:\nUSER       PID COMMAND\nroot       3973 nginx\nwww-data   2346 python3\n\
849boris      5364 nginx\npostgres   4772 bash\nanna       6633 nginx\nroot       8017 redis-server\nroot        303 node\n\
850postgres   5471 nginx\nwww-data   6020 node\n\nQuestion: How many of these processes belong to the user postgres?\nAnswer with a number.";
851
852    fn t(args: Value, input: &str) -> String {
853        table(&args, input).unwrap_or_else(|e| format!("ERR {e}"))
854    }
855
856    #[test]
857    fn table_answers_the_eight_families_of_set_r() {
858        assert_eq!(t(json!({"op": "count", "where": {"column": 5, "op": ">", "value": 2692}}), LS), "5");
859        assert_eq!(t(json!({"op": "sum", "column": 5, "rows": ["db.log", "boot.log"]}), LS), "9962");
860        assert_eq!(t(json!({"op": "sum", "column": 1, "rows": ["boot.log", "debug.log"]}), WC), "611");
861        assert_eq!(t(json!({"op": "argmax", "column": 1}), WC), "db.log");
862        assert_eq!(t(json!({"op": "get", "column": "Avail", "rows": ["/data"]}), DF), "168");
863        assert_eq!(t(json!({"op": "sum", "column": "Used", "rows": ["/", "/var"]}), DF), "110");
864        assert_eq!(t(json!({"op": "diff", "column": 1, "rows": ["/opt/app", "/srv/www"]}), DU), "52765");
865        assert_eq!(t(json!({"op": "count", "where": {"column": "USER", "op": "=", "value": "postgres"}}), PS), "2");
866    }
867
868    #[test]
869    fn table_reads_headers_totals_and_reports_mistakes() {
870        let df = Table::parse(DF).unwrap();
871        assert_eq!(df.header.as_ref().unwrap().last().unwrap(), "Mounted on");
872        assert_eq!(Table::parse(WC).unwrap().rows.len(), 4, "the total line is not a row");
873        assert_eq!(t(json!({"op": "mean", "column": 1}), WC), "356.25");
874        assert_eq!(t(json!({"op": "count", "where": [{"column": "USER", "value": "root"}, {"column": 3, "op": "=", "value": "nginx"}]}), PS), "1");
875        assert_eq!(t(json!({"op": "get", "column": "Use%", "rows": ["/"]}), DF), "34");
876        assert_eq!(t(json!({"op": "get", "column": "Size", "rows": ["/home"]}), DF), "ERR no row named /home");
877        assert_eq!(t(json!({"op": "sum", "column": "Free", "rows": ["/"]}), DF).starts_with("ERR no column named Free"), true);
878        assert_eq!(t(json!({"op": "get", "column": 1}), PS), "ERR 9 rows pass; get reads one");
879        assert_eq!(t(json!({"op": "sum", "column": 1}), PS), "ERR root (row nginx) is not a number");
880        // a stray space in what the model writes does not change the answer
881        assert_eq!(t(json!({"op": "count", "where": {"column": "USER", "op": "=", "value": " anna"}}), PS), "1");
882        assert_eq!(t(json!({"op": "get", "column": "Avail", "rows": [" /data "]}), DF), "168");
883    }
884
885    #[test]
886    fn a_round_runs_built_in_calls_and_leaves_others_to_the_client() {
887        let prompt = format!("<|im_start|>system\nS<|im_end|>\n<|im_start|>user\n{PS}<|im_end|>\n<|im_start|>assistant\n");
888        let turn = "<think>\nA table: count the rows of postgres.\n</think>\n<tool_call>\n{\"name\": \"table\", \"arguments\": \
889{\"op\": \"count\", \"where\": {\"column\": \"USER\", \"op\": \"=\", \"value\": \"postgres\"}}}\n</tool_call>";
890        let r = round(&prompt, turn).expect("a built-in turn");
891        assert_eq!(r.calls[0].2, "2");
892        let next = continue_prompt(&prompt, turn, &r);
893        assert!(next.ends_with("</tool_call><|im_end|>\n<|im_start|>tool\n<tool_response>\n2\n</tool_response><|im_end|>\n<|im_start|>assistant\n"));
894        // the tool's answer is now the last output
895        assert_eq!(last_output(&next), "2");
896        assert!(round(&prompt, "<tool_call>\n{\"name\": \"lookup\", \"arguments\": {\"query\": \"x\"}}\n</tool_call>").is_none());
897        assert!(round(&prompt, "The answer is 2.").is_none());
898        // a second table call after the result reads the table again, not the result
899        let again = round(&next, turn).expect("a built-in turn");
900        assert_eq!(again.calls[0].2, "2");
901        // nor the error of a failed call
902        let miss = "<tool_call>\n{\"name\": \"table\", \"arguments\": {\"op\": \"get\", \"column\": 2, \"rows\": [\"x\"]}}\n</tool_call>";
903        let failed = round(&prompt, miss).unwrap();
904        assert_eq!(failed.calls[0].2, "error: no row named x");
905        let after = continue_prompt(&prompt, miss, &failed);
906        assert_eq!(round(&after, turn).unwrap().calls[0].2, "2");
907        let bad = round(&prompt, "<tool_call>\n{\"name\": \"calc\", \"arguments\": {\"expression\": \"1/0\"}}\n</tool_call>").unwrap();
908        assert_eq!(bad.calls[0].2, "error: division by zero");
909        assert_eq!(descriptions().len(), 2);
910    }
911}