formal-ai 0.187.0

Formal symbolic AI implementation with OpenAI-compatible APIs
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
//! Hidden-number interval riddles translated into linear constraints.

use std::fmt::Write as _;

use crate::engine::{normalize_prompt, SymbolicAnswer};
use crate::event_log::EventLog;
use crate::language::detect as detect_language;
use crate::proof_engine::{
    attempt_proof_with_config, render_outcome_with_config, ProofRenderConfig,
};
use crate::solver_handlers::finalize_simple;

#[derive(Clone, Copy, Debug)]
struct Bound {
    value: i64,
    inclusive: bool,
}

impl Bound {
    const fn lower_operator(self) -> &'static str {
        if self.inclusive {
            ">="
        } else {
            ">"
        }
    }

    const fn upper_operator(self) -> &'static str {
        if self.inclusive {
            "<="
        } else {
            "<"
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct IntervalBounds {
    lower: Bound,
    upper: Bound,
}

pub fn try_number_riddle(
    prompt: &str,
    normalized: &str,
    log: &mut EventLog,
) -> Option<SymbolicAnswer> {
    let lowercased = prompt
        .chars()
        .flat_map(char::to_lowercase)
        .collect::<String>();
    let cleaned = normalize_prompt(normalized);
    if !looks_like_number_riddle(&cleaned, &lowercased) {
        return None;
    }

    let bounds = extract_interval_bounds(&cleaned, &lowercased)?;
    let language = detect_language(prompt).slug();
    let statement = formal_statement(bounds);
    let outcome = attempt_proof_with_config(
        prompt,
        &statement,
        language,
        false,
        false,
        ProofRenderConfig::default(),
    );
    let formal_check = render_outcome_with_config(&outcome, language, ProofRenderConfig::default());
    let integer_solutions = integer_solutions(bounds);
    let body = render_interval_answer(
        language,
        bounds,
        &integer_solutions,
        &statement,
        &formal_check,
    );

    log.append(
        "reasoning:number_constraint",
        "hidden_number_interval".to_owned(),
    );
    log.append("formalization:linear_constraint", statement);
    Some(finalize_simple(
        prompt,
        log,
        "number_constraint_reasoning",
        "response:number_constraint_reasoning",
        &body,
        0.86,
    ))
}

fn looks_like_number_riddle(cleaned: &str, source: &str) -> bool {
    let mentions_number = contains_any(cleaned, &["число", "number", "integer"]);
    let asks_identity = contains_any(
        cleaned,
        &[
            "что это за число",
            "какое это число",
            "какое число",
            "what is the number",
            "what number",
            "which number",
        ],
    );
    let hidden_number = contains_any(
        cleaned,
        &[
            "загадал",
            "загадала",
            "задумал",
            "задумала",
            "i guessed",
            "i picked",
            "i chose",
            "i thought of",
        ],
    );
    let has_bounds = contains_any(
        cleaned,
        &[
            "больше",
            "более",
            "меньше",
            "менее",
            "greater than",
            "more than",
            "less than",
            "at least",
            "at most",
        ],
    ) || contains_any(source, &[">", "<", "", ""]);

    mentions_number && has_bounds && (asks_identity || hidden_number)
}

fn contains_any(text: &str, needles: &[&str]) -> bool {
    needles.iter().any(|needle| text.contains(needle))
}

fn extract_interval_bounds(word_text: &str, symbol_text: &str) -> Option<IntervalBounds> {
    let lower = find_bound(
        word_text,
        &[
            ("больше или равно", true),
            ("более или равно", true),
            ("не меньше", true),
            ("not less than", true),
            ("greater than or equal to", true),
            ("more than or equal to", true),
            ("at least", true),
            ("больше", false),
            ("более", false),
            ("greater than", false),
            ("more than", false),
        ],
    )
    .or_else(|| find_bound(symbol_text, &[(">=", true), (">", false)]))?;
    let upper = find_bound(
        word_text,
        &[
            ("меньше или равно", true),
            ("менее или равно", true),
            ("не больше", true),
            ("not more than", true),
            ("less than or equal to", true),
            ("at most", true),
            ("меньше", false),
            ("менее", false),
            ("less than", false),
        ],
    )
    .or_else(|| find_bound(symbol_text, &[("<=", true), ("<", false)]))?;

    Some(IntervalBounds { lower, upper })
}

fn find_bound(text: &str, phrases: &[(&str, bool)]) -> Option<Bound> {
    phrases.iter().find_map(|(phrase, inclusive)| {
        find_number_after_phrase(text, phrase).map(|value| Bound {
            value,
            inclusive: *inclusive,
        })
    })
}

fn find_number_after_phrase(text: &str, phrase: &str) -> Option<i64> {
    for (index, _) in text.match_indices(phrase) {
        if !phrase_has_boundary(text, index, phrase) {
            continue;
        }
        let tail = &text[index + phrase.len()..];
        if let Some(value) = parse_leading_integer(tail) {
            return Some(value);
        }
    }
    None
}

fn phrase_has_boundary(text: &str, index: usize, phrase: &str) -> bool {
    let before_ok = text[..index]
        .chars()
        .next_back()
        .map_or(true, |character| !character.is_alphanumeric());
    let after_index = index + phrase.len();
    let after_ok = text[after_index..]
        .chars()
        .next()
        .map_or(true, |character| !character.is_alphanumeric());
    before_ok && after_ok && !is_negated_strict_bound(text, index, phrase)
}

fn is_negated_strict_bound(text: &str, index: usize, phrase: &str) -> bool {
    if !matches!(phrase, "больше" | "меньше" | "more than" | "less than") {
        return false;
    }
    text[..index]
        .split_whitespace()
        .next_back()
        .is_some_and(|word| matches!(word, "не" | "not"))
}

fn parse_leading_integer(text: &str) -> Option<i64> {
    let trimmed = text.trim_start_matches(|character: char| {
        character.is_whitespace() || matches!(character, ':' | ',' | '=')
    });
    let mut end = 0usize;
    for (index, character) in trimmed.char_indices() {
        if index == 0 && character == '-' {
            end = character.len_utf8();
            continue;
        }
        if character.is_ascii_digit() {
            end = index + character.len_utf8();
            continue;
        }
        break;
    }
    if end == 0 || trimmed[..end].ends_with('-') {
        return None;
    }
    trimmed[..end].parse().ok()
}

fn formal_statement(bounds: IntervalBounds) -> String {
    format!(
        "x {} {} and x {} {} is satisfiable",
        bounds.lower.lower_operator(),
        bounds.lower.value,
        bounds.upper.upper_operator(),
        bounds.upper.value
    )
}

enum IntegerSolutions {
    None,
    Unique(i64),
    Multiple(Vec<i64>),
    Range { start: i64, end: i64 },
}

fn integer_solutions(bounds: IntervalBounds) -> IntegerSolutions {
    let start = if bounds.lower.inclusive {
        bounds.lower.value
    } else {
        bounds.lower.value.saturating_add(1)
    };
    let end = if bounds.upper.inclusive {
        bounds.upper.value
    } else {
        bounds.upper.value.saturating_sub(1)
    };
    if start > end {
        return IntegerSolutions::None;
    }
    if start == end {
        return IntegerSolutions::Unique(start);
    }
    if end.saturating_sub(start) > 20 {
        return IntegerSolutions::Range { start, end };
    }
    IntegerSolutions::Multiple((start..=end).collect())
}

fn render_interval_answer(
    language: &str,
    bounds: IntervalBounds,
    integer_solutions: &IntegerSolutions,
    statement: &str,
    formal_check: &str,
) -> String {
    match language {
        "ru" => render_interval_answer_ru(bounds, integer_solutions, statement, formal_check),
        _ => render_interval_answer_en(bounds, integer_solutions, statement, formal_check),
    }
}

fn render_interval_answer_ru(
    bounds: IntervalBounds,
    integer_solutions: &IntegerSolutions,
    statement: &str,
    formal_check: &str,
) -> String {
    let integer_line = match integer_solutions {
        IntegerSolutions::Unique(only) => {
            format!("Если это задача про целое число, единственный ответ: {only}.")
        }
        IntegerSolutions::None => String::from("Если это задача про целое число, решения нет."),
        IntegerSolutions::Range { start, end } => format!(
            "Если это задача про целые числа, ответ не единственный: подходит любое целое от {start} до {end}."
        ),
        IntegerSolutions::Multiple(candidates) => format!(
            "Если это задача про целые числа, ответ не единственный: подходят {}.",
            format_candidates(candidates)
        ),
    };
    let real_line = real_domain_line_ru(bounds);
    format!(
        "{integer_line}\n\n\
         Формализация над целыми: x in Z, x {} {}, x {} {}. \
         Проверяемая форма для решателя: `{statement}`.\n\n\
         {real_line}\n\n\
         Формальная проверка relative-meta-logic / SMT:\n{formal_check}",
        bounds.lower.lower_operator(),
        bounds.lower.value,
        bounds.upper.upper_operator(),
        bounds.upper.value
    )
}

fn render_interval_answer_en(
    bounds: IntervalBounds,
    integer_solutions: &IntegerSolutions,
    statement: &str,
    formal_check: &str,
) -> String {
    let integer_line = match integer_solutions {
        IntegerSolutions::Unique(only) => {
            format!("If this is an integer-number riddle, the unique answer is {only}.")
        }
        IntegerSolutions::None => {
            String::from("If this is an integer-number riddle, there is no solution.")
        }
        IntegerSolutions::Range { start, end } => format!(
            "If this is an integer-number riddle, the answer is not unique: every integer from {start} through {end} fits."
        ),
        IntegerSolutions::Multiple(candidates) => format!(
            "If this is an integer-number riddle, the answer is not unique: {} all fit.",
            format_candidates(candidates)
        ),
    };
    let real_line = real_domain_line_en(bounds);
    format!(
        "{integer_line}\n\n\
         Integer formalization: x in Z, x {} {}, x {} {}. \
         Solver form: `{statement}`.\n\n\
         {real_line}\n\n\
         Formal relative-meta-logic / SMT check:\n{formal_check}",
        bounds.lower.lower_operator(),
        bounds.lower.value,
        bounds.upper.upper_operator(),
        bounds.upper.value
    )
}

fn real_domain_line_ru(bounds: IntervalBounds) -> String {
    if has_multiple_real_solutions(bounds) {
        format!(
            "Если разрешены вещественные числа, ответ не единственный: например, x = {} тоже подходит.",
            real_example(bounds)
        )
    } else if has_single_real_solution(bounds) {
        format!(
            "На вещественных числах тоже есть единственное решение: x = {}.",
            bounds.lower.value
        )
    } else {
        String::from("На вещественных числах эти ограничения несовместимы.")
    }
}

fn real_domain_line_en(bounds: IntervalBounds) -> String {
    if has_multiple_real_solutions(bounds) {
        format!(
            "If real numbers are allowed, the answer is not unique; for example, x = {} also fits.",
            real_example(bounds)
        )
    } else if has_single_real_solution(bounds) {
        format!(
            "Over the real numbers there is also a single solution: x = {}.",
            bounds.lower.value
        )
    } else {
        String::from("Over the real numbers, these constraints are inconsistent.")
    }
}

const fn has_multiple_real_solutions(bounds: IntervalBounds) -> bool {
    bounds.lower.value < bounds.upper.value
}

const fn has_single_real_solution(bounds: IntervalBounds) -> bool {
    bounds.lower.value == bounds.upper.value && bounds.lower.inclusive && bounds.upper.inclusive
}

fn real_example(bounds: IntervalBounds) -> String {
    format_half(i128::from(bounds.lower.value) * 2 + 1)
}

fn format_half(half_steps: i128) -> String {
    let sign = if half_steps < 0 { "-" } else { "" };
    let magnitude = half_steps.abs();
    let whole = magnitude / 2;
    if magnitude % 2 == 0 {
        format!("{sign}{whole}")
    } else {
        format!("{sign}{whole}.5")
    }
}

fn format_candidates(candidates: &[i64]) -> String {
    let mut rendered = String::new();
    for (index, candidate) in candidates.iter().enumerate() {
        if index > 0 {
            let _ = write!(rendered, ", ");
        }
        let _ = write!(rendered, "{candidate}");
    }
    rendered
}