formal-ai 0.150.0

Formal symbolic AI implementation with OpenAI-compatible APIs
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Calculator delegation boundary for the universal solver.
//!
//! This module keeps natural-language prompt processing in formal-ai, delegates
//! calculator-shaped expressions to `link-calculator` first, and preserves the
//! local arithmetic evaluator for syntax the upstream crate does not support yet.

use crate::arithmetic::{evaluate_fallback_formatted, ArithmeticError};
use crate::fuzzy::is_close_token_typo;

/// Engine that produced a calculation result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CalculationEngine {
    LinkCalculator,
    FormalAiFallback,
    FormalAiEquationFallback,
}

impl CalculationEngine {
    #[must_use]
    pub const fn slug(self) -> &'static str {
        match self {
            Self::LinkCalculator => "link-calculator",
            Self::FormalAiFallback => "formal-ai-fallback",
            Self::FormalAiEquationFallback => "formal-ai-equation-fallback",
        }
    }
}

/// Structured calculation result used by the solver trace.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CalculationEvaluation {
    pub formatted: String,
    pub engine: CalculationEngine,
    pub lino: Option<String>,
    pub steps: Vec<String>,
}

/// A candidate calculator expression extracted from a user prompt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CalculationCandidate {
    pub expression: String,
    pub explicit: bool,
    pub interpretations: Vec<PromptInterpretation>,
}

/// A visible interpretation applied while normalizing a user prompt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromptInterpretation {
    pub original: String,
    pub corrected: String,
}

fn evaluate_with_link_calculator(
    expression: &str,
) -> Result<CalculationEvaluation, ArithmeticError> {
    let mut calculator = link_calculator::Calculator::new();
    let (_expression, value, steps, lino) = calculator
        .calculate_with_value(expression)
        .map_err(|error| ArithmeticError::Calculator(error.to_string()))?;
    Ok(CalculationEvaluation {
        formatted: value.to_display_string(),
        engine: CalculationEngine::LinkCalculator,
        lino: Some(lino),
        steps,
    })
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct LinearValue {
    coefficient: f64,
    constant: f64,
}

impl LinearValue {
    const fn constant(value: f64) -> Self {
        Self {
            coefficient: 0.0,
            constant: value,
        }
    }

    const fn variable() -> Self {
        Self {
            coefficient: 1.0,
            constant: 0.0,
        }
    }

    fn add(self, other: Self) -> Self {
        Self {
            coefficient: self.coefficient + other.coefficient,
            constant: self.constant + other.constant,
        }
    }

    fn subtract(self, other: Self) -> Self {
        Self {
            coefficient: self.coefficient - other.coefficient,
            constant: self.constant - other.constant,
        }
    }

    fn negate(self) -> Self {
        Self {
            coefficient: -self.coefficient,
            constant: -self.constant,
        }
    }

    fn multiply(self, other: Self) -> Result<Self, ArithmeticError> {
        if self.has_variable() && other.has_variable() {
            return Err(ArithmeticError::Unparseable);
        }
        if self.has_variable() {
            Ok(Self {
                coefficient: self.coefficient * other.constant,
                constant: self.constant * other.constant,
            })
        } else if other.has_variable() {
            Ok(Self {
                coefficient: other.coefficient * self.constant,
                constant: other.constant * self.constant,
            })
        } else {
            Ok(Self::constant(self.constant * other.constant))
        }
    }

    fn divide(self, other: Self) -> Result<Self, ArithmeticError> {
        if other.has_variable() {
            return Err(ArithmeticError::Unparseable);
        }
        if nearly_zero(other.constant) {
            return Err(ArithmeticError::DivisionByZero);
        }
        Ok(Self {
            coefficient: self.coefficient / other.constant,
            constant: self.constant / other.constant,
        })
    }

    fn has_variable(self) -> bool {
        !nearly_zero(self.coefficient)
    }
}

struct LinearParser<'a> {
    input: &'a str,
    position: usize,
    variable: Option<String>,
}

impl<'a> LinearParser<'a> {
    const fn new(input: &'a str) -> Self {
        Self {
            input,
            position: 0,
            variable: None,
        }
    }

    fn parse(mut self) -> Result<(LinearValue, Option<String>), ArithmeticError> {
        let value = self.parse_expression()?;
        self.skip_whitespace();
        if self.position == self.input.len() {
            Ok((value, self.variable))
        } else {
            Err(ArithmeticError::Unparseable)
        }
    }

    fn parse_expression(&mut self) -> Result<LinearValue, ArithmeticError> {
        let mut value = self.parse_term()?;
        loop {
            self.skip_whitespace();
            if self.consume('+') {
                value = value.add(self.parse_term()?);
            } else if self.consume('-') || self.consume('') {
                value = value.subtract(self.parse_term()?);
            } else {
                return Ok(value);
            }
        }
    }

    fn parse_term(&mut self) -> Result<LinearValue, ArithmeticError> {
        let mut value = self.parse_factor()?;
        loop {
            self.skip_whitespace();
            if self.consume('*') || self.consume('×') || self.consume('·') {
                value = value.multiply(self.parse_factor()?)?;
            } else if self.consume('/') || self.consume('÷') {
                value = value.divide(self.parse_factor()?)?;
            } else {
                return Ok(value);
            }
        }
    }

    fn parse_factor(&mut self) -> Result<LinearValue, ArithmeticError> {
        self.skip_whitespace();
        if self.consume('+') {
            return self.parse_factor();
        }
        if self.consume('-') || self.consume('') {
            return Ok(self.parse_factor()?.negate());
        }
        if self.consume('(') {
            let value = self.parse_expression()?;
            self.skip_whitespace();
            if self.consume(')') {
                return Ok(value);
            }
            return Err(ArithmeticError::UnbalancedParens);
        }
        if self
            .peek()
            .is_some_and(|character| character.is_ascii_digit() || character == '.')
        {
            return self.parse_number();
        }
        if self.peek().is_some_and(char::is_alphabetic) {
            return self.parse_variable();
        }
        Err(ArithmeticError::Unparseable)
    }

    fn parse_number(&mut self) -> Result<LinearValue, ArithmeticError> {
        let start = self.position;
        let mut has_digit = false;
        let mut has_dot = false;
        while let Some(character) = self.peek() {
            if character.is_ascii_digit() {
                has_digit = true;
                self.advance(character);
            } else if character == '.' && !has_dot {
                has_dot = true;
                self.advance(character);
            } else {
                break;
            }
        }
        if !has_digit {
            return Err(ArithmeticError::Unparseable);
        }
        self.input[start..self.position]
            .parse::<f64>()
            .map(LinearValue::constant)
            .map_err(|_| ArithmeticError::Unparseable)
    }

    fn parse_variable(&mut self) -> Result<LinearValue, ArithmeticError> {
        let start = self.position;
        while let Some(character) = self.peek() {
            if character.is_alphabetic() || character == '_' {
                self.advance(character);
            } else {
                break;
            }
        }
        let name = self.input[start..self.position].to_owned();
        if name.is_empty() {
            return Err(ArithmeticError::Unparseable);
        }
        if let Some(existing) = &self.variable {
            if existing != &name {
                return Err(ArithmeticError::Unparseable);
            }
        } else {
            self.variable = Some(name);
        }
        Ok(LinearValue::variable())
    }

    fn skip_whitespace(&mut self) {
        while let Some(character) = self.peek() {
            if character.is_whitespace() {
                self.advance(character);
            } else {
                break;
            }
        }
    }

    fn consume(&mut self, expected: char) -> bool {
        if self.peek() == Some(expected) {
            self.advance(expected);
            true
        } else {
            false
        }
    }

    fn peek(&self) -> Option<char> {
        self.input[self.position..].chars().next()
    }

    fn advance(&mut self, character: char) {
        self.position += character.len_utf8();
    }
}

fn nearly_zero(value: f64) -> bool {
    value.abs() < f64::EPSILON
}

fn format_equation_number(value: f64) -> Result<String, ArithmeticError> {
    if !value.is_finite() {
        return Err(ArithmeticError::Overflow);
    }
    if nearly_zero(value) {
        return Ok(String::from("0"));
    }
    if value.fract().abs() < 1e-10 {
        return Ok(format!("{value:.0}"));
    }
    let rendered = format!("{value:.10}");
    Ok(rendered
        .trim_end_matches('0')
        .trim_end_matches('.')
        .to_owned())
}

fn evaluate_linear_equation(expression: &str) -> Result<CalculationEvaluation, ArithmeticError> {
    let mut parts = expression.split('=');
    let left = parts.next().ok_or(ArithmeticError::Unparseable)?;
    let right = parts.next().ok_or(ArithmeticError::Unparseable)?;
    if parts.next().is_some() {
        return Err(ArithmeticError::Unparseable);
    }
    let (left_value, left_variable) = LinearParser::new(left).parse()?;
    let (right_value, right_variable) = LinearParser::new(right).parse()?;
    let variable = match (left_variable, right_variable) {
        (Some(left), Some(right)) if left == right => left,
        (Some(left), None) => left,
        (None, Some(right)) => right,
        _ => return Err(ArithmeticError::Unparseable),
    };
    let coefficient = left_value.coefficient - right_value.coefficient;
    if nearly_zero(coefficient) {
        return Err(ArithmeticError::Unparseable);
    }
    let value = (right_value.constant - left_value.constant) / coefficient;
    Ok(CalculationEvaluation {
        formatted: format!("{variable} = {}", format_equation_number(value)?),
        engine: CalculationEngine::FormalAiEquationFallback,
        lino: None,
        steps: Vec::new(),
    })
}

fn contains_word_operator(expression: &str) -> bool {
    let lower = format!(" {} ", expression.to_lowercase());
    [
        " plus ",
        " minus ",
        " times ",
        " multiplied by ",
        " divided by ",
        " modulo ",
        " mod ",
        " плюс ",
        " минус ",
        " умножить ",
        " умножь ",
        " умножить на ",
        " разделить на ",
        " делить на ",
    ]
    .iter()
    .any(|operator| lower.contains(operator))
}

/// Evaluate an expression, delegating calculator-supported syntax to
/// `link-calculator` and preserving the in-repo evaluator as a fallback for
/// syntax the upstream crate does not support yet.
pub fn evaluate_calculation(expression: &str) -> Result<CalculationEvaluation, ArithmeticError> {
    if let Ok(evaluation) = evaluate_with_link_calculator(expression) {
        return Ok(evaluation);
    }
    if expression.contains('=') {
        if let Ok(evaluation) = evaluate_linear_equation(expression) {
            return Ok(evaluation);
        }
    }
    let formatted = evaluate_fallback_formatted(expression)?;
    Ok(CalculationEvaluation {
        formatted,
        engine: CalculationEngine::FormalAiFallback,
        lino: None,
        steps: Vec::new(),
    })
}

fn trim_prompt_punctuation(value: &str) -> &str {
    value
        .trim()
        .trim_matches(|c| matches!(c, '?' | '!' | '' | '' | ''))
        .trim()
        .trim_end_matches('.')
        .trim()
}

fn strip_prefix_case_insensitive<'a>(value: &'a str, prefix: &str) -> Option<&'a str> {
    let lower = value.to_lowercase();
    lower
        .starts_with(prefix)
        .then(|| value[prefix.len()..].trim_start())
}

fn strip_suffix_case_insensitive<'a>(value: &'a str, suffix: &str) -> Option<&'a str> {
    let lower = value.to_lowercase();
    lower
        .ends_with(suffix)
        .then(|| value[..value.len() - suffix.len()].trim_end())
}

fn leading_word_spans(value: &str, limit: usize) -> Vec<(usize, usize, &str)> {
    let mut spans = Vec::new();
    let mut start = None;
    for (index, character) in value.char_indices() {
        if character.is_whitespace() {
            if let Some(word_start) = start.take() {
                spans.push((word_start, index, &value[word_start..index]));
                if spans.len() == limit {
                    return spans;
                }
            }
        } else if start.is_none() {
            start = Some(index);
        }
    }
    if let Some(word_start) = start {
        spans.push((word_start, value.len(), &value[word_start..]));
    }
    spans
}

fn fuzzy_prefix_match(value: &str, prefix: &str) -> Option<(usize, usize, PromptInterpretation)> {
    let prefix_words: Vec<&str> = prefix.split_whitespace().collect();
    if prefix_words.is_empty() {
        return None;
    }
    let spans = leading_word_spans(value, prefix_words.len());
    if spans.len() != prefix_words.len() {
        return None;
    }
    let mut typo_count = 0;
    for ((_, _, actual), expected) in spans.iter().zip(prefix_words.iter()) {
        if actual.eq_ignore_ascii_case(expected) {
            continue;
        }
        if !is_close_token_typo(actual, expected) {
            return None;
        }
        typo_count += 1;
    }
    if typo_count != 1 {
        return None;
    }
    let matched_end = spans.last()?.1;
    Some((
        typo_count,
        matched_end,
        PromptInterpretation {
            original: value[..matched_end].to_owned(),
            corrected: prefix.trim().to_owned(),
        },
    ))
}

fn strip_fuzzy_prefix_case_insensitive<'a>(
    value: &'a str,
    prefixes: &[&str],
) -> Option<(&'a str, PromptInterpretation)> {
    let mut matches = prefixes
        .iter()
        .filter_map(|prefix| fuzzy_prefix_match(value, prefix))
        .collect::<Vec<_>>();
    matches.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| right.1.cmp(&left.1)));
    let (typos, matched_end, interpretation) = matches.first()?.clone();
    if matches
        .get(1)
        .is_some_and(|candidate| candidate.0 == typos && candidate.1 == matched_end)
    {
        return None;
    }
    Some((value[matched_end..].trim_start(), interpretation))
}

#[must_use]
pub fn interpretation_statements(interpretations: &[PromptInterpretation]) -> String {
    interpretations
        .iter()
        .map(|interpretation| {
            format!(
                "Interpreted \"{}\" as \"{}\".",
                interpretation.original, interpretation.corrected
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn strip_calculation_wrappers(prompt: &str) -> (String, bool, Vec<PromptInterpretation>) {
    let prefixes = [
        "please calculate ",
        "please compute ",
        "can you calculate ",
        "can you compute ",
        "could you calculate ",
        "could you compute ",
        "what is ",
        "what's ",
        "what does ",
        "calculate ",
        "compute ",
        "evaluate ",
        "how much is ",
        "solve ",
        "сколько будет ",
        "посчитай ",
        "посчитайте ",
        "вычисли ",
        "вычислите ",
        "рассчитай ",
        "рассчитайте ",
        "请计算",
        "请算一下",
        "计算一下",
        "算一下",
        "计算",
        "कृपया गणना करें ",
        "गणना करें ",
    ];
    let suffixes = [
        " equal",
        " equals",
        " =",
        "=",
        " please",
        " for me",
        " пожалуйста",
        "是多少",
        "等于多少",
        "等于几",
        "कितना है",
        "क्या है",
        "की गणना करें",
    ];

    let mut working = trim_prompt_punctuation(prompt).to_owned();
    let mut explicit = false;
    let mut interpretations = Vec::new();
    loop {
        let mut changed = false;
        for prefix in &prefixes {
            if let Some(stripped) = strip_prefix_case_insensitive(&working, prefix) {
                working = stripped.to_owned();
                explicit = true;
                changed = true;
                break;
            }
        }
        if !changed {
            if let Some((stripped, interpretation)) =
                strip_fuzzy_prefix_case_insensitive(&working, &prefixes)
            {
                working = stripped.to_owned();
                explicit = true;
                interpretations.push(interpretation);
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    loop {
        working = trim_prompt_punctuation(&working).to_owned();
        let mut changed = false;
        for suffix in &suffixes {
            if let Some(stripped) = strip_suffix_case_insensitive(&working, suffix) {
                working = stripped.to_owned();
                explicit = true;
                changed = true;
                break;
            }
        }
        if !changed {
            break;
        }
    }
    (working.trim().to_owned(), explicit, interpretations)
}

fn has_calculation_signal(expression: &str, explicit: bool) -> bool {
    let lower = format!(" {} ", expression.to_lowercase());
    let has_digit = expression.chars().any(|c| c.is_ascii_digit());
    let has_spelled_arithmetic = contains_spelled_arithmetic(expression);
    if !has_digit && !has_spelled_arithmetic {
        return false;
    }
    let has_letter = expression.chars().any(char::is_alphabetic);
    let has_operator_symbol = expression
        .contains(['+', '*', '/', '%', '^', '=', '×', '·', '÷', ''])
        || (!has_letter && expression.contains('-'));
    let has_word_operator = contains_word_operator(expression);
    if has_operator_symbol || has_word_operator {
        return true;
    }
    let has_currency_symbol = expression.contains(['$', '', '¥', '', '']);
    let looks_like_conversion = lower.contains(" to ")
        || lower.contains(" into ")
        || lower.contains(" convert ")
        || lower.contains(" exchange ");
    if has_currency_symbol && has_letter && !explicit && !looks_like_conversion {
        return false;
    }
    let has_known_calculator_word = [
        " sqrt",
        " sin",
        " cos",
        " tan",
        " log",
        " ln",
        " usd ",
        " eur ",
        " rub ",
        " dollars",
        " dollar",
        " euros",
        " euro",
        " rubles",
        " ruble",
        " kg ",
        " kb ",
        " mb ",
        " ms ",
        " seconds",
        " second",
        " minutes",
        " minute",
        " hours",
        " hour",
        " days",
        " day",
        " grams",
        " gram",
        " months",
        " month",
        " tons",
        " ton",
        "руб",
        "доллар",
        "евро",
        "тонн",
        "кг",
        "феврал",
        "январ",
        "месяц",
        "месяцев",
        "день",
        "дней",
        "换成",
        "兑换成",
        "转换为",
        "美元",
        "欧元",
        "公斤",
        "二月",
        "一月",
        "个月",
        "",
        "ग्राम",
        "किलोग्राम",
        "डॉलर",
        "यूरो",
        "फरवरी",
        "जनवरी",
        "महीने",
        "दिन",
    ]
    .iter()
    .any(|signal| lower.contains(signal));
    if has_known_calculator_word {
        return true;
    }
    explicit && !has_letter
}

fn contains_spelled_arithmetic(expression: &str) -> bool {
    let lower = format!(" {} ", expression.to_lowercase());
    let has_number_word = [
        " zero ",
        " one ",
        " two ",
        " three ",
        " four ",
        " five ",
        " six ",
        " seven ",
        " eight ",
        " nine ",
        " ten ",
        " ноль ",
        " нуль ",
        " один ",
        " одна ",
        " одно ",
        " два ",
        " две ",
        " три ",
        " четыре ",
        " пять ",
        " шесть ",
        " семь ",
        " восемь ",
        " девять ",
        " десять ",
    ]
    .iter()
    .any(|number| lower.contains(number));
    has_number_word && contains_word_operator(expression)
}

/// Pull calculation expressions out of a natural-language prompt. Returns an
/// empty vector when the prompt does not look like a calculator request, so
/// the solver can fall through to other specialized handlers.
#[must_use]
pub fn calculation_expression_candidates(prompt: &str) -> Vec<CalculationCandidate> {
    let trimmed = trim_prompt_punctuation(prompt);
    if trimmed.is_empty() {
        return Vec::new();
    }
    let (stripped, explicit, interpretations) = strip_calculation_wrappers(trimmed);
    let mut candidates = Vec::new();
    if !stripped.is_empty() && has_calculation_signal(&stripped, explicit) {
        candidates.push(CalculationCandidate {
            expression: stripped,
            explicit,
            interpretations,
        });
    }
    if trimmed
        != candidates
            .first()
            .map(|candidate| candidate.expression.as_str())
            .unwrap_or_default()
        && has_calculation_signal(trimmed, false)
    {
        candidates.push(CalculationCandidate {
            expression: trimmed.to_owned(),
            explicit: false,
            interpretations: Vec::new(),
        });
    }
    candidates
}