Building a Reliable Math Computation System with LLMs
Machine LearningModel answerLast updated
Architect a production system that uses language models to solve mathematical problems by orchestrating symbolic computation, code execution, and tool integration.
You're building a production service that accepts mathematical questions in natural language and returns accurate numeric answers. The system should handle a range of problems:
- Basic arithmetic: "What is 127 + 483?"
- Series computations: "Calculate the sum of integers from 1 to 500"
- Percentage calculations: "Find 23% of 8,450"
- Multi-step problems: "If I invest $10,000 at 5% annual interest compounded yearly, how much do I have after 6 years?"
Your task is to design the complete system. Address:
- Architecture: How do you decide whether to compute directly, use formulas, or generate code? What components does the system need?
- Tool integration: When and how should the LLM invoke external tools like calculators or interpreters?
- Prompt design: How do you structure prompts to get reliable, parseable outputs?
- Safety: What guardrails prevent malicious inputs or execution risks?
- Evaluation: How do you measure accuracy, track performance over time, and run experiments?
- Error handling: What happens when computation fails or results disagree?
Discuss trade-offs around latency, cost, accuracy, and operational complexity. Be specific about data structures, APIs, and metrics.
Hints
Hint 1
Language models are unreliable at arithmetic; routing to deterministic tools is crucial for correctness
Hint 2
Most queries are simple expressions that don't need an LLM at all—a fast path can handle them directly
Hint 3
Cross-validation techniques like running multiple solvers or self-consistency sampling catch errors before returning wrong answers
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Building a Reliable Math Computation System with LLMs
This problem tests whether you understand LLM limitations in numerical reasoning and can architect a hybrid system that combines language understanding with deterministic computation. Strong answers emphasize reliability over cleverness.
1. Requirements and Scope
Start by clarifying the problem space:
- Input types: Natural language questions containing arithmetic, series, percentages, compound calculations. Confirm whether symbolic algebra or calculus is needed—assume arithmetic and standard formulas only.
- Output format: Exact numeric answer with optional step-by-step explanation. For integers, require exact match; for decimals, accept solutions within relative tolerance of 1e-9.
- Correctness priority: Returning wrong answers is worse than refusing to answer. Target 99.9%+ accuracy on validated problems.
- Performance targets: Handle 50 QPS with p50 latency under 1 second, p95 under 3 seconds. Keep per-query cost below $0.001 for simple operations.
- Safety requirements: No arbitrary code execution on production hosts; sandboxed environment for any generated programs.
The key insight: most queries (60%+ in typical traffic) are simple expressions that should bypass the LLM entirely. The system architecture should reflect this distribution.
2. System Architecture
Build a multi-tier pipeline:
Tier 1: Input Preprocessing
Normalize the input by stripping whitespace, converting unicode operators (×→*, ÷→/, −→-), and standardizing number formats. This creates a canonical representation for caching and routing.
Tier 2: Expression Fast Path
Before invoking any LLM, attempt to parse the input as a pure arithmetic expression. Use an AST-based parser that accepts only numbers, operators (+, -, *, /, **, %), and parentheses. Set safety limits: exponents capped at 1000, expression depth limited to 50 levels.
If parsing succeeds, evaluate using exact arithmetic (Decimal or Fraction types) and return immediately. This handles "127 + 483" in microseconds with perfect accuracy and zero LLM cost.
Tier 3: Intelligent Router
For everything else, use an LLM to classify the problem into execution strategies:
- Formula route: Problems matching known closed-forms (arithmetic series, geometric series, percentage, compound interest). The LLM outputs structured JSON like
{"strategy": "arithmetic_series", "first_term": 1, "last_term": 500, "count": 500}. - Code generation route: Multi-step problems requiring iteration, conditionals, or complex logic. The LLM generates Python code that executes in a sandbox.
- Out-of-scope: Ambiguous, non-mathematical, or adversarial inputs that should be refused.
The router should rarely use "direct answer" mode where the LLM outputs the number itself—language models are unreliable calculators.
Tier 4: Execution Layer
Formula Library: Implement vetted implementations of common patterns:
def arithmetic_series(a1, an, n):
return Fraction(n * (a1 + an), 2)
def compound_interest(principal, rate, periods):
return Decimal(principal) * (Decimal(1) + Decimal(rate)) ** periods
These run in O(1) time and work even for huge ranges like "sum 1 to 10^15".
Code Sandbox: Execute generated Python in an isolated environment:
- Use containers or lightweight VMs (gVisor/Firecracker)
- Whitelist only safe libraries:
math,fractions,decimal,itertools - Block file I/O, network access, and dangerous builtins
- Enforce 2-second CPU timeout and 256MB memory limit
- Parse the AST before execution to reject imports of
os,subprocess,eval
Tier 5: Verification
Cross-check results before returning:
- When both formula and code routes are applicable, run both and compare outputs
- Use self-consistency: generate 3 independent solutions and take majority vote
- Apply sanity checks: magnitude estimates, sign verification, integer property preservation
- If disagreement occurs or confidence is low, return "unable to solve reliably" rather than guessing
3. Prompt Engineering
Design prompts for structured output:
Router prompt (system):
You classify math problems into solution strategies. Respond with valid JSON only.
Available strategies: formula, code, refuse.
For formula, include parameters. For code, this will trigger Python generation.
Code generation prompt (system):
Write a Python function named solve() that returns the numeric answer.
Use Fraction or Decimal for exact arithmetic. Do not print explanations.
Available imports: math, fractions, decimal, itertools.
Include 2-3 few-shot examples per strategy. Use function calling or structured output mode to enforce JSON schema compliance. Set temperature=0 for deterministic routing. Version every prompt string (e.g., code_generator_v12) and log it with each trace.
4. Safety and Guardrails
Resource protection: The expression parser and formula library have hard limits on input size and computational complexity. The sandbox enforces strict CPU and memory quotas.
Input validation: The router classifies scope before execution. Requests that are clearly non-mathematical or contain injection attempts are refused at routing time.
Secure execution: Generated code never accesses the filesystem, network, or host environment. AST analysis blocks dynamic evaluation primitives. Standard library functions are intercepted to prevent shell access.
Rate limiting: Apply per-user and per-IP quotas to prevent abuse.
5. Evaluation Framework
Offline Evaluation
Maintain a test set of 3,000+ problems stratified by difficulty:
- Simple expressions (1,000): "47 + 89", "12 * 15"
- Series and formulas (800): various arithmetic/geometric progressions
- Multi-step word problems (800): percentage, interest, conversions
- Edge cases (400): very large numbers, negative results, division edge cases
Track accuracy by category. Measure routing precision (did we choose the right strategy?) separately from execution accuracy (did we get the right answer?).
Online Evaluation
Log every request with:
- Original question and normalized form
- Router decision and confidence score
- Each tool invocation: prompt version, model, tokens, latency
- Code execution: program text, stdout, errors, runtime
- Verification results: agreement across methods, sanity check outcomes
- Final answer and total latency
Sample 1% of traffic for human review. Flag disagreements between verification methods for manual inspection.
Metrics Dashboard
- Accuracy (primary): exact match rate on labeled eval set, broken down by problem category
- Router accuracy: percentage of correctly chosen strategies
- Latency: p50, p95, p99 by route type
- Cost: LLM tokens and compute cost per solved problem
- Abstention rate: percentage of "couldn't solve" responses
- Error rate: timeouts, parsing failures, sandbox violations
6. Error Handling Strategy
Parsing errors: If the LLM returns malformed JSON, include the parse error in a retry prompt (max 2 attempts).
Execution failures: Sandbox timeouts or runtime errors trigger one repair attempt—send the traceback back to the model with instructions to fix. After exhausting retries, either fall back to an alternative route (formula→code or vice versa) or abstain.
Verification disagreement: When cross-validation shows conflicting answers, check if one has higher confidence. If uncertainty remains, return an error rather than picking randomly.
Calibrated confidence: Track historical accuracy by confidence bucket. If the system reports 90% confidence, it should be correct 90% of the time. Use this to set dynamic thresholds for abstention.
7. Trade-offs and Design Choices
Latency vs. accuracy: Running multiple verification strategies (formula + code, or self-consistency sampling) doubles compute cost but catches errors. For production, verify on problems where the router confidence is below 0.95, but skip verification for high-confidence simple cases.
Model selection: A smaller model (8B parameters) handles routing and simple code generation with 200ms latency. Larger models (70B+) improve accuracy on complex problems but cost 5x more. Consider a cascade: use the small model first, escalate to the large model only on detected failures.
Caching: Cache results keyed by normalized input. For deterministic routes (fast path, formulas), cache aggressively. For code generation, cache only after verification confirms correctness.
Formula library scope: Each new formula type requires implementation, testing, and maintenance. Start with 10-15 common patterns and expand based on observed traffic. Use the code route as a fallback for uncommon calculations.
8. Common Mistakes
- Over-reliance on prompting: Hoping better prompts will make LLMs accurate at arithmetic. They won't—delegate to tools.
- Underestimating the fast path: Parsing "4 + 5" and computing it costs microseconds. Routing it through an LLM costs milliseconds and money.
- Ignoring verification: Returning the first answer without cross-checks leads to embarrassing errors in production.
- Weak sandboxing: Executing arbitrary code on the application host is a critical security vulnerability.
- No experiment tracking: Without versioned prompts and detailed traces, you can't diagnose regressions or run A/B tests.
Summary
A reliable math-solving system routes most traffic through deterministic computation, uses LLMs only for language understanding and code generation, verifies answers before returning them, and measures accuracy rigorously. The architecture prioritizes correctness over cleverness, and treats the LLM as one component in a broader pipeline rather than the entire solution.