How to Build an AI Math Solving and Tutoring Service
This article explains how to evaluate, architect, and integrate AI math capabilities into a production product. It compares general-purpose large language models with math-specific technologies such as formula recognition and photo-based solving, then breaks down the four capabilities that must work together reliably: input understanding, step-by-step reasoning, geometric figure rendering, and answer verification. You will find selection criteria, a dual-engine architecture that combines perception, reasoning, and symbolic computation, a four-step pipeline for geometry problems, layered system design with engineering details such as asynchronous execution and caching, quality and safety controls, and a three-layer evaluation framework for making data-driven technology decisions.
1. Introduction: From “Getting the Answer” to “Teaching It Clearly”
In math learning scenarios, AI is shifting from an occasional answer lookup tool to an always-available practice companion. A common pattern developers see when evaluating such applications: a demo solves one problem neatly, but when a student submits a handwritten photo or a geometry problem, the response misses the point entirely.
So when deciding whether an AI math capability is ready to integrate into your product, the question is not simply “Can it solve one problem correctly?” It is whether four capabilities can combine reliably: input understanding, step-by-step reasoning, geometric figure presentation, and answer verification.
This article first compares the technical approaches neutrally — the general-purpose route represented by general large language models, and the math-specific route represented by formula recognition and photo-based problem solving. It then breaks down the key capabilities from an engineering perspective, and finally presents a system architecture and an evaluation plan.
2. Selection Methodology: Three Core Criteria
The original screening criteria for AI math solving tools were: does it support geometry problems, does it provide complete steps, and can it be integrated into your product. These three correspond to capability boundaries, teaching quality, and engineering feasibility, and can be turned into a concrete checklist:
| Evaluation Dimension | Key Question | Acceptance Method |
|---|---|---|
| Problem Understanding | Is recognition and comprehension stable with printed text, handwriting, multi-line formulas, tilted photos, shadows, and mixed problem types? | Build a real-world sample set covering different lighting, handwriting, and layouts |
| Reasoning Quality | Are the steps complete and logically coherent? Does it skip steps or use methods beyond the curriculum? Does it flag common mistakes? | Have teachers score each step individually, rather than only checking the final answer |
| Geometry Support | Can it accurately identify figure elements, generate or complete figures, and explain why an auxiliary line is drawn? | Test by geometry problem type and report pass rates separately |
| Structure and Integrability | Can it output stable structured results, support streaming responses, and handle batch calls? | Verify response format, exception handling, and retry mechanisms |
| Controllability and Compliance | Is the content age-appropriate, free of irrelevant material beyond solving the problem, and how is call data anonymized? | Review content moderation policies, data retention policies, and access control policies |
Pay particular attention to handwriting recognition and geometry figures — these two are the most easily masked by the general halo of a general-purpose model’s capabilities.
3. Route One: Capabilities and Limits of General-Purpose LLMs
The strength of general-purpose LLMs is generalization: broad coverage of problem types including algebraic operations, equation solving, function analysis, and word problems, plus the ability to explain in natural language “why we solve it this way.” They also typically support custom instructions and structured output, which makes secondary development easier.
Their weaknesses, however, are concentrated in geometry and complex reasoning:
- Figure understanding depends on vision capability. Pure text models cannot see figures at all. Multimodal models can accept images, but their parsing of complex figures (solid geometry, function graphs, and figures overlaid with geometry) remains unstable.
- Auxiliary line explanation is “visible but not explainable.” Even when a model solves a geometry problem, it can usually only describe it in words like “connect AD” or “extend BC to intersect the circle at point E,” with no figure students can compare against directly.
- Long-chain reasoning is prone to hallucination. When there are many steps, the model may invent theorems or conditions that do not exist.
- Generating figures can introduce new errors. If the model is asked to produce an image or SVG code directly, the lines, angles, and positional relationships may not match the problem statement. Example of the problem:
<!-- Problem: In triangle ABC, D is the midpoint of BC. Draw the median AD. --><!-- Wrong example: the model draws a random triangle whose A, B, C positions do not match the problem --><polygon points="0,0 200,40 130,150" fill="none" stroke="black"/>
A safer approach is to decompose a geometry problem into: recognize geometry elements → generate a geometry description → have a program draw the figure → have the text explanation reference numbered figures. The model does not output the final figure directly; it outputs figure parameters, and a deterministic renderer draws them. The error-prone drawing steps in geometry are handed to rule-based programs.
4. Route Two: Capabilities and Limits of Math-Specific Technologies
Math-specific technologies represented by formula recognition and photo-based problem solving typically consist of three types of components:
- Math formula recognition: converts formulas in an image into editable formula markup language or structured expressions. This is the foundation for digitizing printed and handwritten math content;
- Problem-solving engine: performs symbolic computation and step-by-step derivation on the recognition result, outputting solutions in a fixed format;
- Teaching-oriented explanations: matches the explanation style to grade level and textbook version.
These technologies have clear advantages in recognition and standardized steps, but their limitations are equally clear:
- Limited customization. Most mature solutions are delivered as finished applications or fixed APIs, making it hard for the product team to control explanation style, follow-up question strategy, and interaction details.
- Weak open-domain capability. Text-heavy word problems, cross-disciplinary problems, and custom teaching logic often fall outside what off-the-shelf engines can handle.
- Problem coverage must be verified item by item. Grade span, problem types, and language versions can all become boundaries, so you must sample-test against your own problem distribution before launch.
5. A Third Approach: A Dual-Engine Architecture
The two routes are not mutually exclusive. A more sensible division of labor is:
- Perception layer: formula recognition technology handles “understanding the problem,” converting images into formula markup language and text problem statements;
- Cognition layer: the general-purpose LLM handles “explaining the problem,” doing step planning, error cause analysis, multi-solution comparison, and follow-up responses;
- Execution layer: a symbolic computation engine handles “computing accurately,” taking on key calculations and answer verification to prevent the model from making mistakes in long-chain computation.
The inputs and outputs of all three must be unified as structured data rather than natural language. Example:
{"problem_id": "p-10086","input": {"text": "As shown, in triangle ABC, AB=AC, D is the midpoint of BC. Prove: AD is perpendicular to BC.","figure": {"type": "triangle", "params": {"vertices": ["A", "B", "C"], "midpoint": "D"}}},"recognition": {"source": "ocr","confidence": 0.94,"formula": "AB=AC,\\ AD\\perp BC"},"solution": {"steps": [{"index": 1, "text": "Connect AD", "figure": "fig1", "reason": "Construct an auxiliary line"},{"index": 2, "text": "In triangles ABD and ACD...", "reason": "Side-Side-Side (SSS)"}],"answer": "AD is perpendicular to BC","method": "Congruent triangles","verified_by": "rule_engine"},"hints": ["Think: what does it mean that D is the midpoint?"],"related": [{"type": "similar_problem", "ref": "q-2048"}]}
Example of the calling interface (for format reference only, not tied to any specific vendor API):
import jsonimport requestsdef solve_math(problem_id: str, image_bytes: bytes | None = None,text: str | None = None) -> dict:"""Call the unified solving gateway and return a structured solution."""payload = {"request_id": problem_id,"options": {"modality": "image" if image_bytes else "text","output": "structured", # Request structured output for easy downstream parsing"timeout_ms": 8000,"fallback": ["ocr_engine", "general_llm"]}}files = {"image": image_bytes} if image_bytes else Nonedata = None if files else {"text": text}resp = requests.post("/api/v1/math/solve", json=payload,files=files, data=data, timeout=15)resp.raise_for_status()result = resp.json()if result.get("recognition", {}).get("confidence", 1.0) < 0.8:result["need_review"] = True # Route low-confidence results to human review or a clarifying questionreturn result
6. Specialized Handling for Geometry Problems
Geometry is the touchstone for math learning tools. A four-step pipeline is recommended:
- Recognition and structuring. First decompose the figure into elements such as points, lines, angles, and circles, along with their positional relationships, forming an intermediate representation;
- Standardized geometry description. Use a unified geometry description language to express points, lines, circles, and constraints, serving as a common basis for both rendering and reasoning;
- Rendering and verification. A deterministic renderer converts the description into SVG, and a program verifies whether the figure matches the problem statement (for example, whether “midpoint,” “perpendicular,” and “tangent” hold);
- Aligning text explanation with the figure. The prompt requires the model to reference figure elements by number so that the explanation corresponds one-to-one with the figure:
You are a geometry explanation assistant. Please output in the following steps:1. List the known geometry elements of the problem (points, lines, angles, circles), labeled A, B, C, D;2. Output the geometry description: the coordinates of each point, the endpoints of each line segment, and the center and radius of each circle;3. If an auxiliary line is needed, state which two labeled points are connected and "why it can be drawn this way";4. Give a step-by-step proof, noting the basis for each step (theorem name or condition);5. Finally output a JSON result in the form {"figure": {...}, "steps": [...]}.It is forbidden to invent non-existent points or theorems; if conditions are insufficient, state this explicitly.
When a figure requires a change of viewpoint (such as an unfolded diagram of a solid), you can add a “view transformation” layer before rendering, projecting the 3D description into 2D parameters and then handing it to the same renderer, avoiding having the model judge line occlusion relationships itself.
7. System Integration: Layered Design and Engineering Details
To bring these capabilities into a product, a four-layer structure is typically used:
- Access layer: unified authentication, rate limiting, and request logging, adapting to different clients such as apps, mini programs, and web;
- Orchestration layer: selects the processing chain based on problem type and request type, for example “photo → OCR → solving → rendering → explanation”;
- Capability layer: formula recognition, LLM reasoning, symbolic computation, figure rendering, and content safety moderation;
- Support layer: caching, message queues, object storage, monitoring and alerting, and other foundational capabilities, for which general categories are available on cloud platforms such as Baidu AI Cloud.
A few key engineering points:
- Asynchronous execution. Solving and reasoning take a long time, so the access layer should return a task ID quickly, execute asynchronously via a message queue, and use callbacks or polling on completion to avoid long-connection timeouts;
- Result caching. Cache results keyed by the problem text and image fingerprint, so repeated problems can be reused directly, reducing call cost and latency;
- Fallback strategy. When the main chain fails, try backup models in sequence, simplify the prompt, or return “needs human confirmation” to keep the service running;
- Observability. Log the time taken, recognition confidence, and human correction flags for each request, to help locate the problematic stage in the chain.
Example orchestration code:
def math_pipeline(task):if task["type"] == "image":ocr = ocr_service.recognize(task["image"]) # Formula/handwriting recognitionproblem = {"text": ocr["text"], "formula": ocr["formula"]}else:problem = {"text": task["text"], "formula": None}solution = solver.solve(problem) # Step-by-step reasoning + structured outputfigure = renderer.render(solution["figure"]) # Deterministic rendering to produce SVGsolution["answer"] = verifier.check(solution) # Symbolic verification of key resultsif solution["need_review"]:task_queue.send("human_review", solution) # Route low-confidence cases to human reviewstore.put(task["request_id"], solution) # Persist results for reuse and auditingreturn solution
8. Reasoning Quality and Controllability Design
The correctness of long-chain reasoning depends on three engineering measures:
- Structured output constraints. Require the model to output steps, bases, and the final answer according to a fixed JSON Schema, and automatically retry with an error message attached when parsing fails;
- Self-verification of results. Recheck computable intermediate quantities (equation solutions, areas, angles) with a symbolic computation engine, and fall back to recomputation when inconsistencies are found;
- Grade-specific prompts. Elementary problems should avoid methods beyond the curriculum, while high school problems may use tools such as vectors and trigonometry. The prompt should explicitly state the grade level and textbook scope.
For content safety, the focus in math scenarios is “not going beyond the explanation”: avoid giving extended content unrelated to the problem, avoid inappropriate guidance toward minors, and add moderation and age-appropriateness policies when necessary.
9. Evaluation Framework: Let Data Drive Selection
Selection should not rely on impressions. A three-layer evaluation is recommended:
- Dataset: sample by problem type (algebra, geometry, word problems, probability and statistics), input method (text, printed image, handwritten image), and difficulty level, covering real user scenarios;
- Metrics: recognition accuracy, final answer accuracy, step completeness, geometry figure consistency, average time to first token, cost per call, and human correction rate;
- Process: evaluate offline first, then run a small-traffic canary, then roll out fully; run regression tests quarterly to prevent capability regression caused by model upgrades.
Example evaluation code:
def evaluate(results):total = len(results)metrics = {"answer_accuracy": sum(r["answer_correct"] for r in results) / total,"step_completeness": sum(r["steps_complete"] for r in results) / total,"geometry_consistency": sum(r["figure_ok"] for r in results) / max(1, sum(1 for r in results if r["has_figure"])),"human_correction_rate": sum(r["need_review"] for r in results) / total,}return metrics
10. Conclusion and Implementation Recommendations
Selecting an AI-assisted math learning tool is essentially about finding a balance between “generalization” and “specialized precision.” For developers, five implementation recommendations:
- Define the business scope first: which grade levels, which problem types, and what interaction to present;
- Use recognition accuracy and step quality as two hard metrics for initial screening, rather than only looking at demo performance;
- Model geometry problems separately, using a chain of “structured description + programmatic rendering + numbered explanation”;
- Hand key calculations to a symbolic engine for verification, and let the model handle explanation and organization;
- Build a regression-capable evaluation set with monitoring and alerting, turning selection into a sustainable operational decision.
When the perception, cognition, and execution layers have clear divisions of labor, unified interfaces, and a closed evaluation loop, AI math capabilities can truly move from “usable in a demo” to “usable in teaching.”
