Skip to main content

mathsolver/
lib.rs

1//! mathsolver — BYOK AI math solver with independent verification.
2//!
3//! An answer is only `verified: true` when the model's verification
4//! expression (pure arithmetic) is evaluated locally by this crate and
5//! matches the answer numerically. No model output is ever executed as code.
6
7use serde_json::{json, Value};
8use std::fmt;
9
10pub const SYSTEM_PROMPT: &str = "You are a precise math solver.
11Reply with STRICT JSON only, no markdown fences, in this exact shape:
12{\"program\": \"<string>\", \"steps\": [<string>, ...], \"check\": \"<string>\"}
13Rules:
14- \"program\" is a small JavaScript-like program that computes the final answer.
15  One statement per line (or ; separated). Allowed statements:
16      let NAME = EXPRESSION
17      result = EXPRESSION
18  EXPRESSIONs may use numbers, + - * / % ^ ( ), the functions
19  abs sqrt sin cos tan ln log exp floor ceil round min max
20  (log is base 10, ln is natural), the constants pi and e, and any
21  variable defined by an earlier let. The value assigned to result
22  is the answer. Never state the answer as a number in text.
23- \"steps\" is an array of short plain-language explanation strings.
24- \"check\" is a verification expression containing the placeholder {x}.
25  After solving, {x} is replaced by the computed answer and the whole
26  expression must evaluate to 0.
27  For equations, substitute the answer back into the original equation
28  (e.g. 2x+3=11 -> \"2*{x}+3-11\").
29  For arithmetic, recompute via a different path and subtract the answer
30  (e.g. 15% of 80 -> \"80*15/100-{x}\"). Provide \"check\" whenever possible.";
31
32#[derive(Debug, Clone)]
33pub struct SolverError {
34    pub code: &'static str,
35    pub message: String,
36}
37
38impl SolverError {
39    pub fn new(code: &'static str, message: impl Into<String>) -> Self {
40        Self { code, message: message.into() }
41    }
42}
43
44impl fmt::Display for SolverError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "{}: {}", self.code, self.message)
47    }
48}
49
50impl std::error::Error for SolverError {}
51
52#[derive(Debug, Clone)]
53pub struct SolveOptions {
54    pub api_key: String,
55    pub base_url: String,
56    pub model: String,
57}
58
59impl Default for SolveOptions {
60    fn default() -> Self {
61        Self {
62            api_key: String::new(),
63            base_url: "https://api.openai.com/v1".into(),
64            model: "gpt-4o-mini".into(),
65        }
66    }
67}
68
69#[derive(Debug, Clone)]
70pub struct SolveResult {
71    pub answer: f64,
72    pub steps: Vec<String>,
73    pub expression: String,
74    pub evaluated: Option<f64>,
75    pub verified: bool,
76    pub retries: u32,
77}
78
79/* ------------------------------------------------------------------ */
80/* Expression evaluator (recursive descent, no deps)                    */
81/* ------------------------------------------------------------------ */
82
83#[derive(Debug, Clone, PartialEq)]
84enum Tok {
85    Num(f64),
86    Id(String),
87    Op(char),
88}
89
90fn tokenize(src: &str) -> Result<Vec<Tok>, SolverError> {
91    let mut tokens = Vec::new();
92    let mut chars = src.chars().peekable();
93    while let Some(&c) = chars.peek() {
94        if c.is_whitespace() {
95            chars.next();
96            continue;
97        }
98        if c.is_ascii_digit() || c == '.' {
99            let mut num = String::new();
100            while let Some(&d) = chars.peek() {
101                if d.is_ascii_digit() || d == '.' {
102                    num.push(d);
103                    chars.next();
104                } else {
105                    break;
106                }
107            }
108            // scientific notation
109            if let Some(&e) = chars.peek() {
110                if e == 'e' || e == 'E' {
111                    let mut probe = chars.clone();
112                    probe.next();
113                    if let Some(&sign) = probe.peek() {
114                        if sign == '+' || sign == '-' {
115                            probe.next();
116                        }
117                        if probe.peek().map_or(false, |d| d.is_ascii_digit()) {
118                            num.push(e);
119                            chars.next();
120                            if let Some(&s) = chars.peek() {
121                                if s == '+' || s == '-' {
122                                    num.push(s);
123                                    chars.next();
124                                }
125                            }
126                            while let Some(&d) = chars.peek() {
127                                if d.is_ascii_digit() {
128                                    num.push(d);
129                                    chars.next();
130                                } else {
131                                    break;
132                                }
133                            }
134                        }
135                    }
136                }
137            }
138            let value: f64 = num
139                .parse()
140                .map_err(|_| SolverError::new("EXPR_BAD_NUMBER", format!("bad number {}", num)))?;
141            tokens.push(Tok::Num(value));
142            continue;
143        }
144        if c.is_ascii_alphabetic() || c == '_' {
145            let mut id = String::new();
146            while let Some(&d) = chars.peek() {
147                if d.is_ascii_alphanumeric() || d == '_' {
148                    id.push(d);
149                    chars.next();
150                } else {
151                    break;
152                }
153            }
154            tokens.push(Tok::Id(id));
155            continue;
156        }
157        if "+-*/%^(),".contains(c) {
158            tokens.push(Tok::Op(c));
159            chars.next();
160            continue;
161        }
162        return Err(SolverError::new("EXPR_BAD_CHAR", format!("unexpected character '{}'", c)));
163    }
164    Ok(tokens)
165}
166
167fn apply_fn(name: &str, args: &[f64]) -> Result<f64, SolverError> {
168    let (a0, _a1) = (args.first().copied().unwrap_or(f64::NAN), args.get(1).copied().unwrap_or(f64::NAN));
169    let v = match name {
170        "abs" => a0.abs(),
171        "sqrt" => a0.sqrt(),
172        "sin" => a0.sin(),
173        "cos" => a0.cos(),
174        "tan" => a0.tan(),
175        "ln" => a0.ln(),
176        "log" => a0.log10(),
177        "exp" => a0.exp(),
178        "floor" => a0.floor(),
179        "ceil" => a0.ceil(),
180        "round" => a0.round(),
181        "min" => args.iter().cloned().fold(f64::INFINITY, f64::min),
182        "max" => args.iter().cloned().fold(f64::NEG_INFINITY, f64::max),
183        _ => return Err(SolverError::new("EXPR_UNKNOWN_FUNC", format!("unknown function {}", name))),
184    };
185    Ok(v)
186}
187
188use std::collections::HashMap;
189
190pub type Env = HashMap<String, f64>;
191
192/// Evaluate a pure arithmetic expression string to a number (no variables).
193pub fn eval_expression(src: &str) -> Result<f64, SolverError> {
194    eval_expression_with(src, &Env::new())
195}
196
197/// Evaluate with variable bindings from let-statements.
198pub fn eval_expression_with(src: &str, env: &Env) -> Result<f64, SolverError> {
199    if src.trim().is_empty() {
200        return Err(SolverError::new("EXPR_EMPTY", "empty expression"));
201    }
202    let tokens = tokenize(src)?;
203    let mut pos = 0usize;
204
205    fn peek(tokens: &[Tok], pos: usize) -> Option<&Tok> {
206        tokens.get(pos)
207    }
208
209    fn eat(tokens: &[Tok], pos: &mut usize) -> Result<Tok, SolverError> {
210        let tok = tokens.get(*pos).cloned();
211        match tok {
212            Some(t) => {
213                *pos += 1;
214                Ok(t)
215            }
216            None => Err(SolverError::new("EXPR_SYNTAX", "expected more tokens")),
217        }
218    }
219
220    fn expr(tokens: &[Tok], pos: &mut usize, env: &Env) -> Result<f64, SolverError> {
221        let mut v = term(tokens, pos, env)?;
222        while let Some(Tok::Op(op)) = peek(tokens, *pos) {
223            if *op != '+' && *op != '-' {
224                break;
225            }
226            eat(tokens, pos)?;
227            let r = term(tokens, pos, env)?;
228            v = if *op == '+' { v + r } else { v - r };
229        }
230        Ok(v)
231    }
232
233    fn term(tokens: &[Tok], pos: &mut usize, env: &Env) -> Result<f64, SolverError> {
234        let mut v = unary(tokens, pos, env)?;
235        while let Some(Tok::Op(op)) = peek(tokens, *pos) {
236            if *op != '*' && *op != '/' && *op != '%' {
237                break;
238            }
239            eat(tokens, pos)?;
240            let r = unary(tokens, pos, env)?;
241            v = match op {
242                '*' => v * r,
243                '/' => v / r,
244                _ => v % r,
245            };
246        }
247        Ok(v)
248    }
249
250    fn unary(tokens: &[Tok], pos: &mut usize, env: &Env) -> Result<f64, SolverError> {
251        if let Some(Tok::Op('-')) = peek(tokens, *pos) {
252            eat(tokens, pos)?;
253            return Ok(-unary(tokens, pos, env)?);
254        }
255        if let Some(Tok::Op('+')) = peek(tokens, *pos) {
256            eat(tokens, pos)?;
257            return unary(tokens, pos, env);
258        }
259        power(tokens, pos, env)
260    }
261
262    fn power(tokens: &[Tok], pos: &mut usize, env: &Env) -> Result<f64, SolverError> {
263        let base = atom(tokens, pos, env)?;
264        if let Some(Tok::Op('^')) = peek(tokens, *pos) {
265            eat(tokens, pos)?;
266            let exp = unary(tokens, pos, env)?; // right associative
267            return Ok(base.powf(exp));
268        }
269        Ok(base)
270    }
271
272    fn atom(tokens: &[Tok], pos: &mut usize, env: &Env) -> Result<f64, SolverError> {
273        match eat(tokens, pos)? {
274            Tok::Num(v) => Ok(v),
275            Tok::Id(id) => {
276                if let Some(v) = env.get(id.as_str()) {
277                    return Ok(*v);
278                }
279                let name = id.to_lowercase();
280                if let Some(Tok::Op('(')) = peek(tokens, *pos) {
281                    eat(tokens, pos)?;
282                    let mut args = vec![expr(tokens, pos, env)?];
283                    while let Some(Tok::Op(',')) = peek(tokens, *pos) {
284                        eat(tokens, pos)?;
285                        args.push(expr(tokens, pos, env)?);
286                    }
287                    if !matches!(eat(tokens, pos)?, Tok::Op(')')) {
288                        return Err(SolverError::new("EXPR_SYNTAX", "expected )"));
289                    }
290                    apply_fn(&name, &args)
291                } else if name == "pi" {
292                    Ok(std::f64::consts::PI)
293                } else if name == "e" {
294                    Ok(std::f64::consts::E)
295                } else {
296                    Err(SolverError::new("EXPR_UNKNOWN_ID", format!("unknown identifier {}", name)))
297                }
298            }
299            Tok::Op('(') => {
300                let v = expr(tokens, pos, env)?;
301                if !matches!(eat(tokens, pos)?, Tok::Op(')')) {
302                    return Err(SolverError::new("EXPR_SYNTAX", "expected )"));
303                }
304                Ok(v)
305            }
306            Tok::Op(other) => Err(SolverError::new("EXPR_SYNTAX", format!("unexpected token {}", other))),
307        }
308    }
309
310    let value = expr(&tokens, &mut pos, env)?;
311    if pos != tokens.len() {
312        return Err(SolverError::new("EXPR_TRAILING", "trailing tokens in expression"));
313    }
314    if !value.is_finite() {
315        return Err(SolverError::new("EXPR_NON_FINITE", "expression evaluated to non-finite value"));
316    }
317    Ok(value)
318}
319
320/* ------------------------------------------------------------------ */
321/* JSON helpers                                                         */
322/* ------------------------------------------------------------------ */
323
324struct Parsed {
325    program: String,
326    steps: Vec<String>,
327    check: Option<String>,
328}
329
330fn parse_solver_json(text: &str) -> Result<Parsed, SolverError> {
331    let start = text.find('{').ok_or_else(|| SolverError::new("INVALID_JSON", "no JSON object in reply"))?;
332    let end = text.rfind('}').ok_or_else(|| SolverError::new("INVALID_JSON", "no JSON object in reply"))?;
333    let value: Value = serde_json::from_str(&text[start..=end])
334        .map_err(|_| SolverError::new("INVALID_JSON", "reply was not valid JSON"))?;
335    let program = value["program"]
336        .as_str()
337        .ok_or_else(|| SolverError::new("INVALID_JSON", "missing program"))?
338        .to_string();
339    let check = value["check"].as_str().filter(|s| !s.trim().is_empty()).map(|s| s.to_string());
340    let steps = match &value["steps"] {
341        Value::Array(arr) => arr
342            .iter()
343            .map(|s| s.as_str().unwrap_or_default().to_string())
344            .collect(),
345        _ => Vec::new(),
346    };
347    Ok(Parsed { program, steps, check })
348}
349
350/// Execute a model-generated JS-dialect program (let / assignment / result).
351pub fn run_program(src: &str) -> Result<f64, SolverError> {
352    if src.trim().is_empty() {
353        return Err(SolverError::new("PROGRAM_EMPTY", "empty program"));
354    }
355    let mut env = Env::new();
356    let mut result_defined = false;
357    let mut last_value: Option<f64> = None;
358    for line in src.split(['\n', ';']) {
359        let line = line.trim();
360        if line.is_empty() {
361            continue;
362        }
363        if let Some(rest) = line.strip_prefix("let ") {
364            if let Some(eq) = rest.find('=') {
365                let name = rest[..eq].trim();
366                let val = eval_expression_with(rest[eq + 1..].trim(), &env)?;
367                env.insert(name.to_string(), val);
368                if name == "result" {
369                    result_defined = true;
370                }
371                continue;
372            }
373        }
374        if let Some(eq) = line.find('=') {
375            let name = line[..eq].trim();
376            let is_ident = !name.is_empty()
377                && name.chars().next().map_or(false, |c| c.is_alphabetic() || c == '_')
378                && name.chars().all(|c| c.is_alphanumeric() || c == '_');
379            if is_ident {
380                let val = eval_expression_with(line[eq + 1..].trim(), &env)?;
381                env.insert(name.to_string(), val);
382                if name == "result" {
383                    result_defined = true;
384                }
385                continue;
386            }
387        }
388        last_value = Some(eval_expression_with(line, &env)?);
389    }
390    if result_defined {
391        return Ok(env["result"]);
392    }
393    if let Some(v) = last_value {
394        return Ok(v);
395    }
396    Err(SolverError::new("PROGRAM_NO_RESULT", "program produced no result"))
397}
398
399/// Substitute {x} with the computed answer; passes when value ~ 0.
400pub fn run_check(check_src: &str, answer: f64) -> Result<(f64, bool), SolverError> {
401    let substituted = check_src.replace("{x}", &format!("({})", answer));
402    let value = eval_expression(&substituted)?;
403    let passed = value.abs() <= 1e-6 * answer.abs().max(1.0);
404    Ok((value, passed))
405}
406
407fn numerically_equal(a: f64, b: f64) -> bool {
408    (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0)
409}
410
411/* ------------------------------------------------------------------ */
412/* Client (instantiate once, solve many)                                */
413/* ------------------------------------------------------------------ */
414
415pub type TransportFn = Box<dyn Fn(&str, &str, &str) -> Result<String, SolverError> + Send + Sync>;
416
417pub fn default_transport(url: &str, body: &str, api_key: &str) -> Result<String, SolverError> {
418    let resp = ureq::post(url)
419        .set("Content-Type", "application/json")
420        .set("Authorization", &format!("Bearer {}", api_key))
421        .timeout(std::time::Duration::from_secs(60))
422        .send_string(body)
423        .map_err(|e| SolverError::new("HTTP_ERROR", e.to_string()))?;
424    let text = resp
425        .into_string()
426        .map_err(|_| SolverError::new("HTTP_ERROR", "failed reading API response"))?;
427    let data: Value = serde_json::from_str(&text)
428        .map_err(|_| SolverError::new("HTTP_ERROR", "invalid JSON from API"))?;
429    data["choices"][0]["message"]["content"]
430        .as_str()
431        .map(|s| s.to_string())
432        .ok_or_else(|| SolverError::new("HTTP_ERROR", "API response missing message content"))
433}
434
435/// BYOK client for an OpenAI-compatible endpoint.
436///
437/// ```no_run
438/// let solver = mathsolver::MathSolver::new("sk-...", "https://api.deepseek.com/v1")
439///     .unwrap().model("deepseek-chat");
440/// let r = solver.solve("2x + 3 = 11, solve for x").unwrap(); // r.verified == true
441/// ```
442pub struct MathSolver {
443    api_key: String,
444    base_url: String,
445    model: String,
446    transport: TransportFn,
447}
448
449impl std::fmt::Debug for MathSolver {
450    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
451        f.debug_struct("MathSolver")
452            .field("base_url", &self.base_url)
453            .field("model", &self.model)
454            .finish_non_exhaustive()
455    }
456}
457
458impl MathSolver {
459    /// Create a client with the built-in HTTP transport (ureq).
460    pub fn new(api_key: &str, base_url: &str) -> Result<Self, SolverError> {
461        Self::with_transport(api_key, base_url, default_transport)
462    }
463
464    /// Create a client with an injected transport `(url, body_json, api_key) -> model text`.
465    pub fn with_transport<F>(api_key: &str, base_url: &str, transport: F) -> Result<Self, SolverError>
466    where
467        F: Fn(&str, &str, &str) -> Result<String, SolverError> + Send + Sync + 'static,
468    {
469        if api_key.is_empty() {
470            return Err(SolverError::new("NO_API_KEY", "api_key is required (BYOK)"));
471        }
472        let base = base_url.trim_end_matches('/');
473        if !(base.starts_with("http://") || base.starts_with("https://")) {
474            return Err(SolverError::new("BAD_BASE_URL", "base_url must be an http(s) URL, e.g. https://api.deepseek.com/v1"));
475        }
476        Ok(Self {
477            api_key: api_key.to_string(),
478            base_url: base.to_string(),
479            model: "gpt-4o-mini".to_string(),
480            transport: Box::new(transport),
481        })
482    }
483
484    /// Builder-style model override.
485    pub fn model(mut self, model: impl Into<String>) -> Self {
486        self.model = model.into();
487        self
488    }
489
490    /// Solve a math problem. The answer is the output of executing the model's
491    /// program; `verified` is true only when the check expression passes
492    /// (equations: answer substituted back must satisfy the original equation).
493    pub fn solve(&self, problem: &str) -> Result<SolveResult, SolverError> {
494        if problem.trim().is_empty() {
495            return Err(SolverError::new("NO_PROBLEM", "problem must be non-empty"));
496        }
497        let url = format!("{}/chat/completions", self.base_url);
498
499        let mut messages = vec![
500            json!({"role": "system", "content": SYSTEM_PROMPT}),
501            json!({"role": "user", "content": problem}),
502        ];
503        let call = |messages: &Vec<Value>| -> Result<String, SolverError> {
504            let body = json!({"model": self.model, "messages": messages, "temperature": 0}).to_string();
505            (self.transport)(&url, &body, &self.api_key)
506        };
507
508        let mut parsed = match parse_solver_json(&call(&messages)?) {
509            Ok(p) => p,
510            Err(e) if e.code == "INVALID_JSON" => {
511                messages.push(json!({"role": "assistant", "content": "invalid JSON"}));
512                messages.push(json!({"role": "user", "content": "Your reply was not valid JSON. Reply again with the exact strict JSON shape."}));
513                parse_solver_json(&call(&messages)?)?
514            }
515            Err(e) => return Err(e),
516        };
517
518        // attempt: execute program + run check; reports ok/err without throwing.
519        let attempt = |p: &Parsed| -> Result<(f64, Option<f64>, bool), SolverError> {
520            let answer = run_program(&p.program)?;
521            let mut check_value = None;
522            let mut verified = false;
523            if let Some(check) = &p.check {
524                let (v, passed) = run_check(check, answer)?;
525                check_value = Some(v);
526                verified = passed;
527            }
528            Ok((answer, check_value, verified))
529        };
530
531        let mut program_error: Option<SolverError> = None;
532        let (mut answer, mut check_value, mut verified) = match attempt(&parsed) {
533            Ok(t) => t,
534            Err(e) => { program_error = Some(e); (f64::NAN, None, false) }
535        };
536        let first_ok = program_error.is_none();
537
538        let mut retries = 0u32;
539        if !first_ok || !verified {
540            retries = 1;
541            let reason = if !first_ok {
542                format!("program failed to execute ({})", program_error.as_ref().map(|e| e.message.clone()).unwrap_or_default())
543            } else {
544                format!("check evaluated to {:?} instead of 0", check_value)
545            };
546            messages.push(json!({"role": "assistant", "content": serde_json::to_string(&json!({
547                "program": parsed.program, "steps": parsed.steps, "check": parsed.check
548            })).unwrap_or_default()}));
549            messages.push(json!({"role": "user", "content": format!(
550                "Your submission failed verification: {}. Re-derive the problem carefully and reply again with the same strict JSON shape.", reason
551            )}));
552            match parse_solver_json(&call(&messages)?) {
553                Ok(second) => match attempt(&second) {
554                    Ok((a, cv, v)) => {
555                        parsed = second;
556                        answer = a; check_value = cv; verified = v;
557                    }
558                    Err(e) => return Err(e), // PROGRAM_* persisted after retry
559                },
560                Err(e) => return Err(e),
561            }
562        }
563
564        Ok(SolveResult {
565            answer,
566            steps: parsed.steps,
567            expression: parsed.program,
568            evaluated: check_value,
569            verified,
570            retries,
571        })
572    }
573}